无法从服务中滑动删除通知

时间:2017-01-30 11:11:45

标签: android notifications broadcastreceiver

我有一项服务,可以下载数据,在一个单独的过程中运行(这样当应用程序关闭时它就不会死/重启)并显示有关其进度的通知。我希望能够在用户滑动删除通知时停止服务,但到目前为止还无法执行此操作。相关代码如下:

DatabaseDownloadService.java

public class DatabaseDownloadService extends Service
{
    private final static int NOTIFICATION_ID = 1337;
    private final static String NOTIFICATION_DISMISSAL_TAG = "my_notification_dismissal_tag";
    private NotificationManager mNotificationManager;

    @Override
    public void onCreate()
    {
        super.onCreate();

        mNotificationManager = (NotificationManager) getSystemService(Context.NOTIFICATION_SERVICE);
        Notification notification = getNotification("Downloading database...");
        startForeground(NOTIFICATION_ID, notification);

        startDownloadingStuff();
    }

    private Notification getNotification(String text)
    {
        NotificationDismissedReceiver receiver = new NotificationDismissedReceiver();
        registerReceiver(receiver, new IntentFilter(NOTIFICATION_DISMISSAL_TAG));

        Intent intent = new Intent(this, NotificationDismissedReceiver.class);
        PendingIntent deleteIntent = PendingIntent.getBroadcast(this, NOTIFICATION_ID, intent, 0);

        return new NotificationCompat.Builder(this)
                .setSmallIcon(R.mipmap.ic_launcher)
                .setContentTitle("My Awesome App")
                .setContentText(text)
                .setDeleteIntent(deleteIntent)
                .build();
    }

    public class NotificationDismissedReceiver extends BroadcastReceiver
    {
        @Override
        public void onReceive(Context context, Intent intent)
        {
            int notificationId = intent.getExtras().getInt(NOTIFICATION_DISMISSAL_TAG);
            Toast.makeText(context, "Download cancelled", Toast.LENGTH_SHORT).show();

            // Do more logic stuff here once this works...
        }
    }
}

的AndroidManifest.xml

<application
    ... properties and activities go here...>

    <service
        android:name=".DatabaseDownloadService"
        android:process=":dds_process"
        android:enabled="true"/>

    <receiver
        android:name="com.myapp.DatabaseDownloadService$NotificationDismissedReceiver"
        android:exported="false"/>

</application>

据我所知,.setDeleteIntent()应该使通知刷卡可删除,然后发送广播,然后由我的NotificationDismissedReceiver捕获。但是,就目前而言,我甚至无法刷卡删除通知,而且我从未看到&#34;下载已取消&#34;吐司...

2 个答案:

答案 0 :(得分:0)

使用:

而不是使用startForeground()
NotificationManager notificationManager = (NotificationManager) getSystemService(Context.NOTIFICATION_SERVICE);
notificationManager.notify("tag", NOTIFICATION_ID, notification);

答案 1 :(得分:0)

您可以调用从前台停止服务,传递false表示不删除通知。对于Android N及更高版本,您还可以传递STOP_FOREGROUND_DETACH。

stopForeground(false);

之后,您也可以自己停止服务。

stopSelf();