我已经运行了一些接收器,包括一个用于重启和进入飞行模式的接收器。 但是,我并不总是及时获得Intent以便我做我需要做的事情,向外部服务器发送快速消息。
即使将意图过滤器设置为优先级1000,也不能保证在为时已晚之前进行传输,尽管它确实有帮助。
如上所述,并不是因为我没有接收到我的广播,而是在网络已经关闭之后才得到它们。
任何指示我可以找到一些提示的地方都是非常受欢迎的,我过去几天在网上搜索没有运气。
修改 我目前正在使用4个广播听众之间的以下行动
<action android:name="android.intent.action.MAIN" />
<category android:name="android.intent.category.LAUNCHER" />
<action android:name="android.intent.action.BOOT_COMPLETED" />
<action android:name="android.intent.action.PHONE_STATE" />
<action android:name="android.intent.action.NEW_OUTGOING_CALL" />
<action android:name="android.intent.action.PROVIDER_CHANGED" />
<action android:name="android.intent.action.ACTION_SHUTDOWN" />
<action android:name="android.intent.action.AIRPLANE_MODE" />
编辑2:我意识到我并没有完全清楚我的意图。我不是在谈论网络状态本身,而是用户进入飞行模式或关闭设备的行动。
答案 0 :(得分:0)
参考此代码:
IntentFilter monitorInternetConnectivityFilter = new IntentFilter(
ConnectivityManager.CONNECTIVITY_ACTION);
MonitorInternetConnectivity monitorInternetConnectivityReciever;
monitorInternetConnectivityReciever = new MonitorInternetConnectivity();
class MonitorInternetConnectivity extends BroadcastReceiver {
@Override
public void onReceive(Context context, Intent intent) {
if (!NetworkHelper.isOnline(context)) {
//Toast.maketext("Network went down");
}
}
}
@Override
protected void onPause() {
// TODO Auto-generated method stub
super.onPause();
unregisterReceiver(monitorInternetConnectivityReciever);
}
@Override
protected void onResume() {
// TODO Auto-generated method stub
super.onPause();
registerReceiver(monitorInternetConnectivityReciever,
monitorInternetConnectivityFilter);
}
////////////////////// NetworkHelper
public static boolean isOnline(Context cxt) {
ConnectivityManager cm = (ConnectivityManager) cxt
.getSystemService(Context.CONNECTIVITY_SERVICE);
NetworkInfo netInfo = cm.getActiveNetworkInfo();
if (netInfo != null && netInfo.isConnectedOrConnecting() && canHit()) {
Logger.debug(NetworkHelper.class, "mode is online");
return true;
}
return false;
}
public static boolean canHit() {
try {
URL url = new URL("http://www.google.com/");
HttpURLConnection urlConnection = (HttpURLConnection) url
.openConnection();
urlConnection.setConnectTimeout(3000);
urlConnection.connect();
urlConnection.disconnect();
return true;
} catch (Exception e) {
Logger.error(NetworkHelper.class, e.getMessage());
return false;
}
}
此代码会在网络关闭时通知您,不确定它是否在它之前通知您