我已经实现了NetworkChangeReceiver
,如下所示:
public class NetworkChangeReceiver extends BroadcastReceiver {
@Override
public void onReceive(Context context, Intent intent) {
final ConnectivityManager connectionManager = (ConnectivityManager) context.getSystemService(Context.CONNECTIVITY_SERVICE);
final NetworkInfo wifi = connectionManager.getNetworkInfo(ConnectivityManager.TYPE_WIFI);
logMessage(context, "Network State has changed.");
if (!wifi.isAvailable()) {
logMessage(context, "Golly gosh. WiFi has gone away.");
}
}
private void logMessage(Context context, String message) {
Intent intent = new Intent("logging-event");
intent.putExtra("message", message);
LocalBroadcastManager.getInstance(context).sendBroadcast(intent);
}
}
在我的活动中,我也添加了广播接收器:
private BroadcastReceiver mMessageReceiver = new BroadcastReceiver() {
@Override
public void onReceive(Context context, Intent intent) {
String message = intent.getStringExtra("message");
logMessages.add(message);
}
};
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_player);
LocalBroadcastManager
.getInstance(this)
.registerReceiver(mMessageReceiver, new IntentFilter(("logging-event")));
}
AndroidManifest.xml
<receiver android:name=".NetworkChangeReceiver"
android:label="NetworkChangeReceiver">
<intent-filter>
<action android:name="android.net.conn.CONNECTIVITY_CHANGE" />
<action android:name="android.net.wifi.WIFI_STATE_CHANGED" />
</intent-filter>
</receiver>
由于未知原因,不会调用活动的onReceive方法。知道为什么会这样吗?也许是因为日志记录方法中使用了不同的上下文?如果我使用简单的吐司,它会通过,如果我在服务中使用相同的日志记录方法,我可以将服务本身用作上下文。
答案 0 :(得分:0)
您是否在AndroidManifest.xml中注册了意图?那将是我要检查的第一件事。
如果不是,请确认您拥有相应的权限:
<uses-permission android:name="android.permission.INTERNET" />
<uses-permission android:name="android.permission.ACCESS_NETWORK_STATE" />
答案 1 :(得分:0)
尝试使用registerReceiver()
的{{1}}方法,而不是使用Activity