2
Iam使用聊天應用程序。如何在活動中取消註冊接收者?
在onPause()和onResume()我註冊了接收器。
我不能註銷中的onPause(接收器),因爲在接收器蔭檢查網絡連接
在的onPause和的onResume我必須監視網絡
然後蔭混亂但如註銷接收機?
任何人都可以請幫助我。
protected void onPause(){
backfacekey=1;
//unregisterReceiver(mConnReceiver);
super.onPause();
registerReceiver(mFacebookReceiver,
new IntentFilter(ConnectivityManager.CONNECTIVITY_ACTION));
}
protected void onResume(){
backfacekey=0;
super.onResume();
registerReceiver(mFacebookReceiver,
new IntentFilter(ConnectivityManager.CONNECTIVITY_ACTION));
}
private BroadcastReceiver mFacebookReceiver = new BroadcastReceiver() {
@Override
public void onReceive(Context context, Intent intent) {
NetworkInfo info = (NetworkInfo)intent.getParcelableExtra(ConnectivityManager.EXTRA_NETWORK_INFO);
if (info.getState().equals(NetworkInfo.State.DISCONNECTED)) {
Toast.makeText(getApplicationContext(), "Network disconnected",Toast.LENGTH_LONG).show();
}
key=2;
}
if (info.getState().equals(NetworkInfo.State.CONNECTED)) {
if(key==2){
Toast.makeText(getApplicationContext(), "Network connected ",Toast.LENGTH_LONG).show();
key=0;
}
}
};
爲什麼要在活動處於暫停狀態時檢查事件?您也可以在onStop()方法中取消註冊接收器。 –
爲什麼不直接在Resume上檢查網絡連接,而是讓接收器處於「後臺」狀態? – sandrstar
該解決方案適合您嗎? –