I'm trying to add action
in foreground service notification
. But action click never fired pending intent
. I tried two following approach.
1st Approach
Service
Intent stopActionIntent = new Intent(STOP_SERVICE);
PendingIntent pendingIntent = PendingIntent.getBroadcast(MyService.this, 0, stopActionIntent,0);
NotificationCompat.Builder builder = new NotificationCompat.Builder(this, CHANNEL_ID);
builder.addAction(0,"stop",pendingIntent);
Manifest
<receiver android:name="com.myproject.receivers.ServiceActionReceiver">
<intent-filter >
<action android:name="com.myproject.services.myservice.STOP_SERVICE"/>
</intent-filter>
</receiver>
Broadcast receiver
@Override
public void onReceive(Context context, Intent intent) {
if(intent != null && intent.getAction().equals(MyService.STOP_SERVICE)){
context.stopService(new Intent(context,MyService.class));
}
}
But broadcast receiver never called.
2nd Approach
service
if(intent != null && STOP_SERVICE.equals(intent.getAction())){
stopSelf();
return super.onStartCommand(intent,flags,startId);
}
else {
Intent stopActionIntent = new Intent(this,MyService.class);
stopActionIntent.setAction(STOP_SERVICE);
PendingIntent pendingIntent = PendingIntent.getActivity(MyService.this, 0, stopActionIntent,0);
NotificationCompat.Builder builder = new NotificationCompat.Builder(this, CHANNEL_ID);
builder.addAction(0,"stop",pendingIntent);
}
Neither approach is worked.
build.gradle
defaultConfig {
applicationId "com.myproject.project"
minSdkVersion 16
targetSdkVersion 27
versionCode 2
versionName "1.0.0"
testInstrumentationRunner "android.support.test.runner.AndroidJUnitRunner"
multiDexEnabled true
}
Note: Notification and action are visible.
Edit
Doesn't works on Android 8.0 or higher, other version works.
Try Below Code For Notification: