简体   繁体   English

应用程序销毁时,Android 服务终止

[英]Android Service is terminated when App destroyed

I'm trying to learn Android Service, I'm very noob.我正在尝试学习 Android 服务,我很菜鸟。 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.我正在尝试创建一个 NotificationService,下面是我刚刚尝试使用 Service 的代码。

Manifest:显现:

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

Starting Service via Button Click:通过按钮单击启动服务:

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

Service class MyService.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.我正在我的手机上查看其他服务正在运行的位置,当我终止该应用程序时,该服务也会终止。

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.否则,无论出于何种原因,Android 都不会重新启动您的应用程序。 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.尤其是小米、LG、华为的设备都有这个功能,其他手机也有。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM