持续通知在几秒钟后消失

3

我想在服务启动时将通知放置在状态栏中,并保留在那里,直到我停止服务,但是它会在几秒钟后消失(约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);
}

你的服务是否因某些原因被销毁了?我在onDestroy中看到你删除了通知。你在哪里调用showNotification()函数? - petey
抱歉,在复制问题时我可能已经编辑掉了那一行。showNotification在onCreate中被调用。在onDestroy中显示的日志条目仅在使用stopService结束服务时显示,通知在大约10秒后就会消失,而服务仍在运行。 - Scott
应该补充说明,使用已弃用的setLatestEventInfo方法时,这个功能按预期工作,我正在尝试使用notification.builder进行重写。 - Scott
我似乎在这个通知中遇到了一些奇怪的行为。有时候通知会被创建在 USB 调试/USB 连接通知的左侧,而且当它被创建在那里时,它会一直存在,但有时候它会被创建在它们的右侧,然后在几秒钟后消失。虽然看起来相当随机。 - Scott
1个回答

3
我曾经也遇到过在新手机的ICS系统上,持续通知会消失的同样问题。应用和通知在我之前测试的所有Android版本上都完美地运行,甚至在一个ICS模拟器上也能正常工作。不用说这个问题困扰了我几个月,但最终我找到了答案。 http://code.google.com/p/android/issues/detail?id=21635 我使用一个BroadcastReceiver来监听手机上的来电情况,并在按钮被切换时以编程方式启用接收器并设置通知。因此我编写了一个小型测试应用程序,连接了相同的BroadcastReceiver,并成功地复制出了这个问题。当我注释掉setComponentEnabledSetting调用时,通知不再消失。

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接