防止服务在 android 后重新启动

prevent service restarting in android

我尝试在我的 android 应用程序中使用服务,但我遇到了问题。当我在屏幕锁定服务 运行 并中断后按下转动 on/off 按钮时,看起来服务正在重新启动。这是我的代码:

public class MyService extends Service {
private static String TAG = "Service";

@Override
public void onCreate() {
  super.onCreate();
  Log.i(TAG, "onCreate");

}

@Override
public IBinder onBind(Intent intent) {
  return null;
}

@Override
public void onDestroy() {
  Log.i(TAG, "Destroyed");
  super.onDestroy();
}

@Override
public int onStartCommand(Intent intent, int flags, int startId) {
  Log.i(TAG, "OnStartcommmand");
  return START_STICKY;
 }

 }

为什么我的服务重启了很多次?我怎样才能防止服务重新启动?可能吗 ? 谢谢

您的 Service 被系统终止,以便为更高优先级的应用程序节省资源(例如:当 phone 内存不足时)。被杀后,您的 Service 可以根据 return 在 onStartCommand 上编辑的值重新创建。如果您 return START_STICKYonStartCommand 上,系统将在终止服务后重新创建您的服务。否则,START_NOT_STICKY 告诉 OS 不要再费心重新创建服务。

您可以考虑使用 startForeground 方法来保持您的 Service 存活。这是文档:

A started service can use the startForeground(int, Notification) API to put the service in a foreground state, where the system considers it to be something the user is actively aware of and thus not a candidate for killing when low on memory. (It is still theoretically possible for the service to be killed under extreme memory pressure from the current foreground application, but in practice this should not be a concern.)