Connection change receiver seems to be missing broadcasts
I have a service that gets called periodically, and if it runs into a network error, it checks the network availability, and if there is no network available, the alarm for that service gets cancelled. I then use a network connectivity broadcast receiver to monitor network changes so that, when the network becomes available again, it can restart the timer.
However, as a precaution, I also run a watchdog timer service that every 5 minutes it runs just to check and see IF the service should be running. For instance, if the timer is no longer set and the network IS available, it knows there's a problem.
Well, that's what I've been running into lately, though very rarely. It's why I keep the watchdog timer around, but I'd still rather know why the alarm timer wasn't restarted.
Here's the network receiver:
public class NetworkConnectivityReceiver extends BroadcastReceiver {
Context context;
@Override
public void onReceive(Context ctx, Intent intent) {
context = ctx;
WakeUpManager wakeUpMgr = new WakeUpManager(context);
if (wakeUpMgr.isWakeUpS开发者_Python百科et() == 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
}
}
Here is the manifest entry for that receiver:
<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>
I check for network availability by:
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;
}
}
The last messages I'm seeing in the log are:
- There are no active networks, cancelling timer
- Watchdog service: timer was not set and network IS available
- Network info: Connectivity: Type: mobile Available: true Connected: true ConnectedOrConnecting: true
- Watchdog service: starting timer....
So, the watchdog is reporting a completely available network connection, but my network connectivity receiver never received that message.
Added a log at the start of the receiver and see if the receiver did get the broadcast. If the receiver did get the broadcast then I would suspect it has to do with wake lock. Try grab a wake lock when entered onReceived method and release that wake lock after you finished schedule the alarm to make sure you finish what you have to do before the device go to sleep.
精彩评论