Search code examples
androidandroid-intentandroid-pendingintent

onReceive() is not called after sending PendingIntent


I want to receive the PendingIntent within the same Service class. I added a log in the onReceive method but it never shows in the LogCat.

AndroidManifest:

<service android:name=".UpdateService" android:exported="true">
  <intent-filter>
     <action android:name="monitoringStop" />
  </intent-filter>
</service>`

UpdateService:

public class UpdateService extends Service {
  public static final String BROADCAST_NAME = "monitoringStop";
  private BroadcastReceiver receiver = new BroadcastReceiver() {
    @Override
    public void onReceive(Context context, Intent intent) {
        //Never reached
    }
};

  @Override
  public int onStartCommand(Intent intent, int flags, int startId) {
    //registering        
    IntentFilter filter = new IntentFilter();
    filter.addAction(UpdateService.BROADCAST_NAME);
    registerReceiver(receiver, filter);

    //creating Intent + PendingIntent
    Intent stopIntent = new Intent(this, UpdateService.class);
    stopIntent.setAction(BROADCAST_NAME);
    PendingIntent pendingIntent = 
       PendingIntent.getBroadcast(this, 1, stopIntent, PendingIntent.FLAG_ONE_SHOT);

    //adding PendingIntent to action
    NotificationCompat.Action stopService 
         = new NotificationCompat.Action(R.drawable.stop, getString(R.string.stop), pendingIntent);

    NotificationCompat.Builder notificationBuilder 
         = new NotificationCompat.Builder(this)//settingText etc.
            .addAction(stopService);

    startForeground(1,notificationBuilder.build());
    return Service.START_STICKY;
  }
}

Solution

  • You should call stopIntent.setAction instead of intent.setAction.

    You do not need a Broadcast receiver inside your service. You can just call PedingIntent.getService and the onStartCommand method will be called. Inside this method you can react to the intent.