Search code examples
androidserviceandroid-broadcastreceiver

Background Service or Broadcast Receiver


It is an app locker application that I am working on. It locks all the apps in the android phone. What I want to do is that when a locked app is run in the android, my application should stop the app and display a password or pattern screen, if pattern is correct then it should run the app otherwise disable it. So, I wanted to ask that should I use background service to do that or should I use broadcast receiver? I don't know if the app sends broadcast when it runs for the first time? And if I use the background service, will it run when the android is restarted? I mean without running the application again? Please help me so that I can understand it well. Thank you.


Solution

  • Background service is probably the better choice for this type of requirements. And yes, you can make the background service start when the phone is restarted by using BroadcastReceiver. This is how:

    Make sure to have this permission:

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

    Then in application tag, have this receiver:

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

    Then finally, the BroadcastReceiver:

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

    This way, your service will start each time device reboots.

    Hope this helps.