Himanshu Babal Himanshu Babal - 4 months ago 23
Android Question

IntentService onHandleEvent( ) not starting

I want some methods to execute when I click on Notification Action Button.
I have searched on this site, but everything seems to be in order and my IntentService is not being called.

My Action-Button Intent

Intent off = new Intent();
off.setAction("action");
off.putExtra("test", "off");
PendingIntent pOff = PendingIntent.getService(context, 22, off, 0);


Notification Builder

NotificationCompat.Builder mBuilder = new NotificationCompat.Builder(context)
.setSmallIcon(/**/)
.setContentTitle(/**/)
.setContentText(/**/)
.addAction(/**/, "Off", pOff)
.setContentIntent(pendingIntent)
.setDefaults(Notification.DEFAULT_SOUND)
.setAutoCancel(true);


Intent Service Class

public class NotificationServiceClass extends IntentService {

public NotificationServiceClass(String name) {
super(name);
}

public NotificationServiceClass () {
super("NotificationServiceClass");
}

@Override
protected void onHandleIntent(Intent intent) {
Log.i("test", "onHandle");
if (intent.getAction().equals("action")) {
Log.i("test", "action");
Bundle bundle = intent.getExtras();
if (bundle != null) {
Log.i("test", "onHandleBundleNotNull");
if (bundle.containsKey("test")) {
Log.i("test", bundle.getString("test"));
}
}
}
}
}


XML Declaration for Service class

<service
android:name=".Manager.NotificationServiceClass"
android:exported="false">
</service>

Answer

Per the Intents and Intent Filters training, the Intent you've built is an implicit Intent:

Implicit intents do not name a specific component, but instead declare a general action to perform, which allows a component from another app to handle it. For example, if you want to show the user a location on a map, you can use an implicit intent to request that another capable app show a specified location on a map.

What you actually want is an explicit intent: one that specifies the component to start by name as per the note on the same page:

Note: When starting a Service, you should always specify the component name. Otherwise, you cannot be certain what service will respond to the intent, and the user cannot see which service starts.

When constructing your Intent, you should use

// Note how you explicitly name the class to use
Intent off = new Intent(context, NotificationServiceClass.class);
off.setAction("action");
off.putExtra("test", "off");
PendingIntent pOff = PendingIntent.getService(context, 22, off, 0);
Comments