【问题标题】:Can not dismiss notification of service created无法关闭已创建服务的通知
【发布时间】:2016-10-17 20:03:36
【问题描述】:

我已经创建了一个服务,并且我还创建了一个通知,所以当我的服务运行时会有一个通知。 现在,我希望用户能够滑动/关闭通知,但尝试这样做时遇到了两个问题:

@Override
public int onStartCommand(Intent intent, int flags, int startId) {

        password = intent.getStringExtra("password");
        number = intent.getStringExtra("number");


    Intent activityIntent = new Intent(this, MainActivity.class);
    PendingIntent pendingIntent =   PendingIntent.getActivity(getApplicationContext(), 0,
            activityIntent, PendingIntent.FLAG_UPDATE_CURRENT);


    Notification notification = new Notification.Builder(this).
            setContentTitle(getText(R.string.app_name)).
            setContentText("Subject").
            setContentInfo("Doing stuff in the background...").
            setSmallIcon(R.drawable.ic).
            setAutoCancel(true).
            setContentIntent(pendingIntent).build();

    startForeground(1, notification);


    return super.onStartCommand(intent, flags, startId);
}

这段代码运行得很好,唯一的问题是用户不能滑动关闭通知,所以通过搜索我发现我可以通过用'startForeground'函数替换它来修复它

    NotificationManager notificationManager =
            (NotificationManager) getSystemService(NOTIFICATION_SERVICE);
    notificationManager.notify(0,notification);

然后它起作用了,我可以滑动关闭,但现在我遇到了一个不同的问题,一旦我关闭我的应用程序(使用长按中间按钮然后关闭所有应用程序) 几分钟后,我的应用程序抛出了一个指向该行的空指针异常:

  password = intent.getStringExtra("password");

好像意图是空的。当我使用 startForeground 函数时不会发生这种情况

可能是什么问题?

【问题讨论】:

    标签: android android-studio service notifications


    【解决方案1】:

    在 onStartCommand() 中返回 START_NOT_STICKY。

    【讨论】:

      【解决方案2】:

      当服务在其中运行的进程崩溃时应该发生什么,有三个选项: START_STICKY、START_NOT_STICKY、START_REDELIVER_INTENT。 我想重新加载服务并在它崩溃后保持意图。 START_REDELIVER_INTENT 成功了,它重新启动服务并重新传递意图。 START_STICKY ,几乎成功了,对我来说 START_STICKY 的问题是它重新启动了服务,但意图为空。

      【讨论】:

      • 你是对的,但你没有在你的问题中提到你想重新启动你的服务,所以这就是我建议 START_NOT_STICKY 解决方案的原因。
      • 你说得对,对不起,我好像没提过。
      • 您所说的“服务在崩溃中运行的进程”是什么意思?为什么服务会崩溃??您的意思是 Android 操作系统因资源不足而终止服务吗??
      【解决方案3】:

      当服务仍在前台时,自动取消不起作用。先尝试从前台移除服务:

      startForeground(1, notification);
      stopForeground(false); //false - do not remove generated notification
      

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 1970-01-01
        • 2021-02-16
        • 1970-01-01
        • 2013-03-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 2011-10-08
        相关资源
        最近更新 更多