I want to start and stop a broadcast receiver from two buttons. I had written the code for this in two button listeners.
The code is as follows:-
In startButton I have written the code for registering receiver as follows
startCallBtn.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
// TODO Auto-generated method stub
startCallBtn.setVisibility(View.INVISIBLE);
stopCallBtn.setVisibility(View.VISIBLE);
//register call receiver.
registerReceiver(callReceiver, new IntentFilter(
"android.intent.action.CALL"));
System.out.println("Registered Call Receiver Perfectly");
}
});
In a stop button I have written the call for stop receiver as
stopCallBtn.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
// TODO Auto-generated method stub
stopCallBtn.setVisibility(View.INVISIBLE);
startCallBtn.setVisibility(View.VISIBLE);
stopService(new Intent(MainActivity.this, SpeakOut.class));
FileOutputStream fos;
//Unregister sms receivers
unregisterReceiver(callReceiver);
System.out.println("Unregistered Call Broadcast Receiver");
}
});
still the listener is calling when new call is receiving
in manifest
<receiver android:name="your receiver name">
main Activity
BroadcastReceiver br = new BroadcastReceiver() {
@Override
public void onReceive(Context context, Intent intent) {
Log.w("Check", "Inside On Receiver");
Toast.makeText(getApplicationContext(), "received", Toast.LENGTH_SHORT).show();
}
};
@Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.main);
IntentFilter filter = new IntentFilter();
filter.addAction(BROADCAST_ACTION);
filter.addCategory(Intent.CATEGORY_DEFAULT);
registerReceiver(br, filter);
}
@Override
protected void onPause() {
super.onPause();
unregisterReceiver(br);
}
}
You can try this code for enable
and disable
BroadcastReceiver
..I hope this will help you..
public void enableBroadcastReceiver(View view)
{
ComponentName receiver = new ComponentName(this, AlarmManagerBroadcastReceiver.class);
PackageManager pm = this.getPackageManager();
pm.setComponentEnabledSetting(receiver,
PackageManager.COMPONENT_ENABLED_STATE_ENABLED,
PackageManager.DONT_KILL_APP);
Toast.makeText(this, "Enabled broadcast receiver", Toast.LENGTH_SHORT).show();
}
/**
* This method disables the Broadcast receiver registered in the AndroidManifest file.
* @param view
*/
public void disableBroadcastReceiver(View view){
ComponentName receiver = new ComponentName(this, AlarmManagerBroadcastReceiver.class);
PackageManager pm = this.getPackageManager();
pm.setComponentEnabledSetting(receiver,
PackageManager.COMPONENT_ENABLED_STATE_DISABLED,
PackageManager.DONT_KILL_APP);
Toast.makeText(this, "Disabled broadcst receiver", Toast.LENGTH_SHORT).show();
}
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