d.m*_*ada 18 android android-service android-notifications
我正在创建一个前台服务,其中包含服务启动时通知栏中显示的通知.如果服务停止,通知将解除.我的问题是,当"清除所有通知"或解除通知(滑动)时,有没有办法停止服务?
更新以包括通知的实施:
public int onStartCommand(Intent intent, int flags, int startId)
{
Log.d(CLASS, "onStartCommand service started.");
if (getString(R.string.service_start_action) == intent.getAction())
{
Intent intentForeground = new Intent(this, ServiceMain.class)
.setFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP | Intent.FLAG_ACTIVITY_SINGLE_TOP);
PendingIntent pendIntent = PendingIntent.getActivity(getApplicationContext(), 0, intentForeground, 0);
Notification notification;
Notification.Builder builder = new Notification.Builder(getApplicationContext())
.setSmallIcon(android.R.drawable.btn_star)
.setTicker("Service started...")
.setContentIntent(pendIntent)
.setDefaults(Notification.DEFAULT_ALL)
.setOnlyAlertOnce(true)
.setOngoing(false);
notification = builder.build();
notification.flags |= Notification.FLAG_FOREGROUND_SERVICE;
startForeground(SERV_NOTIFY, notification);
player.start();
}
else
{
Log.d(CLASS, "onStartCommand unable to identify acition.");
}
return START_STICKY;
}
Run Code Online (Sandbox Code Playgroud)
Kev*_*Lee 26
不允许用户滑动正在进行的前台服务生成的通知.
因此,stopForeground(false)首先,其允许用户此后(至少在Lollipop +上)擦除通知.对于pre-Lollipop,您可能必须stopForeground(true)停止前景并删除通知,然后重新发出通知notificationManager.notify(yourNotificationID, yourNotificationObject),以便您的通知可见但可以滑动.
至关重要的是,设置具有删除意图的通知对象,该删除意图在用户将其滑动时触发.
(new NotificationCompat.builder(this).setDeleteIntent(deletePendingIntent)).build()
Run Code Online (Sandbox Code Playgroud)
在哪里deletePendingIntent是这样的
Intent deleteIntent = new Intent(this, YourService.class);
deleteIntent.putExtra(someKey, someIntValue);
PendingIntent deletePendingIntent = PendingIntent.getService(this,
someIntValue,
deleteIntent,
PendingIntent.FLAG_CANCEL_CURRENT);
Run Code Online (Sandbox Code Playgroud)
当用户将其滑动时,其额外的意图被传递给服务.手柄内交付额外的onStartCommand,即检查intent != null,intent.getExtras() != null,然后提取值从演员束定someKey,如果它匹配someIntValue,然后调用stopSelf().
我的问题是,有没有办法在“清除所有通知”或取消通知(滑动)时停止服务?
假设您的Notification设置,以允许它被清除,在deleteIntent当它被清除应该被调用。您可以将其设置为 a getBroadcast() PendingIntent,指向一个清单注册的BroadcastReceiver调用stopService().
该代码对我有用:
this.stopForeground(false);
mNotificationManager.cancel(NOTIFY_ID);
Run Code Online (Sandbox Code Playgroud)
并且您应该将返回值设置为onStartCommand,STRAT_STICKY将重新启动服务。
| 归档时间: |
|
| 查看次数: |
16900 次 |
| 最近记录: |