Message.java revision a334e7c72408c4e2805f2427a35d841a60adefc4
1/*
2 * Copyright (C) 2006 The Android Open Source Project
3 *
4 * Licensed under the Apache License, Version 2.0 (the "License");
5 * you may not use this file except in compliance with the License.
6 * You may obtain a copy of the License at
7 *
8 *      http://www.apache.org/licenses/LICENSE-2.0
9 *
10 * Unless required by applicable law or agreed to in writing, software
11 * distributed under the License is distributed on an "AS IS" BASIS,
12 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
13 * See the License for the specific language governing permissions and
14 * limitations under the License.
15 */
16
17package android.os;
18
19import android.os.Bundle;
20import android.os.Parcel;
21import android.os.Parcelable;
22import android.util.TimeUtils;
23
24/**
25 *
26 * Defines a message containing a description and arbitrary data object that can be
27 * sent to a {@link Handler}.  This object contains two extra int fields and an
28 * extra object field that allow you to not do allocations in many cases.
29 *
30 * <p class="note">While the constructor of Message is public, the best way to get
31 * one of these is to call {@link #obtain Message.obtain()} or one of the
32 * {@link Handler#obtainMessage Handler.obtainMessage()} methods, which will pull
33 * them from a pool of recycled objects.</p>
34 */
35public final class Message implements Parcelable {
36    /**
37     * User-defined message code so that the recipient can identify
38     * what this message is about. Each {@link Handler} has its own name-space
39     * for message codes, so you do not need to worry about yours conflicting
40     * with other handlers.
41     */
42    public int what;
43
44    /**
45     * arg1 and arg2 are lower-cost alternatives to using
46     * {@link #setData(Bundle) setData()} if you only need to store a
47     * few integer values.
48     */
49    public int arg1;
50
51    /**
52     * arg1 and arg2 are lower-cost alternatives to using
53     * {@link #setData(Bundle) setData()} if you only need to store a
54     * few integer values.
55     */
56    public int arg2;
57
58    /**
59     * An arbitrary object to send to the recipient.  When using
60     * {@link Messenger} to send the message across processes this can only
61     * be non-null if it contains a Parcelable of a framework class (not one
62     * implemented by the application).   For other data transfer use
63     * {@link #setData}.
64     *
65     * <p>Note that Parcelable objects here are not supported prior to
66     * the {@link android.os.Build.VERSION_CODES#FROYO} release.
67     */
68    public Object obj;
69
70    /**
71     * Optional Messenger where replies to this message can be sent.  The
72     * semantics of exactly how this is used are up to the sender and
73     * receiver.
74     */
75    public Messenger replyTo;
76
77    /** If set message is in use */
78    /*package*/ static final int FLAG_IN_USE = 1;
79
80    /** Flags reserved for future use (All are reserved for now) */
81    /*package*/ static final int FLAGS_RESERVED = ~FLAG_IN_USE;
82
83    /** Flags to clear in the copyFrom method */
84    /*package*/ static final int FLAGS_TO_CLEAR_ON_COPY_FROM = FLAGS_RESERVED | FLAG_IN_USE;
85
86    /*package*/ int flags;
87
88    /*package*/ long when;
89
90    /*package*/ Bundle data;
91
92    /*package*/ Handler target;
93
94    /*package*/ Runnable callback;
95
96    // sometimes we store linked lists of these things
97    /*package*/ Message next;
98
99    private static Object mPoolSync = new Object();
100    private static Message mPool;
101    private static int mPoolSize = 0;
102
103    private static final int MAX_POOL_SIZE = 10;
104
105    /**
106     * Return a new Message instance from the global pool. Allows us to
107     * avoid allocating new objects in many cases.
108     */
109    public static Message obtain() {
110        synchronized (mPoolSync) {
111            if (mPool != null) {
112                Message m = mPool;
113                mPool = m.next;
114                m.next = null;
115                return m;
116            }
117        }
118        return new Message();
119    }
120
121    /**
122     * Same as {@link #obtain()}, but copies the values of an existing
123     * message (including its target) into the new one.
124     * @param orig Original message to copy.
125     * @return A Message object from the global pool.
126     */
127    public static Message obtain(Message orig) {
128        Message m = obtain();
129        m.what = orig.what;
130        m.arg1 = orig.arg1;
131        m.arg2 = orig.arg2;
132        m.obj = orig.obj;
133        m.replyTo = orig.replyTo;
134        if (orig.data != null) {
135            m.data = new Bundle(orig.data);
136        }
137        m.target = orig.target;
138        m.callback = orig.callback;
139
140        return m;
141    }
142
143    /**
144     * Same as {@link #obtain()}, but sets the value for the <em>target</em> member on the Message returned.
145     * @param h  Handler to assign to the returned Message object's <em>target</em> member.
146     * @return A Message object from the global pool.
147     */
148    public static Message obtain(Handler h) {
149        Message m = obtain();
150        m.target = h;
151
152        return m;
153    }
154
155    /**
156     * Same as {@link #obtain(Handler)}, but assigns a callback Runnable on
157     * the Message that is returned.
158     * @param h  Handler to assign to the returned Message object's <em>target</em> member.
159     * @param callback Runnable that will execute when the message is handled.
160     * @return A Message object from the global pool.
161     */
162    public static Message obtain(Handler h, Runnable callback) {
163        Message m = obtain();
164        m.target = h;
165        m.callback = callback;
166
167        return m;
168    }
169
170    /**
171     * Same as {@link #obtain()}, but sets the values for both <em>target</em> and
172     * <em>what</em> members on the Message.
173     * @param h  Value to assign to the <em>target</em> member.
174     * @param what  Value to assign to the <em>what</em> member.
175     * @return A Message object from the global pool.
176     */
177    public static Message obtain(Handler h, int what) {
178        Message m = obtain();
179        m.target = h;
180        m.what = what;
181
182        return m;
183    }
184
185    /**
186     * Same as {@link #obtain()}, but sets the values of the <em>target</em>, <em>what</em>, and <em>obj</em>
187     * members.
188     * @param h  The <em>target</em> value to set.
189     * @param what  The <em>what</em> value to set.
190     * @param obj  The <em>object</em> method to set.
191     * @return  A Message object from the global pool.
192     */
193    public static Message obtain(Handler h, int what, Object obj) {
194        Message m = obtain();
195        m.target = h;
196        m.what = what;
197        m.obj = obj;
198
199        return m;
200    }
201
202    /**
203     * Same as {@link #obtain()}, but sets the values of the <em>target</em>, <em>what</em>,
204     * <em>arg1</em>, and <em>arg2</em> members.
205     *
206     * @param h  The <em>target</em> value to set.
207     * @param what  The <em>what</em> value to set.
208     * @param arg1  The <em>arg1</em> value to set.
209     * @param arg2  The <em>arg2</em> value to set.
210     * @return  A Message object from the global pool.
211     */
212    public static Message obtain(Handler h, int what, int arg1, int arg2) {
213        Message m = obtain();
214        m.target = h;
215        m.what = what;
216        m.arg1 = arg1;
217        m.arg2 = arg2;
218
219        return m;
220    }
221
222    /**
223     * Same as {@link #obtain()}, but sets the values of the <em>target</em>, <em>what</em>,
224     * <em>arg1</em>, <em>arg2</em>, and <em>obj</em> members.
225     *
226     * @param h  The <em>target</em> value to set.
227     * @param what  The <em>what</em> value to set.
228     * @param arg1  The <em>arg1</em> value to set.
229     * @param arg2  The <em>arg2</em> value to set.
230     * @param obj  The <em>obj</em> value to set.
231     * @return  A Message object from the global pool.
232     */
233    public static Message obtain(Handler h, int what,
234            int arg1, int arg2, Object obj) {
235        Message m = obtain();
236        m.target = h;
237        m.what = what;
238        m.arg1 = arg1;
239        m.arg2 = arg2;
240        m.obj = obj;
241
242        return m;
243    }
244
245    /**
246     * Return a Message instance to the global pool.  You MUST NOT touch
247     * the Message after calling this function -- it has effectively been
248     * freed.
249     */
250    public void recycle() {
251        synchronized (mPoolSync) {
252            if (mPoolSize < MAX_POOL_SIZE) {
253                clearForRecycle();
254
255                next = mPool;
256                mPool = this;
257            }
258        }
259    }
260
261    /**
262     * Make this message like o.  Performs a shallow copy of the data field.
263     * Does not copy the linked list fields, nor the timestamp or
264     * target/callback of the original message.
265     */
266    public void copyFrom(Message o) {
267        this.flags = o.flags & ~FLAGS_TO_CLEAR_ON_COPY_FROM;
268        this.what = o.what;
269        this.arg1 = o.arg1;
270        this.arg2 = o.arg2;
271        this.obj = o.obj;
272        this.replyTo = o.replyTo;
273
274        if (o.data != null) {
275            this.data = (Bundle) o.data.clone();
276        } else {
277            this.data = null;
278        }
279    }
280
281    /**
282     * Return the targeted delivery time of this message, in milliseconds.
283     */
284    public long getWhen() {
285        return when;
286    }
287
288    public void setTarget(Handler target) {
289        this.target = target;
290    }
291
292    /**
293     * Retrieve the a {@link android.os.Handler Handler} implementation that
294     * will receive this message. The object must implement
295     * {@link android.os.Handler#handleMessage(android.os.Message)
296     * Handler.handleMessage()}. Each Handler has its own name-space for
297     * message codes, so you do not need to
298     * worry about yours conflicting with other handlers.
299     */
300    public Handler getTarget() {
301        return target;
302    }
303
304    /**
305     * Retrieve callback object that will execute when this message is handled.
306     * This object must implement Runnable. This is called by
307     * the <em>target</em> {@link Handler} that is receiving this Message to
308     * dispatch it.  If
309     * not set, the message will be dispatched to the receiving Handler's
310     * {@link Handler#handleMessage(Message Handler.handleMessage())}.
311     */
312    public Runnable getCallback() {
313        return callback;
314    }
315
316    /**
317     * Obtains a Bundle of arbitrary data associated with this
318     * event, lazily creating it if necessary. Set this value by calling
319     * {@link #setData(Bundle)}.  Note that when transferring data across
320     * processes via {@link Messenger}, you will need to set your ClassLoader
321     * on the Bundle via {@link Bundle#setClassLoader(ClassLoader)
322     * Bundle.setClassLoader()} so that it can instantiate your objects when
323     * you retrieve them.
324     * @see #peekData()
325     * @see #setData(Bundle)
326     */
327    public Bundle getData() {
328        if (data == null) {
329            data = new Bundle();
330        }
331
332        return data;
333    }
334
335    /**
336     * Like getData(), but does not lazily create the Bundle.  A null
337     * is returned if the Bundle does not already exist.  See
338     * {@link #getData} for further information on this.
339     * @see #getData()
340     * @see #setData(Bundle)
341     */
342    public Bundle peekData() {
343        return data;
344    }
345
346    /**
347     * Sets a Bundle of arbitrary data values. Use arg1 and arg1 members
348     * as a lower cost way to send a few simple integer values, if you can.
349     * @see #getData()
350     * @see #peekData()
351     */
352    public void setData(Bundle data) {
353        this.data = data;
354    }
355
356    /**
357     * Sends this Message to the Handler specified by {@link #getTarget}.
358     * Throws a null pointer exception if this field has not been set.
359     */
360    public void sendToTarget() {
361        target.sendMessage(this);
362    }
363
364    /*package*/ void clearForRecycle() {
365        flags = 0;
366        what = 0;
367        arg1 = 0;
368        arg2 = 0;
369        obj = null;
370        replyTo = null;
371        when = 0;
372        target = null;
373        callback = null;
374        data = null;
375    }
376
377    /*package*/ boolean isInUse() {
378        return ((flags & FLAG_IN_USE) == FLAG_IN_USE);
379    }
380
381    /*package*/ void markInUse() {
382        flags |= FLAG_IN_USE;
383    }
384
385    /** Constructor (but the preferred way to get a Message is to call {@link #obtain() Message.obtain()}).
386    */
387    public Message() {
388    }
389
390    public String toString() {
391        return toString(SystemClock.uptimeMillis());
392    }
393
394    String toString(long now) {
395        StringBuilder   b = new StringBuilder();
396
397        b.append("{ what=");
398        b.append(what);
399
400        b.append(" when=");
401        TimeUtils.formatDuration(when-now, b);
402
403        if (arg1 != 0) {
404            b.append(" arg1=");
405            b.append(arg1);
406        }
407
408        if (arg2 != 0) {
409            b.append(" arg2=");
410            b.append(arg2);
411        }
412
413        if (obj != null) {
414            b.append(" obj=");
415            b.append(obj);
416        }
417
418        b.append(" }");
419
420        return b.toString();
421    }
422
423    public static final Parcelable.Creator<Message> CREATOR
424            = new Parcelable.Creator<Message>() {
425        public Message createFromParcel(Parcel source) {
426            Message msg = Message.obtain();
427            msg.readFromParcel(source);
428            return msg;
429        }
430
431        public Message[] newArray(int size) {
432            return new Message[size];
433        }
434    };
435
436    public int describeContents() {
437        return 0;
438    }
439
440    public void writeToParcel(Parcel dest, int flags) {
441        if (callback != null) {
442            throw new RuntimeException(
443                "Can't marshal callbacks across processes.");
444        }
445        dest.writeInt(what);
446        dest.writeInt(arg1);
447        dest.writeInt(arg2);
448        if (obj != null) {
449            try {
450                Parcelable p = (Parcelable)obj;
451                dest.writeInt(1);
452                dest.writeParcelable(p, flags);
453            } catch (ClassCastException e) {
454                throw new RuntimeException(
455                    "Can't marshal non-Parcelable objects across processes.");
456            }
457        } else {
458            dest.writeInt(0);
459        }
460        dest.writeLong(when);
461        dest.writeBundle(data);
462        Messenger.writeMessengerOrNullToParcel(replyTo, dest);
463    }
464
465    private final void readFromParcel(Parcel source) {
466        what = source.readInt();
467        arg1 = source.readInt();
468        arg2 = source.readInt();
469        if (source.readInt() != 0) {
470            obj = source.readParcelable(getClass().getClassLoader());
471        }
472        when = source.readLong();
473        data = source.readBundle();
474        replyTo = Messenger.readMessengerOrNullFromParcel(source);
475    }
476}
477