我试图在服务启动时在状态栏中放置一个通知,并将其保持在状态栏中,直到我停止服务,但在几秒钟(大约10秒)后消失。关于我遗漏了什么有什么建议吗?在我尝试使用notification.builder重新编写与API15兼容的代码之前,这是有效的。日志条目显示只有在我停止服务后才会调用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);
}

最佳答案

我也有同样的问题,一个正在进行的通知消失在一个新手机的集成电路中。这个应用程序和通知在我之前测试过的每一个android版本中都运行得很好,甚至可以在ics模拟器上运行。不用说这已经让我疯狂了几个月了,但我终于找到了答案。
http://code.google.com/p/android/issues/detail?id=21635
我使用一个广播接收器来监视手机上的来电,并且除了设置通知之外,当切换按钮时,我还以编程方式启用接收器。所以我写了一个小的测试应用程序,把同一个广播接收器连接起来,就能重现这个问题。我注释掉了setcomponentenabledsetting调用,通知不再消失。

10-07 19:33
查看更多