Search code examples
androidandroid-activitybroadcastreceiverlifecycle

BroadcastReceiver not being called after activity resume


First of all I'm a novice to android, so this could probably be a silly issue, nevertheless I've already spent a couple of days trying to get to a solution.

I'm trying to build a wifi module for localization purpouses, so I wrote a BroadcastReceiver in order to handle the wifi scanning and the localization. The application works and does its (quite simple at this stage) job, with anu kind of issues both when I change the orientation of the screen and when I hit the back button on my Desire HD and then open the application again. But when I hit the HOME key, going to the main screen, and then enter again my app the Broadcast Receiver seems not to work anymore, and if I close the application I get an error message.

Here's the code, partially adapted from here.

public class WiFiDemo extends Activity implements OnClickListener {

private static final String TAG = "WiFiDemo";
WifiManager wifi;
BroadcastReceiver receiver;
WifiManager.WifiLock lock;
boolean wifiPrevState;
boolean scanON = false;
String header;


TextView textStatus;
Button buttonScan;

/** Called when the activity is first created. */
@Override
public void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.main);


    // Setup UI
    textStatus = (TextView) findViewById(R.id.textStatus);
    buttonScan = (Button) findViewById(R.id.buttonScan);
    buttonScan.setOnClickListener(this);

    // Setup WiFi
    if (wifi == null){
        wifi = (WifiManager) getSystemService(Context.WIFI_SERVICE);
    }


    //checking WiFi status, enabling it if needed and locking it.
    wifiPrevState = wifi.isWifiEnabled();
    wifi.setWifiEnabled(true);
    if (lock == null){
        lock = wifi.createWifiLock("lock");
    }

    lock.acquire();

    // Get WiFi status
    WifiInfo info = wifi.getConnectionInfo();
    header="\n\nWiFi Status: \n" + info.toString() + "\n\nAvailable nets:";
    textStatus.append(header);

    // Register Broadcast Receiver
    if (receiver == null)
        receiver = new WiFiScanReceiver(this);

    registerReceiver(receiver, new IntentFilter(
            WifiManager.SCAN_RESULTS_AVAILABLE_ACTION));
    Log.d(TAG, "onCreate()");

}

/*
@Override
protected void onPause(){
    super.onPause();
    wifi.setWifiEnabled(wifiPrevState);
    lock.release();
    unregisterReceiver(receiver);
    Log.d(TAG, "onPause()");
}

@Override
protected void onResume(){
    super.onResume();
    wifi.setWifiEnabled(true);
    lock.acquire();
    registerReceiver(receiver, new IntentFilter(
            WifiManager.SCAN_RESULTS_AVAILABLE_ACTION));
    Log.d(TAG, "onResume()");

}
*/

@Override
public void onStop() {
    super.onStop();
    wifi.setWifiEnabled(wifiPrevState);
    lock.release();
    unregisterReceiver(receiver);

}

public void onClick(View view) {
    Toast.makeText(this, "On Click Clicked. Toast to that!!!",
            Toast.LENGTH_LONG).show();

    if (view.getId() == R.id.buttonScan) {
        Log.d(TAG, "onClick() wifi.startScan()");
        scanON = !scanON;
        wifi.startScan();
    }
}

}

And this is the BroadcastReceiver

public class WiFiScanReceiver extends BroadcastReceiver {
  private static final String TAG = "WiFiScanReceiver";
  WiFiDemo wifiDemo;
  ScanResult storedBest;

  public WiFiScanReceiver(WiFiDemo wifiDemo) {
    super();
    this.wifiDemo = wifiDemo;
    storedBest = null;
  }

 @Override
 public void onReceive(Context c, Intent intent) {
    List<ScanResult> results = wifiDemo.wifi.getScanResults();
    ScanResult bestSignal = null;
    wifiDemo.textStatus.setText(wifiDemo.header);

    for (ScanResult result : results) {
      if (bestSignal == null
         || WifiManager.compareSignalLevel(bestSignal.level, result.level) < 0)
         bestSignal = result;
      wifiDemo.textStatus.append("\n\n" + result.toString());
    }

      if ( storedBest == null || ((bestSignal.SSID.compareTo(storedBest.SSID)!=0) &&  bestSignal.level>-50)){
         storedBest = bestSignal;
         String locationMessage = String.format("You are near %s's Access Point",
                 bestSignal.SSID);
         Toast.makeText(wifiDemo, locationMessage, Toast.LENGTH_LONG).show();
      }
      String message = String.format("%s networks found. %s is the strongest. Its level is %s",
         results.size(), bestSignal.SSID, bestSignal.level);
      if (wifiDemo.scanON) wifiDemo.wifi.startScan();
      Log.d(TAG, "onReceive() message: " + message);
  }

}

Solution

  • When posting, its best to post the error message that you are getting so we know the problem you are having.

    That being said, the reason it probably isn't working is because you unregister your receiver in onStop and you only register your receiver in onCreate. You should typically do these type of calls in life cycle stages that match.

    • onCreate/onDestroy
    • onStart/onStop
    • onResume/onPause.

    To fix your problem, try registering your receiver in onStart instead of onCreate.