如何使Android应用程序始终在后台运行? [英] How to make an android app to always run in background?

查看:1816
本文介绍了如何使Android应用程序始终在后台运行?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在使用Android设备.当我打开设置">应用程序">正在运行"时,屏幕左上角有一个选项可以查看:(1)运行进程(2)缓存的后台进程.我一直希望(24×7)运行的应用程序不幸地列在(2)缓存后台进程下,我希望将其列在(1)运行进程下(如果可能的话) ).能做到吗或简而言之,如何使android应用始终在后台运行?

I'm using an android device. When I open the Settings > Apps > Running, there is an option on the top-left of the screen to see : (1) Running processes (2) Cached background processes. And the app(s) which I wanted to run always (24×7) is/are unfortunately listed under (2) Cached background processes, which I wanted it/them to be listed under (1) Running processes (if it is possible). Can it be done? Or in short, how to make an android app to always run in background?

我希望我传达了这个问题:-)

I hope I conveyed the question :-)

推荐答案

您必须在Application类中启动服务才能始终运行它. 如果这样做,您的服务将始终处于运行状态.即使用户从任务管理器中终止了您的应用程序或强制停止了您的应用程序,它仍将重新开始运行.

You have to start a service in your Application class to run it always. If you do that, your service will be always running. Even though user terminates your app from task manager or force stop your app, it will start running again.

创建服务:

public class YourService extends Service {

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

    @Override
    public int onStartCommand(Intent intent, int flags, int startId) {
        // do your jobs here
        return super.onStartCommand(intent, flags, startId);
    }
}

创建一个Application类并启动您的服务:

Create an Application class and start your service:

public class App extends Application {

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

        startService(new Intent(this, YourService.class));
    }
}

添加名称"将属性分配给应用程序"您的AndroidManifest.xml标签

Add "name" attribute into the "application" tag of your AndroidManifest.xml

android:name=".App"

此外,别忘了将您的服务添加到应用程序"您的AndroidManifest.xml标签

Also, don't forget to add your service in the "application" tag of your AndroidManifest.xml

<service android:name=".YourService"/>

还有清单"中的此许可请求.标记(如果API级别为28或更高):

And also this permission request in the "manifest" tag (if API level 28 or higher):

<uses-permission android:name="android.permission.FOREGROUND_SERVICE"/>


更新

在Android Oreo之后,Google引入了一些背景限制.因此,上述解决方案可能行不通.当用户从任务管理器中杀死您的应用程序时,Android系统也会终止您的服务.如果要运行始终在后台运行的服务.您必须运行前台服务并显示正在进行的通知.因此,如下所示编辑您的服务.

After Android Oreo, Google introduced some background limitations. Therefore, this solution above won't work probably. When a user kills your app from task manager, Android System will kill your service as well. If you want to run a service which is always alive in the background. You have to run a foreground service with showing an ongoing notification. So, edit your service like below.

public class YourService extends Service {

    private static final int NOTIF_ID = 1;
    private static final String NOTIF_CHANNEL_ID = "Channel_Id";

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

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

        // do your jobs here

        startForeground();
        
        return super.onStartCommand(intent, flags, startId);
    }

    private void startForeground() {
        Intent notificationIntent = new Intent(this, MainActivity.class);

        PendingIntent pendingIntent = PendingIntent.getActivity(this, 0,
                notificationIntent, 0);

        startForeground(NOTIF_ID, new NotificationCompat.Builder(this, 
                NOTIF_CHANNEL_ID) // don't forget create a notification channel first
                .setOngoing(true)
                .setSmallIcon(R.drawable.ic_notification)
                .setContentTitle(getString(R.string.app_name))
                .setContentText("Service is running background")
                .setContentIntent(pendingIntent)
                .build());         
    }
}


受限OEMs

不幸的是,某些OEM(小米,OnePlus,三星,华为等)由于提供更长的电池寿命而限制了后台操作.这些OEM没有适当的解决方案.用户需要允许某些特定于OEM的特殊权限,或者需要通过设备设置将您的应用添加到列入白名单的应用列表中.您可以从 https://dontkillmyapp.com/中找到更多详细信息.

Unfortunately, some OEMs (Xiaomi, OnePlus, Samsung, Huawei etc.) restrict background operations due to provide longer battery life. There is no proper solution for these OEMs. Users need to allow some special permissions that are specific for OEMs or they need to add your app into whitelisted app list by device settings. You can find more detail information from https://dontkillmyapp.com/.

如果必须执行后台操作,则需要向用户解释您的功能为何不起作用以及他们如何通过允许这些权限来启用您的功能.我建议您按顺序使用AutoStarter库( https://github.com/judemanutd/AutoStarter )可以轻松地从您的应用中重定向有关权限页面的用户.

If background operations are an obligation for you, you need to explain it to your users why your feature is not working and how they can enable your feature by allowing those permissions. I suggest you to use AutoStarter library (https://github.com/judemanutd/AutoStarter) in order to redirect your users regarding permissions page easily from your app.

顺便说一句,如果您需要运行一些定期工作而不是进行连续的后台工作.您最好看看WorkManager( https://developer.android.com/topic/libraries/architecture/workmanager )

By the way, if you need to run some periodic work instead of having continuous background job. You better take a look WorkManager (https://developer.android.com/topic/libraries/architecture/workmanager)

这篇关于如何使Android应用程序始终在后台运行?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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