Search code examples
androidbroadcastreceiver

Stop notification from BroadcastReceiver


I am trying to stop service when user swipes the notification, I can detect the swipe but not able to stop service. Here is the below code. Swipe is detected and i got toast message in broadcast receiver but service is not stopping ,why ?

private void errorNotification( String order_id) {

    NotificationManager mNotificationManager = (NotificationManager) this.getSystemService(Context.NOTIFICATION_SERVICE);

    Bitmap bitmap = BitmapFactory.decodeResource(getResources(), R.drawable.app_favicon_inside);
    Intent intent = new Intent(this,SplashScreenAct.class);
    intent.addFlags(Intent.FLAG_ACTIVITY_SINGLE_TOP | Intent.FLAG_ACTIVITY_CLEAR_TOP);
    PendingIntent contentIntent = PendingIntent.getActivity(this, 0, intent, PendingIntent.FLAG_UPDATE_CURRENT);

    String message = "There seems to be a connection problem. Please check your network connection and try again";

    Intent intent2 = new Intent();
    intent2.setAction("com.kitchenvilla.stopnotification");
    PendingIntent eraseIntent = PendingIntent.getBroadcast(this.getApplicationContext(), 0, intent2, 0);

    Notification.Builder mBuilder = new Notification.Builder(this)
            .setSmallIcon(R.drawable.app_favicon)
            .setContentTitle("GingerBuds")
            .setLargeIcon(bitmap)
            .setSortKey(order_id)
            .setAutoCancel(true)
            .setContentIntent(contentIntent)
            .setDeleteIntent(eraseIntent)
            .setContentText(message);

    Notification notification ;

    if ( Build.VERSION.SDK_INT >= Build.VERSION_CODES.JELLY_BEAN) {
        notification = mBuilder.build();
    } else {
        notification = mBuilder.getNotification();
    }
//  notification.defaults |= Notification.DEFAULT_SOUND;
//  notification.defaults |= Notification.DEFAULT_VIBRATE;
    mNotificationManager.notify(Integer.parseInt(order_id), notification);
}

And BroadcastReceiver is

public class StopNotification extends BroadcastReceiver {
    @Override
    public void onReceive(Context context, Intent intent) {
        Log.d("swipe", "notification swiped event");
        Toast.makeText(context, "swipe detected", Toast.LENGTH_SHORT).show();
        context.stopService(new Intent(context,NotificationService.class));
    }
}

Solution

  • Try to unbind your Service if it's bound somewhere (e.g. in onStop method of an Activity).