Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Prevent a service from starting at startup

My broadcast receiver runs automatically when app starts.

How to prevent this? I want to start it on button click.

BroadCastReceiver:

public class TestAlarmReceiver extends BroadcastReceiver {

    @DebugLog
    @Override
    public void onReceive(Context context, Intent intent) {
        Intent i = new Intent(context, TestService.class);
        i.putExtra("foo", "bar");
        context.startService(i);
    }
}

IntentService:

public class TestService extends IntentService {

    public TestService() {
        super("TestService");
    }

    @DebugLog
    @Override
    protected void onHandleIntent(Intent intent) {
        Log.d(getClass().getSimpleName(), "Service is running");
    }
}

Also, I added these lines to AndroidManifest file inside application section:

    <receiver
        android:name=".service.TestAlarmReceiver"
        android:process=":remote" />

    <service
        android:name=".service.TestService"
        android:exported="false" />
like image 987
burjulius Avatar asked Nov 19 '25 07:11

burjulius


1 Answers

You should set android:enabled="false" (options for receiver) for your receiver on your manifest and then activate it using package Manager to enable it. Then you could write this function on the button click:

public void enableReceiver(Context context) {
    ComponentName component = new ComponentName(context, TestAlarmReceiver .class);
    PackageManager pm = context.getPackageManager();
    pm.setComponentEnabledSetting(
                component,
                PackageManager.COMPONENT_ENABLED_STATE_ENABLED,
                PackageManager.DONT_KILL_APP);
}

To stop the Receiver at runtime you only have to use the constant PackageManager.COMPONENT_ENABLED_STATE_DISABLED instead of PackageManager.COMPONENT_ENABLED_STATE_ENABLED.

I can't try it right now, but this should work.

like image 61
ex0ns Avatar answered Nov 20 '25 22:11

ex0ns