我正在尝试向我的应用添加一些连接状态感知功能。 使用这里的示例和google的文档,我们想出了一个接收器,它可以在连接状态发生变化时正确显示警报,但每当创建活动时也会不需要地显示警报。
ConnectStatusReceiver:
package com.zivtaller.placefinder.receivers;
import android.content.BroadcastReceiver;
import android.content.Context;
import android.content.Intent;
import android.net.ConnectivityManager;
import android.net.NetworkInfo;
import android.util.Log;
import android.widget.Toast;
public class ConnectStatusReceiver extends BroadcastReceiver {
private String TAG = "netReceiver";
public ConnectStatusReceiver() {
super();
}
@Override
public void onReceive(Context context, Intent arg1) {
ConnectivityManager cm = (ConnectivityManager) context
.getSystemService(Context.CONNECTIVITY_SERVICE);
NetworkInfo activeNetwork = cm.getActiveNetworkInfo();
boolean isConnected = activeNetwork != null
&& activeNetwork.isConnectedOrConnecting();
if (isConnected) {
Log.d(TAG, "Data connected");
Toast.makeText(context, "Data connected", Toast.LENGTH_SHORT)
.show();
} else {
Log.d(TAG, "Data not connected");
Toast.makeText(context, "Data not connected", Toast.LENGTH_SHORT)
.show();
}
}
}
在活动的onResume()中初始化和注册:
netReceiver = new ConnectStatusReceiver();
IntentFilter netFilter = new IntentFilter();
netFilter.addAction("android.net.conn.CONNECTIVITY_CHANGE");
registerReceiver(netReceiver, netFilter);
答案 0 :(得分:6)
系统可能会生成粘性广播android.net.conn.CONNECTIVITY_CHANGE
意图。粘性广播在发送后留在身边。每当您注册BroadcastReceiver
以侦听粘性广播时,最近广播的意图将在调用registerReceiver()
时立即传递给接收方。
测试android.net.conn.CONNECTIVITY_CHANGE
广播是否为粘性的简便方法是检查registerReceiver()
onResume()
来电的返回值
netReceiver = new ConnectStatusReceiver();
IntentFilter netFilter = new IntentFilter();
netFilter.addAction("android.net.conn.CONNECTIVITY_CHANGE");
Intent intent = registerReceiver(netReceiver, netFilter);
if (intent != null) {
// broadcast is sticky
}
如果您能够确定广播确实是粘性的,那么您所遇到的是预期的行为。
请参阅what is the difference between sendStickyBroadcast and sendBroadcast in Android。
答案 1 :(得分:3)
请做,
unregisterReceiver(netReceiver);
使用onPause()
方法。
答案 2 :(得分:3)
正如Bryan Dunlap所说,你正在处理粘性意图。要检查您收到的意图是否具有粘性,请致电onReceive()
isInitialStickyBroadcast()