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