我有一个定期调用的服务,如果它遇到网络错误,它会检查网络可用性,如果没有可用的网络,该服务的警报将被取消。然后,我使用网络连接广播接收器来监视网络变化,以便当网络再次可用时,它可以重新启动计时器。
但是,作为预防措施,我还运行一个看门狗计时器服务,它每运行5分钟就检查一次,看看服务是否应该运行。例如,如果不再设置定时器并且网络可用,则它知道存在问题。
嗯,这是我最近遇到的情况,尽管很少。这就是我保持看门狗定时器的原因,但我仍然知道为什么闹钟定时器没有重启。
这是网络接收器:
public class NetworkConnectivityReceiver extends BroadcastReceiver {
Context context;
@Override
public void onReceive(Context ctx, Intent intent) {
context = ctx;
WakeUpManager wakeUpMgr = new WakeUpManager(context);
if (wakeUpMgr.isWakeUpSet() == false) {
// Log all messages received while the wakeup is not set and it should be.
Log.d(TAG, "The timer is not set, and a network change message was received");
}
// Check if the network is connected, and if so, then restart the timer
}
}
以下是该接收者的清单条目:
<receiver android:name="com.mycom.receivers.NetworkConnectivityReceiver">
<intent-filter>
<action android:name="android.net.conn.CONNECTIVITY_CHANGE" />
<action android:name="android.net.ConnectivityManager.CONNECTIVITY_ACTION" />
</intent-filter>
</receiver>
我通过以下方式检查网络可用性:
public static boolean isNetworkAvailable(Context context) {
ConnectivityManager mgr = (ConnectivityManager) context.getSystemService(Context.CONNECTIVITY_SERVICE);
NetworkInfo info = mgr.getActiveNetworkInfo();
if (info != null && info.isConnected()) {
return true;
}
else {
return false;
}
}
我在日志中看到的最后一条消息是:
因此,看门狗报告了一个完全可用的网络连接,但我的网络连接接收器从未收到过该消息。
答案 0 :(得分:0)
在接收器的开头添加了一个日志,看看接收器是否确实接收了广播。如果接收器确实得到广播,那么我怀疑它与唤醒锁定有关。输入onReceived方法时尝试抓取唤醒锁定,并在完成警报计划后释放唤醒锁定,以确保在设备进入睡眠状态之前完成所需操作。