简体   繁体   中英

Use of setComponent() when including extras with your intent in onReceive

I want to pass extras with my pending intent when I set an alarm to be picked up by my receiver in onReceive and then passed on as extras in my receive intent to be picked up by my scheduling service to be included in my notification.

Eg set an alarm to remind me to take a medicine with name 'x' in 'y' amount of time. I want the name 'x' to be displayed in the notification when the alarm is fired.

I found this answer very helpful.

However, in the Google Android sample project scheduler available from here , it advises that if your receiver intent includes extras that need to be passed along to the service, use setComponent() to indicate that the service should handle the receiver's intent:

ComponentName comp = new ComponentName(context.getPackageName(), 
           MyService.class.getName());

// This intent passed in this call will include the wake lock extra as well as
// the receiver intent contents.
startWakefulService(context, (intent.setComponent(comp)));

The answer I referenced does not do this.

Is it only required to use setComponent when the component from onReceive is a service and this is not required when the component is an activity?

Thanks, Sam.

However, in the Google Android sample project scheduler available from here, it advises that if your receiver intent includes extras that need to be passed along to the service, use setComponent() to indicate that the service should handle the receiver's intent:

Nothing related to this appears on the page that you linked to.

The answer I referenced does not do this.

Yes, it does. It sets the component via the Intent constructor.

Is it only required to use setComponent when the component from onReceive is a service and this is not required when the component is an activity?

Setting the component, whether via the constructor or setComponent() , is used to indicate that this is the component that should handle the operation, creating a so-called explicit Intent . If you do not set the component, then other criteria, like the action string and Uri , will be used to infer who should handle the operation (an implicit Intent ).

Generally speaking, where possible, use explicit Intent objects, with components that do not have an <intent-filter> , for maximum security.

The use of explicit versus implicit Intent objects has nothing directly to do with whether the component in question is an activity, a service, or a receiver.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM