Search code examples
javaandroidservicebackground-process

Never Ending Background Service - Java for Android


I wanted to make this service a never ending service, even if the app is killed by the user. That service starts with the app - when it is background, the service still runs-, but when I clear the background tasks on phone, it is also killed. I wanted that final part to be different, wanted this service to keep running on the device... Is that possible? Thanks for the help

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();
}

}

Here is my Manifest file :

       <?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>


Solution

  • Never Ending Background Service is not possible but you can Limit Close Service

    cause this will Take More Battery which Not Allowed

    1- Use Forground Service

    this will make service to be run with Notification Like Music App

    2- Use START_STICKY

    this will make your service start when it Killed