2

I created a brodcastReceiver for Wi-Fi ,every thing is working fine ,except ,that when i lunch the application ,the broadcastreceiver start directly scanning ,and i can't stop it, and keeps running even i go out from the application. I tryed to controle the broadcast receiver from the main activity ,but it seems that there is a broblem. Can someone take a look to my code, and if it's possible ,tell me what could be the problem.

Thank you in advance.

PS :when click buttons ,the toasts are working,but there is no influence on the brodcast receiver.

I'm lunching a service in the brodcastreceiver, could it have an influence on the broblem ?

                                  **EDIT** 

This is my MainActivity

    public class MainActivity extends Activity {
    int newRssi;
    List<String> listDebitDistance = new ArrayList<String>(); 
    WifiManager wifi;

    private final BroadcsatReceiverMnager broad = new BroadcsatReceiverMnager();
    ArrayList<int[]> listCursorReçue = new ArrayList<int[]>();
     IntentFilter rssiFilter = new          IntentFilter(WifiManager.SCAN_RESULTS_AVAILABLE_ACTION);
    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);
    }




/**
 * This method enables the Broadcast receiver registered in the AndroidManifest file.
 * @param view
 */
    public void enableBroadcastReceiver(View view){
        switch (view.getId()){

        case R.id.button1 :

             super.registerReceiver(broad, new IntentFilter("android.intent.action.BOOT_COMPLETED"));

            this.registerReceiver(broad, rssiFilter);
            WifiManager wifiMan=(WifiManager)MainActivity.this.getSystemService(Context.WIFI_SERVICE);
            wifiMan.startScan();

          Toast.makeText(this, "Enabled broadcast receiver", Toast.LENGTH_SHORT).show();

            break; 
        }

        }
/**
* This method disables the Broadcast receiver registered in the AndroidManifest file.
* @param view
*/
public void disableBroadcastReceiver(View view){
    switch (view.getId()){

    case R.id.button2 :
        //this.unregisterReceiver(broad); //this gives the exception 
     unregisterReceiver(broad); //this methode gives the exception too
      Toast.makeText(this, "Disabled broadcst receiver", Toast.LENGTH_SHORT).show();


        break; 
    }

}

public void onPause() {

    super.onPause();
    this.unregisterReceiver(broad);
//S'il y a un appel l'app crash !!! a voir !!!!
}
/**
 * Broadcast receiver to update 
 */

public void onResume() {
    super.onResume();
   // BroadcsatReceiverMnager broad = new BroadcsatReceiverMnager();

    //Note: Not using RSSI_CHANGED_ACTION because it never calls me back.


    WifiManager wifiMan=(WifiManager)MainActivity.this.getSystemService(Context.WIFI_SERVICE);
    wifiMan.startScan();

}
}

And this is my BroadcsatReceiverMnager class

  public class BroadcsatReceiverMnager extends BroadcastReceiver {
    int newRssi;

     int rssi1 ;
   int rssi2;
   int rssi3 ;
   int rssiOp1=0  ;
    int rssiOp2 =0 ;
    int rssiOp3=0  ;
    WifiManager wifi;



    @Override
    public void onReceive(Context arg0, Intent arg1) {      
        Toast.makeText(arg0,"MyTag BroadcsatReceiverMnager "+ "onReceive", Toast.LENGTH_LONG).show();

        wifi = (WifiManager)arg0.getSystemService(Context.WIFI_SERVICE);

    if(arg1.getAction().equals(WifiManager.SCAN_RESULTS_AVAILABLE_ACTION )){//
             List<ScanResult> results = wifi.getScanResults();
            Toast.makeText(arg0, "results"+results, Toast.LENGTH_SHORT).show();
            rssiOp1 =   results.get(0).level;
            rssiOp2 =   results.get(1).level;
            rssiOp3 =   results.get(2).level;

      }
     WifiManager wifiMan=(WifiManager)arg0.getSystemService(Context.WIFI_SERVICE);
      wifiMan.startScan();
      int newRssi = wifiMan.getConnectionInfo().getRssi();
      Toast.makeText(arg0, "BroadcsatReceiverMnager"+newRssi, Toast.LENGTH_SHORT).show();
}


}
Amina
  • 723
  • 8
  • 20

1 Answers1

1

If you want to control the registration and the un-registration of your receiver, don't define it in your manifest at all. as I said in this answer :

If you register the receiver in the manifest, the handler of the receiver will start each time that a the correspondent event come. example: the messenger of facebook is lunched every time that you have a connection to show you your notifications... or other applications are lunched when you connect to propose updates ... in other words, the receiver is always registered.

In you case, define the receiver in your activity, register it and unregister it in the same activity.

/**
 * the intent of communication with the Brodcast receiver
 */
IntentFilter intentFilter = new IntentFilter();



/**
 * the BroadcastReceiver 
 */
BroadcastReceiver yourBroadcastReceiver = new BroadcsatReceiverMnager ();

in your onCreat() :

// set the action
intentFilter.addAction("SCAN_RESULTS_AVAILABLE_ACTION");

register it :

    registerReceiver(yourBroadcastReceiver , intentFilter);

unregister it :

unregisterReceiver(yourBroadcastReceiver);

So, in you listeners :

    /**
 * This method enables the Broadcast receiver registered in the AndroidManifest file.
 * @param view
 */
    public void enableBroadcastReceiver(View view){
        switch (view.getId()){

        case R.id.button1 :

           registerReceiver(yourBroadcastReceiver , intentFilter);

              Toast.makeText(this, "Enabled broadcast receiver", Toast.LENGTH_SHORT).show();

            break; 
        }

        }
/**
* This method disables the Broadcast receiver registered in the AndroidManifest file.
* @param view
*/
public void disableBroadcastReceiver(View view){
    switch (view.getId()){

    case R.id.button2 :

        unregisterReceiver(yourBroadcastReceiver);

          Toast.makeText(this, "Disabled broadcst receiver", Toast.LENGTH_SHORT).show();


        break; 
    }

}

The answer to your last question in the comments :

1/ you have a scan to do, to get some information.

2/ you want to lunch the scan only when you are in main activity, by action (by intent filter).

===> you use your receiver in this activity : - register it in onResume() and unregister it in onPause() - do the scan (and what you want to do with the data that it will return) in the onReceive() of the receiver.

3/ you want to manage when to activate the Receiver, and when to desable it : the receiver doesn't only depend on the life cycle of the Activity: ===> then you add a button to activate or disable it (register/unregister).

Community
  • 1
  • 1
ahmed_khan_89
  • 2,755
  • 26
  • 49
  • Thank you for replying ,i did as you said ,when click on buttons i'm getting those exceptions :`04-24 09:35:46.034: E/AndroidRuntime(4436): java.lang.IllegalStateException: Could not execute method of the activity ` and this one ` Caused by: java.lang.IllegalArgumentException: Component class com.example.downloadservicetest1.BroadcsatReceiverMnager does not exist in com.example.downloadservicetest1`, what do you think is the problem. @ahmed_khan_89 – Amina Apr 24 '14 at 08:39
  • The second exception is pointion to `pm.setComponentEnabledSetting(receiver, PackageManager.COMPONENT_ENABLED_STATE_ENABLED, PackageManager.DONT_KILL_APP);` – Amina Apr 24 '14 at 08:44
  • 1
    I added what you have to update in the click listeners in my answer. Is it what you did ? – ahmed_khan_89 Apr 24 '14 at 08:47
  • yes ,i updated my code in the onclick ,now i don't have exceptions.But i'm having the same result as in the beginning.I don't know why the scann starts automaticly,and i con't stop it,please could you take a look to onPause and resume methods in the main Activity.@ahmed_khan_89 – Amina Apr 24 '14 at 08:59
  • WifiManager wifiMan=(WifiManager)MainActivity.this.getSystemService(Context.WIFI_SERVICE); wifiMan.startScan(); – ahmed_khan_89 Apr 24 '14 at 09:33
  • 1
    you have this in your onResume() , delete it. then the scan will not begin in onResmue. and you are registering and unregistring the receivers in onResume() and onPause(). remove that as well if you want to register and unregister only by buttons. – ahmed_khan_89 Apr 24 '14 at 09:34
  • yes this is what i did .Could see my edits please in my POST.Now i can start the broadcastReceiver ,but i can't stop it. A nd when i click on "stop" i'm having this exception : `Caused by: java.lang.IllegalArgumentException: Receiver not registered: com.example.downloadservicetest1.BroadcsatReceiverMnager@41c16860` and it point on this : ` unregisterReceiver(broad); `in the disableBroadcastReceiver method ,what do you think abou that ,i tryed two methods ,you can see them in the EDIT. – Amina Apr 24 '14 at 09:38
  • could you please try : MainActivity.this.registerReceiver(broad, rssiFilter); and : MainActivity.this.unregisterReceiver(broad); – ahmed_khan_89 Apr 24 '14 at 09:44
  • the same same problem :( ,again the same exception Receiver not registered,in the MainActivity.this.unregisterReceiver(broad); . **PS** :when i click the first time on stop nothing happens ,but when force clicking i get this exception. – Amina Apr 24 '14 at 10:01
  • 1
    super.registerReceiver(broad, new IntentFilter("android.intent.action.BOOT_COMPLETED")); why are registring this action also? I mean do you need to lunch the onReceive() when the boot has complited. for the exception, if it is not from the first click, that means that the receiver has been unregistred successfully (I guess). you can check if the receiver is registered or not by better methods than Toasts... see this link : http://stackoverflow.com/questions/2682043/how-to-check-if-receiver-is-registered-in-android – ahmed_khan_89 Apr 24 '14 at 10:10
  • 1
    you are also starting the scan, in the click listener , in the onResume and in the broadcast receiver , I don't know how you can test then :P . also put some logs (Log.i(tag,msg);), better than toasts ; logs are faster. – ahmed_khan_89 Apr 24 '14 at 10:13
  • I added this code to the button listener : ` Log.i("unregisterReceiver1",broad+""); if (broad != null) { MainActivity.this.unregisterReceiver(broad); Log.i("unregisterReceiver2",broad+""); broad = null; }` the i get this LOg`I/unregisterReceiver1(14952):com.example.downloadservicetest1.BroadcsatReceiverMnager@41c16710andI/unregisterReceiver2(14952):com.example.downloadservicetest1.BroadcsatReceiverMnager@41c16710 ` – Amina Apr 24 '14 at 10:45
  • i would like to ask you again (i already mention it in the post PS).When the broadcast starts : a service is launched to do some computings.If the brodcast is stopped ,will the service stopes too ,or i need to stop it too ?@ahmed_khan_89 – Amina Apr 24 '14 at 10:53
  • 1
    So it is resolved ? Can I ask you why you don't just register the receiver in onResume() and unregister it in onPause() ? --> when this activity is alive , if the receiver receive the intent action, it lunchs the onReceive(). and life is pink :) – ahmed_khan_89 Apr 24 '14 at 10:56
  • 1
    else , you use only when button to register/unregister the BroadcastReceiver , in each click to the button you update the listener of the button... because this story of "null" is not funny – ahmed_khan_89 Apr 24 '14 at 10:57
  • 1
    The service life cycle doesn't depend on the activity one or the receiver one ... no it will not stop. – ahmed_khan_89 Apr 24 '14 at 10:59
  • O my God, @ahmed_khan_89 ,what do you advice me to do , i'm feeling like i'm turning in a cercle. Sorry if i'm weisting your time. PS :the onResume an OnPause methodes i used them ,as in the first code that i posted ,But i need to do some work with the results that i get after stopping the scan. – Amina Apr 24 '14 at 11:05