3

I have made Android application which uses one background service. It works good, but if user reboot his device that my application will be stopped. How can I fix it, i.e. how can I restart my application after rebooting of device?

Andrew Barber
  • 39,603
  • 20
  • 94
  • 123
user1134602
  • 597
  • 1
  • 4
  • 11

1 Answers1

7

You can do this in following way :

Register a receiver which will be initiated when boot_completed and add the following permission in android :

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

and add following lines in manifest file:

<receiver android:name="com.test.check.MyReceiver">
            <intent-filter>
                 <action android:name="android.intent.action.BOOT_COMPLETED"></action>
            </intent-filter>
        </receiver>

                 <service android:name=".MyService">
                    <intent-filter>
                        <action android:name="com.test.check.MyService" />
                    </intent-filter>
                </service>

Now in the onReceive() method of MyReceiver start the service :

public class MyReceiver extends BroadcastReceiver {

    @Override
    public void onReceive(Context arg0, Intent arg1) {
        // TODO Auto-generated method stub


         Toast.makeText(arg0, "boot completed",Toast.LENGTH_LONG).show();

         Intent serviceIntent = new Intent("com.test.check.MyService");
         arg0.startService(serviceIntent);


    }
}

And now in onCreate method of the service launch the app you want using its package name :

Intent LaunchIntent = getPackageManager().getLaunchIntentForPackage("package.name");
            startActivity( LaunchIntent );

This will fulfill your requirement.

Dinesh Sharma
  • 11,533
  • 7
  • 42
  • 60