Generally speaking it's not possible in Android to make your app to start automatically at bootup. But you can use a trick to achieve the same result.
Basically you have to register a BroadcastReceiver in your AndroidManifest.xml file to listen to the Intent.ACTION_BOOT_COMPLETED event. In your BroadcastReceiver class you can now start your app or Service.
This method is often used to start a Service to perform certain operations in the background (for example, to register an alarm clock).
Let's look at the code of the AndroidManifest.xml file:
<uses-permission android:name="android.permission.RECEIVE_BOOT_COMPLETED" />
...
<receiver android:enabled="true" android:name=".BootUpReceiver"
android:permission="android.permission.RECEIVE_BOOT_COMPLETED">
<intent-filter>
<action android:name="android.intent.action.BOOT_COMPLETED" />
<category android:name="android.intent.category.DEFAULT" />
</intent-filter>
</receiver>
Now, let's suppose that you want to start a Service at bootup. The code of our BroadcastReceiver is the following:
public class BootUpReceiver extends BroadcastReceiver{
@Override
public void onReceive(Context context, Intent intent) {
Intent i = new Intent(INTENT_ACTION);
i.putExtra...
[...]
context.startService(i);
}
}
Of course you have to use this code only when really needed: an app starting app every time the device is booting could possibly waste system's resources.
No comments:
Post a Comment