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 
17 package android.content;
18 
19 import android.annotation.Nullable;
20 import android.app.ActivityManager;
21 import android.app.ActivityManager.PendingIntentInfo;
22 import android.app.ActivityOptions;
23 import android.app.ActivityThread;
24 import android.app.IApplicationThread;
25 import android.compat.annotation.UnsupportedAppUsage;
26 import android.os.Bundle;
27 import android.os.Handler;
28 import android.os.IBinder;
29 import android.os.Parcel;
30 import android.os.Parcelable;
31 import android.os.RemoteException;
32 import android.os.UserHandle;
33 import android.util.AndroidException;
34 
35 /**
36  * A description of an Intent and target action to perform with it.
37  * The returned object can be
38  * handed to other applications so that they can perform the action you
39  * described on your behalf at a later time.
40  *
41  * <p>By giving a IntentSender to another application,
42  * you are granting it the right to perform the operation you have specified
43  * as if the other application was yourself (with the same permissions and
44  * identity).  As such, you should be careful about how you build the IntentSender:
45  * often, for example, the base Intent you supply will have the component
46  * name explicitly set to one of your own components, to ensure it is ultimately
47  * sent there and nowhere else.
48  *
49  * <p>A IntentSender itself is simply a reference to a token maintained by
50  * the system describing the original data used to retrieve it.  This means
51  * that, even if its owning application's process is killed, the
52  * IntentSender itself will remain usable from other processes that
53  * have been given it.  If the creating application later re-retrieves the
54  * same kind of IntentSender (same operation, same Intent action, data,
55  * categories, and components, and same flags), it will receive a IntentSender
56  * representing the same token if that is still valid.
57  *
58  * <p>Instances of this class can not be made directly, but rather must be
59  * created from an existing {@link android.app.PendingIntent} with
60  * {@link android.app.PendingIntent#getIntentSender() PendingIntent.getIntentSender()}.
61  */
62 public class IntentSender implements Parcelable {
63     @UnsupportedAppUsage
64     private final IIntentSender mTarget;
65     IBinder mWhitelistToken;
66 
67     // cached pending intent information
68     private @Nullable PendingIntentInfo mCachedInfo;
69 
70     /**
71      * Exception thrown when trying to send through a PendingIntent that
72      * has been canceled or is otherwise no longer able to execute the request.
73      */
74     public static class SendIntentException extends AndroidException {
SendIntentException()75         public SendIntentException() {
76         }
77 
SendIntentException(String name)78         public SendIntentException(String name) {
79             super(name);
80         }
81 
SendIntentException(Exception cause)82         public SendIntentException(Exception cause) {
83             super(cause);
84         }
85     }
86 
87     /**
88      * Callback interface for discovering when a send operation has
89      * completed.  Primarily for use with a IntentSender that is
90      * performing a broadcast, this provides the same information as
91      * calling {@link Context#sendOrderedBroadcast(Intent, String,
92      * android.content.BroadcastReceiver, Handler, int, String, Bundle)
93      * Context.sendBroadcast()} with a final BroadcastReceiver.
94      */
95     public interface OnFinished {
96         /**
97          * Called when a send operation as completed.
98          *
99          * @param IntentSender The IntentSender this operation was sent through.
100          * @param intent The original Intent that was sent.
101          * @param resultCode The final result code determined by the send.
102          * @param resultData The final data collected by a broadcast.
103          * @param resultExtras The final extras collected by a broadcast.
104          */
onSendFinished(IntentSender IntentSender, Intent intent, int resultCode, String resultData, Bundle resultExtras)105         void onSendFinished(IntentSender IntentSender, Intent intent,
106                 int resultCode, String resultData, Bundle resultExtras);
107     }
108 
109     private static class FinishedDispatcher extends IIntentReceiver.Stub
110             implements Runnable {
111         private final IntentSender mIntentSender;
112         private final OnFinished mWho;
113         private final Handler mHandler;
114         private Intent mIntent;
115         private int mResultCode;
116         private String mResultData;
117         private Bundle mResultExtras;
FinishedDispatcher(IntentSender pi, OnFinished who, Handler handler)118         FinishedDispatcher(IntentSender pi, OnFinished who, Handler handler) {
119             mIntentSender = pi;
120             mWho = who;
121             mHandler = handler;
122         }
performReceive(Intent intent, int resultCode, String data, Bundle extras, boolean serialized, boolean sticky, int sendingUser)123         public void performReceive(Intent intent, int resultCode, String data,
124                 Bundle extras, boolean serialized, boolean sticky, int sendingUser) {
125             mIntent = intent;
126             mResultCode = resultCode;
127             mResultData = data;
128             mResultExtras = extras;
129             if (mHandler == null) {
130                 run();
131             } else {
132                 mHandler.post(this);
133             }
134         }
run()135         public void run() {
136             mWho.onSendFinished(mIntentSender, mIntent, mResultCode,
137                     mResultData, mResultExtras);
138         }
139     }
140 
141     /**
142      * Perform the operation associated with this IntentSender, allowing the
143      * caller to specify information about the Intent to use and be notified
144      * when the send has completed.
145      *
146      * @param context The Context of the caller.  This may be null if
147      * <var>intent</var> is also null.
148      * @param code Result code to supply back to the IntentSender's target.
149      * @param intent Additional Intent data.  See {@link Intent#fillIn
150      * Intent.fillIn()} for information on how this is applied to the
151      * original Intent.  Use null to not modify the original Intent.
152      * @param onFinished The object to call back on when the send has
153      * completed, or null for no callback.
154      * @param handler Handler identifying the thread on which the callback
155      * should happen.  If null, the callback will happen from the thread
156      * pool of the process.
157      *
158      *
159      * @throws SendIntentException Throws CanceledIntentException if the IntentSender
160      * is no longer allowing more intents to be sent through it.
161      */
sendIntent(Context context, int code, Intent intent, OnFinished onFinished, Handler handler)162     public void sendIntent(Context context, int code, Intent intent,
163             OnFinished onFinished, Handler handler) throws SendIntentException {
164         sendIntent(context, code, intent, onFinished, handler, null, null /* options */);
165     }
166 
167     /**
168      * Perform the operation associated with this IntentSender, allowing the
169      * caller to specify information about the Intent to use and be notified
170      * when the send has completed.
171      *
172      * @param context The Context of the caller.  This may be null if
173      * <var>intent</var> is also null.
174      * @param code Result code to supply back to the IntentSender's target.
175      * @param intent Additional Intent data.  See {@link Intent#fillIn
176      * Intent.fillIn()} for information on how this is applied to the
177      * original Intent.  Use null to not modify the original Intent.
178      * @param onFinished The object to call back on when the send has
179      * completed, or null for no callback.
180      * @param handler Handler identifying the thread on which the callback
181      * should happen.  If null, the callback will happen from the thread
182      * pool of the process.
183      * @param requiredPermission Name of permission that a recipient of the PendingIntent
184      * is required to hold.  This is only valid for broadcast intents, and
185      * corresponds to the permission argument in
186      * {@link Context#sendBroadcast(Intent, String) Context.sendOrderedBroadcast(Intent, String)}.
187      * If null, no permission is required.
188      *
189      *
190      * @throws SendIntentException Throws CanceledIntentException if the IntentSender
191      * is no longer allowing more intents to be sent through it.
192      */
sendIntent(Context context, int code, Intent intent, OnFinished onFinished, Handler handler, String requiredPermission)193     public void sendIntent(Context context, int code, Intent intent,
194             OnFinished onFinished, Handler handler, String requiredPermission)
195             throws SendIntentException {
196         sendIntent(context, code, intent, onFinished, handler, requiredPermission,
197                 null /* options */);
198     }
199 
200     /**
201      * Perform the operation associated with this IntentSender, allowing the
202      * caller to specify information about the Intent to use and be notified
203      * when the send has completed.
204      *
205      * @param context The Context of the caller.  This may be null if
206      * <var>intent</var> is also null.
207      * @param code Result code to supply back to the IntentSender's target.
208      * @param intent Additional Intent data.  See {@link Intent#fillIn
209      * Intent.fillIn()} for information on how this is applied to the
210      * original Intent.  Use null to not modify the original Intent.
211      * @param onFinished The object to call back on when the send has
212      * completed, or null for no callback.
213      * @param handler Handler identifying the thread on which the callback
214      * should happen.  If null, the callback will happen from the thread
215      * pool of the process.
216      * @param requiredPermission Name of permission that a recipient of the PendingIntent
217      * is required to hold.  This is only valid for broadcast intents, and
218      * corresponds to the permission argument in
219      * {@link Context#sendBroadcast(Intent, String) Context.sendOrderedBroadcast(Intent, String)}.
220      * If null, no permission is required.
221      * @param options Additional options the caller would like to provide to modify the sending
222      * behavior.  May be built from an {@link ActivityOptions} to apply to an activity start.
223      *
224      * @throws SendIntentException Throws CanceledIntentException if the IntentSender
225      * is no longer allowing more intents to be sent through it.
226      * @hide
227      */
sendIntent(Context context, int code, Intent intent, OnFinished onFinished, Handler handler, String requiredPermission, @Nullable Bundle options)228     public void sendIntent(Context context, int code, Intent intent,
229             OnFinished onFinished, Handler handler, String requiredPermission,
230             @Nullable Bundle options)
231             throws SendIntentException {
232         try {
233             String resolvedType = intent != null ?
234                     intent.resolveTypeIfNeeded(context.getContentResolver())
235                     : null;
236             final IApplicationThread app = ActivityThread.currentActivityThread()
237                     .getApplicationThread();
238             int res = ActivityManager.getService().sendIntentSender(app, mTarget, mWhitelistToken,
239                     code, intent, resolvedType,
240                     onFinished != null
241                             ? new FinishedDispatcher(this, onFinished, handler)
242                             : null,
243                     requiredPermission, options);
244             if (res < 0) {
245                 throw new SendIntentException();
246             }
247         } catch (RemoteException e) {
248             throw new SendIntentException();
249         }
250     }
251 
252     /**
253      * @deprecated Renamed to {@link #getCreatorPackage()}.
254      */
255     @Deprecated
getTargetPackage()256     public String getTargetPackage() {
257         return getCreatorPackage();
258     }
259 
260     /**
261      * Return the package name of the application that created this
262      * IntentSender, that is the identity under which you will actually be
263      * sending the Intent.  The returned string is supplied by the system, so
264      * that an application can not spoof its package.
265      *
266      * @return The package name of the PendingIntent, or null if there is
267      * none associated with it.
268      */
getCreatorPackage()269     public String getCreatorPackage() {
270         return getCachedInfo().getCreatorPackage();
271     }
272 
273     /**
274      * Return the uid of the application that created this
275      * PendingIntent, that is the identity under which you will actually be
276      * sending the Intent.  The returned integer is supplied by the system, so
277      * that an application can not spoof its uid.
278      *
279      * @return The uid of the PendingIntent, or -1 if there is
280      * none associated with it.
281      */
getCreatorUid()282     public int getCreatorUid() {
283         return getCachedInfo().getCreatorUid();
284     }
285 
286     /**
287      * Return the user handle of the application that created this
288      * PendingIntent, that is the user under which you will actually be
289      * sending the Intent.  The returned UserHandle is supplied by the system, so
290      * that an application can not spoof its user.  See
291      * {@link android.os.Process#myUserHandle() Process.myUserHandle()} for
292      * more explanation of user handles.
293      *
294      * @return The user handle of the PendingIntent, or null if there is
295      * none associated with it.
296      */
getCreatorUserHandle()297     public UserHandle getCreatorUserHandle() {
298         int uid = getCachedInfo().getCreatorUid();
299         return uid > 0 ? new UserHandle(UserHandle.getUserId(uid)) : null;
300     }
301 
302     /**
303      * Comparison operator on two IntentSender objects, such that true
304      * is returned then they both represent the same operation from the
305      * same package.
306      */
307     @Override
equals(@ullable Object otherObj)308     public boolean equals(@Nullable Object otherObj) {
309         if (otherObj instanceof IntentSender) {
310             return mTarget.asBinder().equals(((IntentSender)otherObj)
311                     .mTarget.asBinder());
312         }
313         return false;
314     }
315 
316     @Override
hashCode()317     public int hashCode() {
318         return mTarget.asBinder().hashCode();
319     }
320 
321     @Override
toString()322     public String toString() {
323         StringBuilder sb = new StringBuilder(128);
324         sb.append("IntentSender{");
325         sb.append(Integer.toHexString(System.identityHashCode(this)));
326         sb.append(": ");
327         sb.append(mTarget != null ? mTarget.asBinder() : null);
328         sb.append('}');
329         return sb.toString();
330     }
331 
describeContents()332     public int describeContents() {
333         return 0;
334     }
335 
writeToParcel(Parcel out, int flags)336     public void writeToParcel(Parcel out, int flags) {
337         out.writeStrongBinder(mTarget.asBinder());
338     }
339 
340     public static final @android.annotation.NonNull Parcelable.Creator<IntentSender> CREATOR
341             = new Parcelable.Creator<IntentSender>() {
342         public IntentSender createFromParcel(Parcel in) {
343             IBinder target = in.readStrongBinder();
344             return target != null ? new IntentSender(target) : null;
345         }
346 
347         public IntentSender[] newArray(int size) {
348             return new IntentSender[size];
349         }
350     };
351 
352     /**
353      * Convenience function for writing either a IntentSender or null pointer to
354      * a Parcel.  You must use this with {@link #readIntentSenderOrNullFromParcel}
355      * for later reading it.
356      *
357      * @param sender The IntentSender to write, or null.
358      * @param out Where to write the IntentSender.
359      */
writeIntentSenderOrNullToParcel(IntentSender sender, Parcel out)360     public static void writeIntentSenderOrNullToParcel(IntentSender sender,
361             Parcel out) {
362         out.writeStrongBinder(sender != null ? sender.mTarget.asBinder()
363                 : null);
364     }
365 
366     /**
367      * Convenience function for reading either a Messenger or null pointer from
368      * a Parcel.  You must have previously written the Messenger with
369      * {@link #writeIntentSenderOrNullToParcel}.
370      *
371      * @param in The Parcel containing the written Messenger.
372      *
373      * @return Returns the Messenger read from the Parcel, or null if null had
374      * been written.
375      */
readIntentSenderOrNullFromParcel(Parcel in)376     public static IntentSender readIntentSenderOrNullFromParcel(Parcel in) {
377         IBinder b = in.readStrongBinder();
378         return b != null ? new IntentSender(b) : null;
379     }
380 
381     /** @hide */
382     @UnsupportedAppUsage
getTarget()383     public IIntentSender getTarget() {
384         return mTarget;
385     }
386 
387     /** @hide */
getWhitelistToken()388     public IBinder getWhitelistToken() {
389         return mWhitelistToken;
390     }
391 
392     /** @hide */
393     @UnsupportedAppUsage
IntentSender(IIntentSender target)394     public IntentSender(IIntentSender target) {
395         mTarget = target;
396     }
397 
398     /** @hide */
IntentSender(IIntentSender target, IBinder whitelistToken)399     public IntentSender(IIntentSender target, IBinder whitelistToken) {
400         mTarget = target;
401         mWhitelistToken = whitelistToken;
402     }
403 
404     /** @hide */
IntentSender(IBinder target)405     public IntentSender(IBinder target) {
406         mTarget = IIntentSender.Stub.asInterface(target);
407     }
408 
getCachedInfo()409     private PendingIntentInfo getCachedInfo() {
410         if (mCachedInfo == null) {
411             try {
412                 mCachedInfo = ActivityManager.getService().getInfoForIntentSender(mTarget);
413             } catch (RemoteException e) {
414                 throw e.rethrowFromSystemServer();
415             }
416         }
417 
418         return mCachedInfo;
419     }
420 }
421