应用销毁后,Android服务终止 [英] Android Service is terminated when App destroyed

查看:308
本文介绍了应用销毁后,Android服务终止的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在尝试学习Android服务,我非常菜鸟.我正在创建一个服务,即使该应用程序被销毁后该服务也将运行,但是当我终止该应用程序时,该服务也会被终止.我正在尝试制作一个NotificationService,下面是我刚刚尝试使用Service的代码.

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.

清单:

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

通过按钮单击启动服务:

Starting Service via Button Click:

startService(new Intent(this, 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.

推荐答案

在某些手机上,您需要将应用明确添加到允许在后台运行的应用列表中.否则,如果出于任何原因将其杀死,Android将不会重新启动您的应用程序.应该有一个设置页面,其中列出了已安装的应用程序,并允许您将其添加到此列表中.在某些设备上,它被称为受保护的应用程序".尤其是来自小米,LG和华为的设备具有此功能,还有其他手机.

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.

这篇关于应用销毁后,Android服务终止的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆