75

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 always run in the background?

I hope I conveyed the question :-)

Saeed
  • 3,294
  • 5
  • 35
  • 52
Manuel
  • 885
  • 1
  • 7
  • 9
  • for new APIs you can use this trick ;) : https://stackoverflow.com/a/49878237/2201814 – MHSaffari Apr 17 '18 at 12:51
  • You can try creating a service. Here is the official documentation for doing that: [Link](https://developer.android.com/guide/components/services.html#Basics) – JP_ Jan 03 '16 at 03:46

3 Answers3

113

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.

Create a service:

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

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

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

android:name=".App"

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

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

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

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

UPDATE

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

EDIT: RESTRICTED OEMS

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/.

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.

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)

sembozdemir
  • 4,137
  • 3
  • 21
  • 30
  • 1
    Thank you. But, how to create a service? Is there an appropriate app for it? Sorry, bcoz I'm just a beginner.. Can u provide a step-by-step guide right from the beginning? – Manuel Jan 03 '16 at 04:08
  • 5
    Right click on **app** from project explorer (on the left in Android Studio). And then, **New >> Service >> Service** – sembozdemir Jan 03 '16 at 04:11
  • "Android Studio" is an app? – Manuel Jan 03 '16 at 04:27
  • 3
    Android studio is an IDE (Integrated Development Environment). You need to use that (or Eclipse IDE) to program Android apps. It is a program which runs on the desktop (Windows, Mac, or Linux). "App" is a folder within the project files which can be found in the Project Explorer on the left-hand side. Did I clear things up? – Anish Muthali Jul 15 '16 at 04:44
  • 5
    Your code got me moving in the right direction - and finally to a solution. **Thanks**, mate!! **@sembozdemir** – SilSur Mar 09 '18 at 13:55
  • 3
    @sembozdemir I have tried your solution with Android 8.1. It does not work. That is, once I "Force Stop" my app from the Settings app, the app does not auto restart, and I still need to manually restart the app. Which version of Android have you tested your solution with? My understanding is, once an app is stopped, its services with the same process should stop also, otherwise it's a design flaw. – jonathanzh Aug 13 '18 at 22:22
  • @sembozdemir, I know Google has been trying to push developers towards using the "jobScheduler()" method instead of services. Are foreground services still the best way to go about this if I want to create an app that runs in the background as a server? – Nactus Jan 17 '19 at 17:57
  • @jonathanzh that's because you didn't create notification channel. Here is a way you can create it https://stackoverflow.com/a/44524976/6009482 – Valgaal Jan 22 '19 at 19:26
  • 1
    @Nactus it depends on your needs. If you need to run your code in scheduled periods. You don't need a foreground service. (I guess Work Manager in Jetpack is the best way to do that) However, if you still need to run your code always in background (like listening clipboard, getting real-time locations), you need a foreground service. – sembozdemir Jan 23 '19 at 05:54
  • @Valgaal OK, I see now the "UPDATE" section of this answer has been added after my initial comment. This makes YourService a foreground service which will work for Android 8.0 and later. Thanks! – jonathanzh Jan 23 '19 at 20:41
  • If you set compileSdkVersion to 24 and targetSdkVersion to 26, the service will be allowed to run as a background process after the app is terminated (because of compileSdkVersion) and you will still be allowed to publish the app to Play Store (because of targetSdkVersion). – Henrik Solgaard Jan 24 '19 at 16:44
  • The notification still disappears every time I clear all running apps. – Taslim Oseni Mar 03 '19 at 14:53
  • @sembozdemir in that case from oreo run the service from BOOT_COMPLETE my app is crash ` this.startService(startIntent);`. – Mathan Chinna Mar 06 '19 at 07:11
  • @sembozdemir apparently Chinese phones kill background processes. I tried to implement the work manager but it gets killed immediately when the app is swiped from the recent screen. Also, if you get permission like IGNORE_BATTERY_OPTIMIZATIONS, still the scheduled works and jobs are killed after some time. I had to opt foreground service for this and ran the work from there and called the foreground service every time when the work was finished since foreground service was also getting killed after some time! – Anirudh Ganesh Jul 31 '20 at 02:09
  • 1
    @AnirudhGanesh yes, you are right. Unfortunately, there is an important issue with those OEMs. I added extra information and suggestions under my answer about this. – sembozdemir Aug 05 '20 at 11:10
  • @sembozdemir I tried it with WorkManager and no luck. It stops working after 12 hours. I'm looking for other alternatives. Will look for other methods and will update back here If I find anything. Leaving another link for setting up the app permissions: bitbucket.org/copluk/acr/issues/607 Try including this too as the instructions are quite straight forward. – Anirudh Ganesh Aug 05 '20 at 16:52
  • [Google and Samsung partner - Android 14 + One UI 6.0 - background services won't be randomly killed](https://www.androidpolice.com/google-samsung-partner-fix-android-biggest-annoyances/). However, this won't help with user swipe-killing an app. That action is a statement by user that the app should be fully stopped. Ultimately, the user is in control, not your app. By design. – ToolmakerSteve May 06 '23 at 22:14
4

On some mobiles like mine (MIUI Redmi 3) you can just add specific Application on list where application doesnt stop when you terminate applactions in Task Manager (It will stop but it will start again)

Just go to Settings>PermissionsAutostart

Tad
  • 49
  • 1
  • Yes, you are right. In some phones like Mi and Vivo, we have to change the settings and give the app special permission to run in background from the settings app. Even if you have made a service that auto-restarts when the app is closed, the service won't run until and unless you set permissions in the settings app of your phone. – Gaurav Bharti Jun 02 '18 at 10:19
  • can I ask for this permission from my app or will I have to tell the user to manually go and change the settings? – ColdSpike Jun 09 '18 at 10:17
0

In mi and vivo - Using the above solution is not enough. You must also tell the user to add permission manually. You can help them by opening the right location inside phone settings. Varies for different phone models.

H.D.
  • 49
  • 4