我试图在服务启动时在状态栏中放置一个通知,并将其保留在那里直到我停止该服务,但在几秒钟(大约 10 秒)后消失。关于我缺少什么的任何建议?这在我尝试使用 notification.builder 重新编写以与 api 15 兼容之前起作用。日志条目显示在我停止服务之前不会调用 onDestroy,因此它仍在运行。
public class MyService extends Service {
private NotificationManager mNM;
private int NOTIFICATION = R.string.service_started;
public void onCreate() {
super.onCreate();
mNM = (NotificationManager)getSystemService(NOTIFICATION_SERVICE);
showNotification();
}
@Override
public int onStartCommand(Intent intent, int flags, int startId) {
Log.e("MyService", "Service Started");
return START_STICKY;
}
@Override
public void onDestroy() {
super.onDestroy();
mNM.cancel(NOTIFICATION);
Log.e("MyService", "Service Ended");
}
@Override
public IBinder onBind(Intent intent) {
return mBinder;
}
private final IBinder mBinder = new LocalBinder();
private void showNotification() {
Notification.Builder builder = new Notification.Builder(getApplicationContext());
builder.setAutoCancel(false)
.setOngoing(true)
.setSmallIcon(R.drawable.myicon)
.setTicker(getText(R.string.service_label))
.setWhen(System.currentTimeMillis())
.setContentTitle(getText(R.string.service_started))
.setContentText(getText(R.string.service_label));
Notification notification = builder.getNotification();
mNM.notify(NOTIFICATION, notification);
}
最佳答案
我遇到了同样的问题,即在新手机上 ICS 中的持续通知消失了。该应用程序和通知在我之前测试过的每个 Android 版本中都运行良好,甚至可以在 ICS 模拟器上运行。不用说,这几个月来一直让我发疯,但我终于找到了答案。
http://code.google.com/p/android/issues/detail?id=21635
我正在使用 BroadcastReceiver 来监控手机上的来电,除了设置通知外,我还以编程方式在切换按钮时启用接收器。因此,我编写了一个连接了相同 BroadcastReceiver 的小型测试应用程序,并且能够重现该问题。我注释掉了 setComponentEnabledSetting 调用,通知不再消失。
关于android - 持续通知在几秒钟后消失,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/11146246/