在活动恢复后不调用BroadcastReceiver

时间:2011-10-21 17:24:03

标签: android android-activity broadcastreceiver lifecycle

首先,我是android的新手,所以这可能是一个愚蠢的问题,但我已经花了几天时间试图找到解决方案。

我正在尝试为本地化的purpouses构建一个wifi模块,所以我写了一个BroadcastReceiver来处理wifi扫描和本地化。应用程序工作并完成它(在这个阶段非常简单)的工作,当我改变屏幕的方向和我在Desire HD上按下后退按钮然后再次打开应用程序时,会出现类似的问题。但是,当我按下HOME键,进入主屏幕,然后再次输入我的应用程序时,广播接收器似乎不再工作,如果我关闭应用程序,我会收到一条错误消息。

以下是代码,部分改编自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();
    }
}

}

这是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);
  }

}

2 个答案:

答案 0 :(得分:1)

发帖时,最好发布您收到的错误消息,以便我们知道您遇到的问题。

话虽如此,它可能无法正常工作的原因是因为您在onStop中取消注册接收器,而您只在onCreate中注册接收器。您通常应该在匹配的生命周期阶段中执行这些类型的调用。

  • 的onCreate /的onDestroy
  • 在onStart /的onStop
  • 的onResume /的onPause。

要解决您的问题,请尝试在onStart而不是onCreate中注册接收器。

答案 1 :(得分:0)

你的onResume()方法被注释掉了......

你确定这是正确的IntentFilter吗?