Android Can';t从服务中滑动删除通知
我有一个服务可以下载数据,在一个单独的进程中运行(这样当应用程序关闭时它不会死机/重新启动),并显示一个进度通知。如果用户刷卡删除了通知,我希望能够停止服务,但到目前为止还无法这样做。相关代码如下: DatabaseDownloadService.javaAndroid Can';t从服务中滑动删除通知,android,notifications,broadcastreceiver,Android,Notifications,Broadcastreceiver,我有一个服务可以下载数据,在一个单独的进程中运行(这样当应用程序关闭时它不会死机/重新启动),并显示一个进度通知。如果用户刷卡删除了通知,我希望能够停止服务,但到目前为止还无法这样做。相关代码如下: DatabaseDownloadService.java public class DatabaseDownloadService extends Service { private final static int NOTIFICATION_ID = 1337; private f
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()代替,使用:
您可以从前台调用停止服务,传递false表示不删除通知。对于安卓N和更高版本,您还可以通过STOP_FOREGROUND_DETACH
stopForeground(false);
之后,您也可以自己停止服务
stopSelf();
我认为您在使用
startForeground
时遇到了平台的限制:根据官方文档:让此服务在前台运行,提供要在此状态下显示给用户的正在进行的通知。
但您可以创建一个挂起的意图,在单击该意图时立即关闭该服务,并触发实际停止该服务的挂起意图-从而删除该通知我使用startForeground()的原因我希望即使用户关闭应用程序,服务也能继续运行。使用notify()将在应用程序关闭时重新启动服务,这不是我想要的行为。在生成通知时是否尝试显式设置setContinuous(false)?
stopSelf();