gpt4 book ai didi

Android 服务在启动后立即终止,尽管调用了 startForeground()

转载 作者:搜寻专家 更新时间:2023-11-01 08:12:49 30 4
gpt4 key购买 nike

我的 IntentService 有问题。每次我启动服务时,一旦服务空闲,就会调用 onDestroy() 方法。我将我的服务设置为在前台运行,尽管如此,该服务仍会立即被终止。我的应用程序中只有一项其他 Activity ,它没有调用 stopService()。

阅读开发人员文档给我的印象是调用 startForeground() 将允许您的服务持续存在,即使在空闲时也是如此,除非对内存有非常高的需求,或者我读错了吗?

我的代码如下:

public class FileMonitorService extends IntentService {
public int mNotifyId = 273;
public FileMonitorService(){
super("FileMonitorService");
}

@Override
protected void onHandleIntent(Intent arg0) {

}

@Override
public void onDestroy() {
Toast.makeText(this, getText(R.string.toast_service_stop), Toast.LENGTH_SHORT).show();
stopForeground(true);
super.onDestroy();
}

@Override
public int onStartCommand(Intent intent, int flags, int startId) {
Notification notification = new Notification(R.drawable.icon, getText(R.string.notification_short), System.currentTimeMillis());
notification.flags|=Notification.FLAG_NO_CLEAR;
Intent notificationIntent = new Intent(this, FileMonitorActivity.class);
PendingIntent pendingIntent = PendingIntent.getActivity(this, 0, notificationIntent, 0);
notification.setLatestEventInfo(this, getText(R.string.notification_short),getText(R.string.notification_long), pendingIntent);
startForeground(mNotifyId, notification);


Toast.makeText(this, getText(R.string.toast_service_start), Toast.LENGTH_SHORT).show();
return super.onStartCommand(intent, flags, startId);
}
}

最佳答案

您需要考虑使用常规 Service 而不是 IntentServiceIntentService 旨在在有工作要做时保持运行。完成 onStartCommand 方法后,它会尝试停止。

参见 docs :

Clients send requests through startService(Intent) calls; the service is started as needed, handles each Intent in turn using a worker thread, and stops itself when it runs out of work.

(强调我的)

关于Android 服务在启动后立即终止,尽管调用了 startForeground(),我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/8040460/

30 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com