需要实现一个开机时刻启动升级服务的功能,但是接受的广播为android的"android.intent.action.BOOT_COMPLETED",接收到广播后,系统的网络并不一定就绪,在网络不通的情况下可能导致本次升级服务启动不了。
解决方法是,在接收到广播之后查询网络状况,如果网络通畅,则启动升级服务,否则等待150s,直到网络通畅再启动升级。
该方法成功的解决了收到开机广播和网络就绪不同步问题,保证升级服务在有线连接和wifi连接情况下都能够顺利启动。
需要注意的一点是,等待操作不能直接加入到广播接受的reviever函数中,这样,如果等待时间较久,一般超过十秒钟,会报anr错误。
E/ActivityManager( 2029): ANR in com.tcl.mtk.mtkVersionUpdate
E/ActivityManager( 2029): PID: 2810
E/ActivityManager( 2029): Reason: Broadcast of Intent { act=android.intent.action.BOOT_COMPLETED flg=0x18000010 cmp=com.tcl.mtk.mtkVersionUpdate/.broadcastManage.BroadCastManger (has extras) }
E/ActivityManager( 2029): Load: 4.17 / 0.97 / 0.32
代码实现片段:
@Override
public void onReceive(Context context, Intent intent) {
mContext = context;
String action = intent.getAction();
if (action.equals(BroadCastType.systemBootFinished)) { // 系统启动完成,首先判断自动升级是否已经开启,如果自动升级已经开启,则需要启动自动升级;
System.out.println("received systemBootFinished broadcast:"
+ BroadCastType.standServiceFinished);
new AutoNetworkUpdateThread().start();
}
}
class AutoNetworkUpdateThread extends Thread {
public void run() {
Log.i(TAG, "AutoNetworkUpdateThread in");
boolean isNetworkAlive = isNetworkAvailable(mContext);
if (isNetworkAlive) {
Log.i(TAG, "isNetworkAlive = " + isNetworkAlive);
standardServiceFinished(mContext);
} else {
//实现连接不上则尝试五十次连接功能
int attemptTime = 0;
while (attemptTime < maxConnectTime) {
Log.d(TAG,"attemptStrTime = " + attemptTime);
isNetworkAlive = isNetworkAvailable(mContext);
Log.i(TAG, "isNetworkAlive = " + isNetworkAlive);
if (isNetworkAlive) {
standardServiceFinished(mContext);
break;
}
try {
Thread.sleep(3000);
} catch (InterruptedException e1) {
// TODO Auto-generated catch block
e1.printStackTrace();
}
Log.d(TAG,"The " + attemptTime + " time attempt...." );
if (attemptTime == maxConnectTime - 1) {
Log.d(TAG,"The last time attempt str update....throw Exception...." );
}
attemptTime++;
}
}
}
}