Stop Android BroadCastReceiver - android

I'm using BroadcastReceiver class in android to get information about network change
using the following code:
class NetworkStatus extends BroadcastReceiver{
......
#Override
public void onReceive(Context context, Intent intent) {
}
public void startBroadCastReceiver()
{
}
public void StopBroadCastReceiver()
{
}
I want to stop the broadcast receiver and then start it again
How can I do this

Broadcast receiver likes event handler, Android system calls it automatically when a broadcast matches you defined intent. If you define the boardcast receiver in manifast file, I think the only way you can do it to return immediately when you don't want to handle the broadcast, like the following:
public void onReceive(Context context, Intent intent) {
if (stoppedBroadcast)
return;
// handle broadcast.
}
public void stopBroadcast {
stoppedBroadcast = true;
}
public void resumeBroadcast {
stoppedBroadcast = false;
}

If you want to stop recieving network changes try unregisterReciever in your registering activity/service.
When you want to enable recieving register the reciever with its IntentFilter again.

Related

How to unregister multiple Broadcast receiver which are in different classes at a time?

i want to unregister some broadcast receivers with single click.here is the flow.. lets say in Activity A i have below broadcast receivers.
public BroadcastReceiver upload = new BroadcastReceiver() {
#Override
public void onReceive(Context context, Intent intent) {
}
};
public BroadcastReceiver download = new BroadcastReceiver() {
#Override
public void onReceive(Context context, Intent intent) {
}
};
and in Activity B i have below broadcast receivers
public BroadcastReceiver wifi = new BroadcastReceiver() {
#Override
public void onReceive(Context context, Intent intent) {
}
};
public BroadcastReceiver data = new BroadcastReceiver() {
#Override
public void onReceive(Context context, Intent intent) {
}
};
my problem is i want to unregister all these BroadcastReceiver from Activity C with a button click. How can i do that? and how can i check is receiver is registered or not..?
Keeping broadcast receiver register even after activity is out of screen is memory leak and you should not do that.
Always register your broadcast receivers in onStart/onCreate/onResume and unregister them in onStop/onDestroy/onPause.
Why do you need to keep receiver active even in case activity is out of screen? You might as well use Android Service if you want something to execute out of activity scopes.
Create an Interface in your Activity C with a method unresisterRegisters()
Implement this Interface In Activity A and B. Overrrid the method and write code for unregistere Receivers
create object of A and B in Activity C inside OnButton click and call unresisterRegisters() method with both methods.
I hope this will help You.

media player should stop on disconnecting headphone in my android app programatically

I have an issue in developing a media player application.
I want it so that when I remove my headphone from my device then the MediaPlayer in my app pauses.
The Android documentation suggests using the AUDIO_BECOMING_NOISY intent filter
Set the intent filter in your manafest and then:
public class MusicIntentReceiver extends android.content.BroadcastReceiver {
#Override
public void onReceive(Context ctx, Intent intent) {
if (intent.getAction().equals(
android.media.AudioManager.ACTION_AUDIO_BECOMING_NOISY)) {
// signal your service to stop playback
// (via an Intent, for instance)
}
}
}
Info: http://developer.android.com/guide/topics/media/mediaplayer.html#noisyintent
You can get a ACTION_HEADSET_PLUG Intent over the Broadcast when ever someone Plugs a Headset in or out.
At the start of your App you can use AudioManager.isWiredHeadsetOn() to check if ther is a headset pluged in at the moment. (Dont forgget to add MODIFY_AUDIO_SETTINGS permission.)
Register Broadcast in same Activity.
private BroadcastReceiver mNoisyReceiver = new BroadcastReceiver() {
#Override
public void onReceive(Context context, Intent intent) {
if( mMediaPlayer != null && mMediaPlayer.isPlaying() ) {
mMediaPlayer.pause();
}
}
};
Handles headphones coming unplugged. cannot be done through a manifest receiver
#Override
public void onActivityCreated(#Nullable Bundle savedInstanceState) {
IntentFilter filter = new IntentFilter(AudioManager.ACTION_AUDIO_BECOMING_NOISY);
registerReceiver(mNoisyReceiver, filter);
}
UnRegister Receiver
#Override
public void onDestroy() {
super.onDestroy();
unregisterReceiver(mNoisyReceiver);
}

Remove floating button from WindowManager when power key pressed

My app has a service that add a floating button to WindowManager.
I want to remove my floating button from WindowManager When user press the power key and turn screen off. So when user turn screen on my floating button does not conceal (mask) android pattern screen lock.
I add following code to my Service but it doesn't work !
Should I add any permission or my service must run in background?!
public class Receiver extends BroadcastReceiver {
#Override
public void onReceive(Context context, Intent intent) {
if (intent.getAction().equals(Intent.ACTION_SCREEN_OFF))
{
try{
// Remove Floating Button from Window Manager
MyWindowManager.removeView(floating_btn);
// Stop Service
stopSelf();
}
catch (Exception e)
{
//Log Error
}
}
}
}
Normally you would declare a receiver in your manifest. Something like this
<receiver android:name="com.whatever.client.Receiver"
<intent-filter>
<action android:name="android.intent.action.SCREEN_OFF" />
</intent-filter>
</receiver>
For some reason (not sure why), you don't seem to be able to do this for SCREEN_OFF or SCREEN_ON. So you have to register it programmatically.
As a test, I made a simple app.
public class App extends Application {
#Override
public void onCreate() {
super.onCreate();
BroadcastReceiver receiver = new BroadcastReceiver() {
#Override
public void onReceive(Context context, Intent intent) {
if (intent.getAction().equals(Intent.ACTION_SCREEN_OFF)) {
startService(new Intent(context, MyService.class));
}
}
};
IntentFilter filter = new IntentFilter();
filter.addAction(Intent.ACTION_SCREEN_OFF);
registerReceiver(receiver, filter);
}
}
With a simple service.
public class MyService extends IntentService {
public MyService() {
super("MyService");
}
#Override
protected void onHandleIntent(Intent intent) {
Log.e("MyService", "Screen was turned off!");
}
}
I've got the same problem and I'm working on it now. In your case it didn't work because 1) your "stopSelf()" have to in class extended by Service, not by BroadcastReceiver. 2) if you want to remove a view from window manager you have to somehow pass(the information of view) that view from that method where you'd declared it to method where you want to remove that view

send action from receiver to activity?

I am using broadcast receiver in my app to detect incomming call and it works fine. But problem is I can not send action to activity. I mean.. I want do something in activity not in receiver. I read many tutorial but they all are performing action in receiver. Any idea ?
You can declare a BroadcastReceiver as inner class of the Activity. In this case you can directly call activity's methods:
public class MyActivity extends Activity {
private final BroadcastReceiver receiver = new BroadcastReceiver() {
#Override
public void onReceive(Context context, Intent intent) {
activityMethod();
}
};
private final IntentFilter filter = new IntentFilter("android.intent.action.PHONE_STATE");
#Override
protected void onStart() {
super.onResume();
registerReceiver(receiver, filter);
}
#Override
protected void onStop() {
super.onPause();
unregisterReceiver(receiver);
}
private void activityMethod() {
}
}
You can start the Activity using an Intent and put a command code in the Intent extra fields. In your Activity you can then decide the behaviour based on the command code or resort to a default behaviour if none is present.
You can start an activity from your receiver via the normal means:
#Override
public void onReceive(Context context, Intent intent) {
Intent i = new Intent(context, YourActivity.class);
startActivity(i);
}
Note though that the user is going to expect that the phone application starts up since they are receiving a phone call. It is very likely a bad idea to hijack the phone call by dumping your own activity on top of the stock dialer app.

Unregister all broadcast receivers registered in the activity

Is it possible to register them all at once with a simple code?
Or do they have to be unregistered one by one?
I know it's an old question but why don't you use broadcastreceivers to pick up an intent which then triggers all receivers to unregister?
(Wanted to post something more accurate than the current answer provides)
In the responding fragments/ activities you put this:
public class PanicFragment extends Fragment {
IntentFilter killFilter = new IntentFilter("your.app.name.some.awesome.action.title");
BroadcastReceiver kill = new BroadcastReceiver() {
#Override
public void onReceive(Context context, Intent intent) {
context.unregisterReceiver(receiver); // The actual receiver you want to unreigster
context.unregisterReceiver(this); // The one you just created
}
};
(Don't forget to register the receivers initially when creating the fragment/ activity)
And in your service or other activity or whatever you want this:
private void callThisToUnregisterAllYourReceivers(Context context) {
Intent killThemAll = new Intent();
killThemAll.setAction("your.app.name.some.awesome.action.title");
context.sendBroadcast(killThemAll);
}
I hope this was in any way helpful
You have to do it one by one. An activity should not have very many, if any, and so I would not expect this to be too tedious.
I wouldn't use another BroadcastReceiver to remove other broadcast receivers.
Here is what I added in my Application Class:
private static List<BroadcastReceiver> broadcastReceivers = new LinkedList<>();
public void addReceiver(BroadcastReceiver receiver, IntentFilter filter) {
mContext.registerReceiver(receiver, filter);
broadcastReceivers.add(receiver);
}
public void removeReceiver(BroadcastReceiver receiver) {
unregisterReceiver(receiver);
broadcastReceivers.remove(receiver);
}
public List<BroadcastReceiver> getAllReceivers() {
return broadcastReceivers;
}
public void removeAllReceivers() {
for (BroadcastReceiver receiver : getAllReceivers()) {
removeReceiver(receiver);
}
}

Categories

Resources