Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Stop broadcast receiver from a button in acivity

I want to stop and start a broadcast receiver through a button click. two services associated with the broadcast receiver should also stop and start with button click how can i do it..

like image 795
Geethu Avatar asked Jan 18 '13 04:01

Geethu


3 Answers

this is the code............

b1.setOnClickListener(new View.OnClickListener() {

 @Override
 public void onClick(View v) {
    // TODO Auto-generated method stub

        PackageManager pm  = Re_editActivity.this.getPackageManager();
        ComponentName componentName = new ComponentName(currentActivity.this, name_of_your_receiver.class);
        pm.setComponentEnabledSetting(componentName,PackageManager.COMPONENT_ENABLED_STATE_ENABLED,
                        PackageManager.DONT_KILL_APP);
        Toast.makeText(getApplicationContext(), "activated", Toast.LENGTH_LONG).show();

        }
    });

  b2.setOnClickListener(new View.OnClickListener() {

    @Override
    public void onClick(View v) {
        // TODO Auto-generated method stub
        PackageManager pm  = Re_editActivity.this.getPackageManager();
        ComponentName componentName = new ComponentName(currentActivity.this, name_of_your_receiver.class);
        pm.setComponentEnabledSetting(componentName,PackageManager.COMPONENT_ENABLED_STATE_DISABLED,
                        PackageManager.DONT_KILL_APP);
        Toast.makeText(getApplicationContext(), "cancelled", Toast.LENGTH_LONG).show();
    }
});
like image 75
Geethu Avatar answered Sep 21 '22 12:09

Geethu


You can choose to "stop" a BroadcastReceiver either on, say a Button click, or perhaps in the onPause().

For example:

// DECLARED GLOBALLY
BroadcastReceiver receiver;
Intent intentMyService;
ComponentName service;

And in the onCreate():

// FOR THE SERVICE:
intentMyService = new Intent(this, MyGpsService.class);
service = startService(intentMyService);

// FOR THE BROADCASTRECEIVER:
IntentFilter mainFilter = new IntentFilter();
receiver = new MyMainLocalReceiver();
registerReceiver(receiver, mainFilter);

Then to "stop" it, all you have to do, is make a call to this method in either the onPause() or on the click of a Button:

// "STOP" THE BROADCASTRECEIVER
unregisterReceiver(receiver);

// STOP THE SERVICE
stopService(intentMyService);
like image 29
Siddharth Lele Avatar answered Sep 21 '22 12:09

Siddharth Lele


public class MyActivity extends Activity
{
  private final BroadcastReceiver mybroadcast = new SmsBR();

  public void onResume()
  {
    IntentFilter filter = new IntentFilter();
    filter.addAction("android.provider.Telephony.SMS_RECEIVED");
    registerReceiver(mybroadcast, filter);  

  }

  public void onPause()
  {

// add the below line in your button click event

    unregisterReceiver(mybroadcast);
  }
}
like image 27
Ramesh Sangili Avatar answered Sep 18 '22 12:09

Ramesh Sangili