服务在被系统终止后不会重新启动



告诉我,有人能遇到这样的问题吗。常规服务:

public class ContactChangeService extends Service {
public ContactChangeService() {
}
@Override
public void onCreate() {
super.onCreate();
}
@Override
public int onStartCommand(Intent intent, int flags, int startId) {

Intent notificationIntent = new Intent(this, MainActivity.class);
PendingIntent pendingIntent = PendingIntent.getActivity(this,
0, notificationIntent, 0);
Notification notification = new NotificationCompat.Builder(this, CONTACT_CHANGE_CHANNEL_ID)
.setContentTitle("itle")
.setSmallIcon(R.drawable.ic_black_list)
.setContentText("Message")
.setContentIntent(pendingIntent)
.build();
startForeground(1546644, notification);

return START_STICKY;
}
@Nullable
@Override
public IBinder onBind(Intent intent) {
return null;
}
@Override
public void onDestroy() {
super.onDestroy();
}}

这就是从一个片段启动服务的方式:

Intent serviceIntent = new Intent(getContext(), ContactChangeService.class);
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.O) {
ContextCompat.startForegroundService(getActivity(), serviceIntent);
} else {
getActivity().startService(serviceIntent);
}

为了清楚地了解该系统如何与服务协同工作,我选择了FinePower进行测试,它可能是内存量较小的最弱的智能手机。一个人只需要运行几个应用程序,RAM中的内存就会耗尽,服务就会被系统终止。但是,尽管onStartCommand中有START_SICKY值,但即使再次有足够的RAM,服务也不会再次启动。可能是什么问题?提前谢谢。

有些设备,尤其是低端设备,不允许应用程序在后台无限期运行(出于节省电池的目的(。即使您从onStartCommand()返回START_STICKY,这些设备也不会自动重新启动服务。通常在这些设备上,有一种方法可以手动将您的应用程序添加到";受保护的应用程序";或";允许在后台运行的应用程序";。一旦你将你的应用程序添加到此列表中,安卓系统将按照设计自动重新启动它。无法自动将您的应用程序添加到此列表,用户必须手动添加。通常在设置中有一种方法可以做到这一点;"功率管理"电池管理";,或";安全性";。我不知道你正在测试的设备,所以我不能告诉你在哪里可以找到设置。

有关更多信息,请参阅以下内容:

  • BroadcastReceiver工作一段时间,然后停止
  • "受保护的应用程序";华为手机上的设置,以及如何处理

最新更新