且构网

分享程序员开发的那些事...
且构网 - 分享程序员编程开发的那些事

在android中设置关闭操作的关闭通知

更新时间:2023-02-26 21:43:38

如果你只是想从一个通知中停止一个 Service,你不需要打扰 Activity.

If you just want to stop a Service from a Notification, you don't need to bother Activity.

在服务中,定义关闭操作:

In a Service, define an action for closing:

private static final String ACTION_CLOSE = "ACTION_CLOSE";

// in setupNotification():

final Intent notificationIntent_Close = new Intent(this, TimerService.class);
notificationIntent_Close.setAction(ACTION_CLOSE); // use Action
PendingIntent closeIntent = PendingIntent.getService(this,
        1, notificationIntent_Close, PendingIntent.FLAG_UPDATE_CURRENT);

在服务中,处理动作

@Override
public int onStartCommand(final Intent intent, final int flags, 
            final int startId) {
    if (intent != null) {
        final String action = intent.getAction();
        if (action != null) {
            switch (action) {
                case ACTION_CLOSE:
                    stopSelf();
                    break;
            }
        }
    }
    return START_NOT_STICKY;
}

@Override
public void onDestroy() {
    super.onDestroy();
    notificationManager.cancel(0);
}