Android Service is terminated when App destroyed

2019-07-30 01:30发布

问题:

I'm trying to learn Android Service, I'm very noob. I'm creating a service which will run even after the app is destroyed but when I terminate the App, the Service gets terminated too. I'm trying to make a NotificationService, below is my code that I just tried working with Service.

Manifest:

<service
        android:name="com.test.testworks.MyService"
        />

Starting Service via Button Click:

startService(new Intent(this, MyService.class));

Service class MyService.class:

public class MyService extends Service {

@Override
public void onCreate() {
    super.onCreate();
}

@Override
public int onStartCommand(Intent intent, int flags, int startId) {


    /* 1. *//*ScheduledExecutorService scheduleTaskExecutor = Executors.newScheduledThreadPool(5);

   // This schedule a runnable task every 2 minutes
    scheduleTaskExecutor.scheduleAtFixedRate(new Runnable() {
        public void run() {

        }
    }, 0, 10000, TimeUnit.SECONDS);*/


    /*  2. *//*final Handler handler = new Handler();
    handler.postDelayed(new Runnable() {
        public void run() {
            Toast.makeText(MyService.this, "suiubsibddubsuidv", Toast.LENGTH_LONG).show();
            handler.postDelayed(this, 10000); //now is every 2 minutes
        }
    }, 10000);*/


    return START_STICKY;

}

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

} 

I'm checking on my phone where the other Services are running and when I terminate the App, the Service terminates also.

回答1:

On some phones, you need to add your app explicitly to the list of apps that are allowed to run in the background. Otherwise, Android will not restart your app if it is killed for whatever reason. There should be a settings page which lists installed apps and allows you to add them to this list. It is called "protected apps" on some devices. Especially devices from Xiaomi, LG, Huawei have this feature, but also other phones.