2

I require my app to be launched when the user turns on the smartphone and then keep it running in background. What are the prerequisites? And how can I make it possible? Thanks

Muhammad Maqsoodur Rehman
  • 33,681
  • 34
  • 84
  • 124

4 Answers4

3

Activity can't and shouldn't work in background. For background operations in Android you should use Service.

For more help check this link-

Running activity in the background

For starting Service on boot add following code-

Add permissions-

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

Add receiver-

<receiver
    android:name="com.<!your activity!>"
    android:permission="android.permission.RECEIVE_BOOT_COMPLETED" >
    <intent-filter>
        <action android:name="android.intent.action.BOOT_COMPLETED" />
    </intent-filter>
</receiver>

In your Activity class-

public class MyReceiver extends BroadcastReceiver {   
    @Override
    public void onReceive(Context context, Intent intent) {
    Intent myIntent = new Intent(context, YourService.class);
    context.startService(myIntent);
    }

For long-running background operations Service should be used.

Community
  • 1
  • 1
Kanwaljit Singh
  • 4,339
  • 2
  • 18
  • 21
2

To launch on device booted (in your manifest):

<receiver android:name="MyBroadcastReceiver">
        <intent-filter>
            <action android:name="android.intent.action.BOOT_COMPLETED"></action>
            <category android:name="android.intent.category.HOME"></category>
        </intent-filter>
</receiver>

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

To keep it running: I'm not sure whether that's possible since the user can stop the app from the settings menu...

Toon Borgers
  • 3,638
  • 1
  • 14
  • 22
1

You need to use a Service triggered by a BroadcastReceiver.

Add the permission

<uses-permission android:name="android.permission.RECEIVE_BOOT_COMPLETED">

The AAA BroacastReceiver checks when the boot is completed or when the device shuts down. The BroadcastReceiver is declared as:

    <receiver android:name="AAA">
        <intent-filter>
          <action android:name="android.intent.action.BOOT_COMPLETED"/> 
          <action android:name="android.intent.action.ACTION_SHUTDOWN"/>
          </intent-filter>
    </receiver>

Here is an implementation of the BroadcastReceiver

public class AAA extends BroadcastReceiver {

  @Override
  public void onReceive(Context context, Intent intent) {

    String action = intent.getAction();
    Intent i = new Intent(context, BackgroundService.class);
    if (action.equals(Intent.ACTION_BOOT_COMPLETED)) {

      // The boot is completed - > Start the service

      context.startService(i);


    } else if (action.equals(Intent.ACTION_SHUTDOWN)) {

      // The device is shutting down - Stop the service.
      context.stopService(i);
    }



  }


}

When the boot is completed correctly, the broadcast start the Service; whereas, the service is stop when the broadcast AAA is notified by the shutdown of the device.

The Service needs to be a sticky one (if the system kills it for memory needs, the system takes care to recreate as soon as possible). The task of the service needs to be implemented in a separate thread of the main thread of the service in order to avoid ANR. Here is an example:

public class BackgroundService extends Service {


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



    Thread t = new Thread(new Runnable() {
      @Override
      public void run() {
        // Task to perform in the background - NOT in the MAIN thread (No UI changes)

      }
    });


    t.start();


    // We want this service to continue running until it is explicitly
    // stopped, so return sticky.
    return START_STICKY;
  }

  @Override
  public IBinder onBind(Intent intent) {
    // TODO Auto-generated method stub
    return null;
  }


}
Dekra
  • 554
  • 5
  • 15
1

START BACKGROUND SERVICE/APPLICATION AFTER BOOT COMPLETES IN ANDROID

Add this lines in your manifest

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

<receiver android:enabled="true" android:name=".OnBootReceiver">

<intent-filter>
        <action android:name="android.intent.action.BOOT_COMPLETED" />
        <category android:name="android.intent.category.DEFAULT" />
</intent-filter>
</receiver> 

Your Manifest now look like this after adding above lines eg :

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

<application
 android:icon="@drawable/ic_launcher"
 android:label="@string/app_name" >
 <activity
    android:name=".MainActivity"
    android:label="@string/app_name" >
    <intent-filter>
        <action android:name="android.intent.action.MAIN" />

        <category android:name="android.intent.category.LAUNCHER" />
    </intent-filter>
</activity>


<service android:name=".MyBackgroundService" 
          android:label="@string/app_name"
          >
</service>

<receiver android:enabled="true" android:name=".OnBootReceiver">
 <intent-filter>
        <action android:name="android.intent.action.BOOT_COMPLETED" />
        <category android:name="android.intent.category.DEFAULT" />
 </intent-filter>
</receiver>
</application>

If you wanted to start a service after boot completes, use this class

import android.content.BroadcastReceiver;
import android.content.Context;
import android.content.Intent;
import android.content.SharedPreferences;
import android.preference.PreferenceManager;

public class OnBootReceiver extends BroadcastReceiver {

@Override
public void onReceive(Context context, Intent intent) {
    if (intent.getAction().equals("android.intent.action.BOOT_COMPLETED")) {
        SharedPreferences prefs = PreferenceManager.getDefaultSharedPreferences(context);
        if (prefs.getBoolean("AUTOSTART_SERVICE", false)) {
                context.startService(new Intent(context, MyBackgroundService.class));
        }
    }
 }
}

If you wanted to start your application itself after boot completes, use this class

import android.content.BroadcastReceiver;
import android.content.Context;
import android.content.Intent;
import android.content.SharedPreferences;
import android.preference.PreferenceManager;

public class OnBootReceiver extends BroadcastReceiver {

@Override
public void onReceive(Context context, Intent intent) {
    if (intent.getAction().equals("android.intent.action.BOOT_COMPLETED")) {
        SharedPreferences prefs = PreferenceManager.getDefaultSharedPreferences(context);
        if (prefs.getBoolean("AUTOSTART_APPLICATION", false)) {
            Intent mIntent = new Intent();
            mIntent.setClassName("com.example", "com.example.MainActivity");
            mIntent.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
            context.startActivity(mIntent);
        }
    }
 }
}

If you have a settings options to enable/disable this boot receivers then change the values of shared preference as below, or else you can remove the shared preferences from OnBootReceiver class

public void startAppOnBoot(Boolean start){
  SharedPreferences mPreferences = PreferenceManager.getDefaultSharedPreferences(context);
  SharedPreferences.Editor mEditor = mPreferences.edit();
  mEditor.putBoolean("AUTOSTART_APPLICATION", start);
  mEditor.commit();
}

public void startSerciceOnBoot(Boolean start){
  SharedPreferences mPreferences = PreferenceManager.getDefaultSharedPreferences(context);
  SharedPreferences.Editor mEditor= mPreferences.edit();
  mEditor.putBoolean("AUTOSTART_SERVICE", start);
  mEditor.commit();
}

if you need an example of Service in android please check this link : http://www.tutorialspoint.com/android/android_services.htm

Sujith
  • 7,543
  • 1
  • 28
  • 38