【发布时间】:2017-01-30 11:11:44
【问题描述】:
我有一个服务,它下载数据,在一个单独的进程中运行(这样当应用程序关闭时它不会死/重新启动)并显示一个通知它的进度。如果用户滑动删除通知,我希望能够停止服务,但到目前为止还无法做到。相关代码如下:
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 捕获。但是,就目前而言,我什至无法滑动删除通知,而且我从来没有看到“下载取消”Toast...
【问题讨论】:
-
我认为您在使用
startForeground时遇到了平台限制:stackoverflow.com/questions/26576872/… -
根据官方文档:
Make this service run in the foreground, supplying the ongoing notification to be shown to the user while in this state.但是您可以创建一个待处理的 Intent,一旦单击触发实际停止服务的待处理 Intent 就关闭该服务 - 从而删除通知
标签: android notifications broadcastreceiver