无法从服务中滑动删除通知
Posted
tags:
篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了无法从服务中滑动删除通知相关的知识,希望对你有一定的参考价值。
我有一个下载数据的服务,在一个单独的进程中运行(这样当应用程序关闭时它不会死/重启)并显示一个通知,告诉它进度。我希望能够在用户滑动删除通知时停止服务,但到目前为止还无法执行此操作。相关代码如下:
database download service.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捕获。但是,就目前而言,我甚至无法刷卡删除通知,而且我从未看到“下载已取消”Toast ...
答案
而不是使用startForeground(),使用:
NotificationManager notificationManager = (NotificationManager) getSystemService(Context.NOTIFICATION_SERVICE);
notificationManager.notify("tag", NOTIFICATION_ID, notification);
另一答案
您可以调用从前台停止服务,传递false,意味着不删除通知。对于Android N及更高版本,您也可以传递STOP_FOREGROUND_DETACH。
stopForeground(false);
之后,您也可以自己停止服务。
stopSelf();
以上是关于无法从服务中滑动删除通知的主要内容,如果未能解决你的问题,请参考以下文章
当应用程序从后台删除时,Apple Push 通知不会在 ios 7 上传递