yyd*_*ydl 13 android android-service android-notifications
在我的应用程序中,我将我的服务放在前台,以防止它被使用:
startForeground(NOTIFY_ID, notification);
Run Code Online (Sandbox Code Playgroud)
这也向用户显示通知(这很棒).问题是以后我需要更新通知.所以我使用代码:
notification.setLatestEventInfo(getApplicationContext(), someString, someOtherString, contentIntent);
mNotificationManager.notify(NOTIFY_ID, notification);
Run Code Online (Sandbox Code Playgroud)
接下来的问题是:这样做是否会使服务脱离其特殊的前景状态?
在这个答案中,CommonsWare表明这种行为是可行的,但他不确定.那么有谁知道实际答案?
注意:我知道解决这个问题的一个简单方法是startForeground()每次我想要更新通知时重复调用.我想知道这种替代方案是否也有效.
Lor*_*rte 12
Android开发人员站点上的RandomMusicPlayer应用程序使用NotificationManager来更新前台服务的通知,因此保留前台状态的可能性非常大.
(请参阅MusicService.java类中的setUpAsForeground()和updateNotification().)
根据我的理解,如果您取消通知,该服务将停止作为前台服务,所以请记住这一点; 如果取消通知,则需要再次调用startForeground()以恢复服务的前台状态.
sli*_*n77 12
澄清这里所说的内容:
根据我的理解,如果您取消通知,该服务将停止作为前台服务,所以请记住这一点; 如果取消通知,则需要再次调用startForeground()以恢复服务的前台状态.
答案的这一部分表明可以通过使用持久性来删除a正在进行的Notification集合.这不是真的.通过使用删除正在进行的通知集是不可能的.ServiceNotificationManager.cancel()NotificationstartForeground()NotificationManager.cancel()
删除它的唯一方法是调用stopForeground(true),因此正在进行的通知被删除,其中当然也使得Service停止在前台.所以它实际上是另一种方式; 在Service不停止在前台,因为是Notification被取消,Notification只能通过停止取消Service在前台之中.
当然,人们可以立即致电startForeground(),以新的方式恢复国家Notification.如果必须再次显示自动收报机文本,您可能希望这样做的一个原因,因为它只会在第一次Notification显示时运行.
这种行为没有记录,我浪费了4个小时试图弄清楚为什么我无法删除Notification.有关此问题的更多信息:NotificationManager.cancel()对我不起作用
当您想通过startForeground()更新通知集时,只需构建一个新的通知,然后使用NotificationManager来通知它。
关键是要使用相同的通知ID。
更新通知不会将服务从前台状态中删除(只能通过调用stopForground来完成);
例:
private static final int notif_id=1;
@Override
public void onCreate (){
this.startForeground();
}
private void startForeground() {
startForeground(notif_id, getMyActivityNotification(""));
}
private Notification getMyActivityNotification(String text){
// The PendingIntent to launch our activity if the user selects
// this notification
CharSequence title = getText(R.string.title_activity);
PendingIntent contentIntent = PendingIntent.getActivity(this,
0, new Intent(this, MyActivity.class), 0);
return new Notification.Builder(this)
.setContentTitle(title)
.setContentText(text)
.setSmallIcon(R.drawable.ic_launcher_b3)
.setContentIntent(contentIntent).getNotification();
}
/**
this is the method that can be called to update the Notification
*/
private void updateNotification() {
String text = "Some text that will update the notification";
Notification notification = getMyActivityNotification(text);
NotificationManager mNotificationManager = (NotificationManager) getSystemService(Context.NOTIFICATION_SERVICE);
mNotificationManager.notify(notif_id, notification);
}
Run Code Online (Sandbox Code Playgroud)
| 归档时间: |
|
| 查看次数: |
7239 次 |
| 最近记录: |