Labels

Wednesday, June 22, 2011

Autostart Service on Device Boot

Reference: My life with Android :-): Autostarting services

It's possible to register your own application service for starting automatically when the device has been booted. You need this, for example, when you want to receive push events from a http server and want to inform the user as soon a new event occurs. The user doesn't have to start the activity manually before the service get started...

It's quite simple. First give your app the permission RECEIVE_BOOT_COMPLETED.
Next you need to register a BroadcastReveiver. We call it BootCompletedIntentReceiver.

Your Manifest.xml should now look like this:
<manifest xmlns:android="http://schemas.android.com/apk/res/android"
 package="com.jjoe64">
 <uses-permission android:name="android.permission.RECEIVE_BOOT_COMPLETED"/>
 <application>
  <receiver android:name=".BootCompletedIntentReceiver">
   <intent-filter>
    <action android:name="android.intent.action.BOOT_COMPLETED" />
   </intent-filter>
  </receiver>
  <service android:name=".BackgroundService"/>
 </application>
</manifest>

As the last step you have to implement the Receiver. This receiver just starts your background service.
package com.jjoe64;

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

import com.jjoe64.BackgroundService;

public class BootCompletedIntentReceiver extends BroadcastReceiver {
 @Override
 public void onReceive(Context context, Intent intent) {
  if ("android.intent.action.BOOT_COMPLETED".equals(intent.getAction())) {
   Intent pushIntent = new Intent(context, BackgroundService.class);
   context.startService(pushIntent);
  }
 }
}

That's all ;-)

14 comments:

  1. Thanks for posting this. Simple and easy to understand. Using this in a home automation project.

    ReplyDelete
  2. Hey. Thank you for your code

    I have tried to do so but starting an Activity:

    Intent pushIntent = new Intent(context, MainActivity.class);
    context.startActivity(pushIntent);

    But when my device has started up a system error occurs.

    Could you please help me out?

    ReplyDelete
  3. I have solved it :)

    Intent pushIntent = new Intent(context, MainActivity.class);
    pushIntent.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
    context.startActivity(pushIntent);

    ReplyDelete
  4. can you post your hello world example with auto run feature .please help me i stuck in code .

    ReplyDelete
  5. Hi Jonas Gehring, i have one question as soon as boot completes i have to call my activity so that part is working fine but in this process first mobile home screen is appearing then it is going to my activity. so there is a dealy happening in between, i want to start my activity as soon as boot completes dealy should not happen so how come we are going to acheive...


    thanks in advance.........

    ReplyDelete
  6. What is the code for com.jjoe64.BackgroundService ?
    Please help. I need to add this feature in my app urgently.

    ReplyDelete
  7. Thanks for the simple solution, it works as expected.
    How can I supply a preferences setting to deactivate autostart? Is is possible to unregister the receiver permanently during runtime?

    ReplyDelete
  8. @Peter Rosenberg

    To unregister a receiver created in the manifest use this code:



    ComponentName component = new ComponentName(getApplicationContext(), NetworkStateReceiver.class);

    getApplication().getPackageManager().setComponentEnabledSetting(component, PackageManager.COMPONENT_ENABLED_STATE_DISABLED, PackageManager.DONT_KILL_APP);

    Where NetworkStateReceiver is the name of the class that extends BroadcastReceiver

    ReplyDelete
  9. good one! thanks for sharing!!

    ReplyDelete
  10. Hi--
    I have following code in my BootUpReceiver. Its unable to start the application...fails while starting application on phone reboot. How can I debug/fix the problem.

    onReceiveMethod of BootUpReceiver has this line of code.


    Log.d(TAG,"Registering SMS BroadCast receiver");
    SMSReceiver mSMSreceiver = new SMSReceiver(nemesisManager);
    IntentFilter mIntentFilter = new IntentFilter();
    mIntentFilter.addAction("android.provider.Telephony.SMS_RECEIVED");
    context.registerReceiver(mSMSreceiver, mIntentFilter);
    Log.d(TAG,"Registered SMS BroadCast receiver");

    Log.d(TAG,"Registering PhoneStatechangeListener (to handle incoming call from bank)");
    TelephonyManager telephonyManager = (TelephonyManager) context.getSystemService(Context.TELEPHONY_SERVICE);
    telephonyManager.listen(new NemesisPhoneStateListener(nemesisManager), PhoneStateListener.LISTEN_CALL_STATE);
    Log.d(TAG,"Registered PhoneStatechangeListener (to handle incoming call)");

    Log.d(TAG,"Registering LocationChangeListener (to handle change in location)");
    LocationManager locationManager = (LocationManager) context.getSystemService(Context.LOCATION_SERVICE);
    locationManager.requestLocationUpdates(LocationManager.NETWORK_PROVIDER, MINIMUM_DISTANCE_TIME_UPDATE, MINIMUM_LOCATION_CHANGE, new NemesisLocationListener(nemesisManager));
    Log.d(TAG,"Registered LocationChangeListener (to handle change in location)");

    Log.d(TAG,"Registering PeriodicUpdater");
    Timer timer = new Timer();
    timer.scheduleAtFixedRate(new PeriodicUpdaterTask(nemesisManager),INITIAL_TIMER_DELAY_IN_MILLISECONDS,NEMESIS_UPDATE_FREQUENCY*1000);
    Log.d(TAG,"Registered PeriodicUpdater");

    Log.d(TAG,"Registering Connectivity Change Receiver ");
    //SMS event receiver
    ConnectivityChangeReceiver mConnectivityChangeReceiver = new ConnectivityChangeReceiver(nemesisManager);
    mIntentFilter = new IntentFilter();
    mIntentFilter.addAction("android.net.conn.CONNECTIVITY_CHANGE");
    context.registerReceiver(mConnectivityChangeReceiver, mIntentFilter);
    Log.d(TAG,"Registered Connectivity Change Receiver");


    I have all permission an AndroidManifest.xml.





















    Any suggestion/help really appreciated.

    ReplyDelete
  11. This comment has been removed by the author.

    ReplyDelete
  12. Hi--
    I have found out what is the problem.

    I am trying to register BroadCastReceiver (SMSReceiver and ConnectivityReceiver) inside another BroadCastReceiver. Can this be done in Android at all ?

    I would not like to go ahead with traditional way of registering Receivers in manifest files because it is not Runtime and more over I am exposing interface in my app to initialize the app. In initialisation of app....I am registering SMSReceiver as broadcast service.
    Log.d(TAG,"Registering SMS BroadCast receiver");
    SMSReceiver mSMSreceiver = new SMSReceiver(nemesisManager);
    IntentFilter mIntentFilter = new IntentFilter();
    mIntentFilter.addAction("android.provider.Telephony.SMS_RECEIVED");
    context.registerReceiver(mSMSreceiver, mIntentFilter);
    Log.d(TAG,"Registered SMS BroadCast receiver");

    Is there way to achieve this (registering BroadcastReceiver inside another one) ?

    Cheers,
    Prashanth

    ReplyDelete
  13. Is this still functional? Does it works with Android OS 4.x ??

    ReplyDelete