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" />
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With