【问题标题】:Never Ending Background Service - Java for Android永无止境的后台服务 - 适用于 Android 的 Java
【发布时间】:2018-03-24 14:07:30
【问题描述】:

我想让这项服务成为永无止境的服务,即使应用程序被用户杀死。该服务从应用程序开始 - 当它是后台时,服务仍然运行 - 但是当我清除手机上的后台任务时,它也会被杀死。我希望最后一部分有所不同,希望该服务继续在设备上运行......这可能吗?感谢您的帮助

public class BackgroundService extends Service {

public static Runnable runnable = null;
public Context context = this;
public Handler handler = null;


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

@Override
public void onCreate() {
    final PackageManager manager = getPackageManager();



    //Packages instalados no dispositivo
    List<ApplicationInfo> packages = manager.getInstalledApplications(PackageManager.GET_META_DATA);
    for (ApplicationInfo info : packages) {
        Log.i("Info", "Installed package:" + info.packageName);
    }

    for (int i = 0; i < packages.size(); i++) {
        if(packages.get(i).sourceDir.startsWith("/data/app/")){
            //Non System Apps
            Log.i("Info", "Installed package /NON SYSTEM/:" + packages.get(i).packageName);

        }else{
            //system Apps
            Log.i("Info", "Installed package !/SYSTEM/!:" + packages.get(i).packageName);

        }}




    handler = new Handler();
    runnable = new Runnable() {
        public void run() {
            final ActivityManager am = (ActivityManager) getBaseContext().getSystemService(ACTIVITY_SERVICE);

            String currentApp ="";

           // The first in the list of RunningTasks is always the foreground task.
            if (android.os.Build.VERSION.SDK_INT >= android.os.Build.VERSION_CODES.LOLLIPOP) {
                UsageStatsManager usm = (UsageStatsManager) getSystemService(USAGE_STATS_SERVICE);
                long time = System.currentTimeMillis();
                List<UsageStats> appList = usm.queryUsageStats(UsageStatsManager.INTERVAL_DAILY,
                        time - 1000 * 1000, time);
                if (appList != null && appList.size() > 0) {
                    SortedMap<Long, UsageStats> mySortedMap = new TreeMap<Long, UsageStats>();
                    for (UsageStats usageStats : appList) {
                        mySortedMap.put(usageStats.getLastTimeUsed(),
                                usageStats);
                    }
                    if (mySortedMap != null && !mySortedMap.isEmpty()) {
                        currentApp = mySortedMap.get(
                                mySortedMap.lastKey()).getPackageName();
                    }
                }
            } else {
                ActivityManager.RunningTaskInfo foregroundTaskInfo = am.getRunningTasks(1).get(0);
                currentApp = foregroundTaskInfo.topActivity.getPackageName();
            }

            boolean ApiLigaIsRunning = false;

            if (currentApp.contains("maps")) {
                ApiLigaIsRunning = true;
                Log.i("CHOOSEN APP IS RUNNING ","YES!!!!!!!!!!!            " + currentApp);
                Handler handler2 = new Handler();
                final String finalCurrentApp = currentApp;
                handler2.postDelayed(new Runnable() {
                    public void run() {
                        Intent openMe = new Intent(getApplicationContext(), LoginActivity.class);
                        openMe.setFlags(Intent.FLAG_ACTIVITY_SINGLE_TOP | Intent.FLAG_ACTIVITY_NEW_TASK);
                        startActivity(openMe);
                        am.killBackgroundProcesses(finalCurrentApp);
                    }
                }, 200);

            }

            Toast.makeText(context, "Service is running", Toast.LENGTH_LONG).show();
            List<ActivityManager.RunningAppProcessInfo> appProcesses = am.getRunningAppProcesses();
            for(ActivityManager.RunningAppProcessInfo appProcess : appProcesses){
                if(appProcess.importance == ActivityManager.RunningAppProcessInfo.IMPORTANCE_FOREGROUND){
                    if (ApiLigaIsRunning == true)
                        Log.i("Foreground App ", appProcess.processName);
                    else
                        Log.i("Not Working! ", appProcess.processName);
                }

            handler.postDelayed(runnable,200);


            }
        }
    };

    handler.postDelayed(runnable, 200);
}







@Override
public void onDestroy() {
    Toast.makeText(this, "Service stopped", Toast.LENGTH_LONG).show();
}

}

这是我的清单文件:

       <?xml version="1.0" encoding="utf-8"?>
       <manifest xmlns:android="http://schemas.android.com/apk/res/android"
          xmlns:tools="http://schemas.android.com/tools"
           package="***************">
<uses-permission android:name="android.permission.INTERNET" />
<uses-permission android:name="android.permission.KILL_BACKGROUND_PROCESSES" />
<uses-permission android:name="android.permission.REAL_GET_TASKS" />
<uses-permission android:name="android.permission.GET_TASKS"/>
<uses-permission android:name="android.permission.RECEIVE_BOOT_COMPLETED" />
<uses-permission android:name="android.permission.GET_TOP_ACTIVITY_INFO"/>
<uses-permission android:name="android.permission.INSTANT_APP_FOREGROUND_SERVICE"/>
<uses-permission android:name="android.permission.PACKAGE_USAGE_STATS" tools:ignore="ProtectedPermissions" />



<application
    android:allowBackup="true"
    android:icon="@mipmap/icon"
    android:label="@string/app_name"
    android:theme="@style/AppTheme" >
<activity
    android:name=".LoginActivity"
    android:theme="@style/AppTheme.Dark">

    <intent-filter>
        <action android:name="android.intent.action.MAIN" />

        <category android:name="android.intent.category.LAUNCHER" />
    </intent-filter>
</activity>
    <service 
        android:name=".BackgroundService"
        android:exported="true"
        android:enabled="true"
        />

</application>

【问题讨论】:

  • 永无止境的后台服务?不可能。
  • I wanted to make this service a never ending service, even if the app is killed by the user - 如果进程终止,Service 终止。

标签: java android service background-process


【解决方案1】:

永无止境的后台服务是不可能的,但你可以限制关闭服务

因为这会消耗更多不允许的电池

1- 使用前台服务

这将使服务与 Notification Like Music App 一起运行

2- 使用 START_STICKY

这将使您的服务在被杀死时启动

【讨论】:

    【解决方案2】:

    Broadcoast Receiver 是可能的。但由于 Oreo (API 26),您只能使用 Job Scheduler 执行此操作。

    在大多数情况下,应用可以通过使用 JobScheduler 作业。这种方法让应用程序安排执行工作 当应用程序没有主动运行,但仍为系统提供 以不影响用户的方式安排这些作业的余地 经验。 Android 8.0 对 JobScheduler 进行了多项改进 这使得替换服务和广播接收器变得更容易 预定的作业。

    查看更多信息:https://developer.android.com/about/versions/oreo/background

    【讨论】:

      猜你喜欢
      • 2019-09-04
      • 1970-01-01
      • 1970-01-01
      • 2020-01-26
      • 1970-01-01
      • 1970-01-01
      • 2015-12-17
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多