Android启动时,会发出一个系统广播 ACTION_BOOT_COMPLETED,它的字符串常量表示为 “android.intent.action.BOOT_COMPLETED”
开机自启动程序,只需要“捕捉”到这个消息再启动你的程序即可,我们要做的是接收这个消息,并实现一个BroadcastReceiver;
网络状态发生变化时会发出一个系统广播CONNECTIVITY_ACTION,值为"android.net.conn.CONNECTIVITY_CHANGE",
对网络做一判断,即可实现开机时有可用网络以及网络状态变化且网络可用时自动运行程序 。
代码如下:
/**
* 开机启动检测和连接wifi检测
* */
public class BootBroadcastReceiver extends BroadcastReceiver {
static final String ACTION = "android.intent.action.BOOT_COMPLETED";//boot
static final String NetChange = "android.net.conn.CONNECTIVITY_CHANGE";//the net change
private static final String TAG = "BootBroadcastReceiver";
@Override
public void onReceive(Context context, Intent intent) {
ConnectivityManager connectivityManager = (ConnectivityManager) context
.getSystemService(Context.CONNECTIVITY_SERVICE);
NetworkInfo wifiInfo = connectivityManager
.getNetworkInfo(ConnectivityManager.TYPE_WIFI);
Log.d(TAG, intent.getAction());
if((intent.getAction().equals(ACTION) && wifiInfo.isConnected())
||(intent.getAction().equals(NetChange) && wifiInfo.isConnected())){
Intent startIntent = new Intent(context,MainActivity.class);
startIntent.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
context.startActivity(startIntent);
}else{
Log.d(TAG, "no net ,do not start app");
}
}
}
<receiver android:name=".receiver.BootBroadcastReceiver" >
<intent-filter >
<!-- boot -->
<action android:name="android.intent.action.BOOT_COMPLETED" />
</intent-filter>
<intent-filter >
<!-- net change action -->
<action android:name="android.net.conn.CONNECTIVITY_CHANGE" />
</intent-filter>
</receiver>