Android Service is terminated when App destroyed

a 夏天 提交于 2019-12-11 06:57:25

问题


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.



来源:https://stackoverflow.com/questions/41703717/android-service-is-terminated-when-app-destroyed

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!