停止BroadcastReceiver的通知

时间:2016-02-20 20:16:15

标签: android broadcastreceiver

我试图在用户滑动通知时停止服务,我可以检测到滑动但无法停止服务。这是下面的代码。检测到滑动,我在广播接收器中收到了吐司消息,但服务没有停止,为什么?

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);
}

而BroadcastReceiver是

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));
    }
}

2 个答案:

答案 0 :(得分:1)

尝试onStop您的服务,如果它绑定在某处(例如,在活动的{{1}}方法中)。

答案 1 :(得分:0)

使用此代码停止服务。

PackageManager pm = getPackageManager();
int flag = (PackageManager.COMPONENT_ENABLED_STATE_DISABLED);
ComponentName cn = new ComponentName(context, yourService.class);
pm.setComponentEnabledSetting(Cn, flag, PackageManager.DONT_KILL_APP);