Background Service or Broadcast Receiver

751 views Asked by At

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.

2

There are 2 answers

4
ᴛʜᴇᴘᴀᴛᴇʟ On BEST ANSWER

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.

0
squalle0nhart On

Use need add android.permission.PACKAGE_USAGE_STATS to manifest and if your android version is 5.0 and above run this code to request usage stat permission :

 Intent intent = new Intent(Settings.ACTION_USAGE_ACCESS_SETTINGS);
 startActivity(intent);