服务被系统杀死后不会重新启动

时间:2020-08-09 16:37:01

标签: android android-service

告诉我,任何人都可以遇到这样的问题。常规服务:

    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);
}

为了清楚地了解系统如何与服务一起工作,我选择进行测试,可能是功能最弱的智能手机,它带有少量RAM,FinePower。一个只能运行几个应用程序,RAM中的内存用完,服务被系统杀死。但是,尽管onStartCommand中具有START_STICKY值,但是即使再次有足够的RAM,该服务也不会再次启动。可能是什么问题呢?预先感谢。

1 个答案:

答案 0 :(得分:0)

有些设备(尤其是低端设备)不允许应用无限期地在后台运行(出于节省电池的目的)。即使您从START_STICKY返回onStartCommand(),这些设备也不会自动重启服务。通常,在这些设备上,可以通过手动方式将您的应用添加到“受保护的应用”列表或“允许在后台运行的应用”列表中。将您的应用添加到此列表后,Android将按照设计自动重启它。无法自动将您的应用添加到此列表,用户必须手动执行。通常,可以在“电源管理”,“电池管理”或“安全性”下的“设置”中执行此操作。我不知道您要测试的设备,因此无法确切告诉您在哪里可以找到设置。

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