1 在AndroidManifest.xml中添加权限
<!-- 允许程序开机启动 -->
<uses-permission android:name="android.permission.RECEIVE_BOOT_COMPLETED" />
2 在AndroidManifest.xml中添加消息接收
<receiver android:name=".BootBroadcastReceiver">
<intent-filter android:priority="1000">
<action android:name="android.intent.action.BOOT_COMPLETED" />
<action android:name="android.intent.action.USER_PRESENT" />
<action android:name="android.net.conn.CONNECTIVITY_CHANGE" />
<action android:name="android.intent.action.ACTION_POWER_CONNECTED" />
<action android:name="android.intent.action.ACTION_POWER_DISCONNECTED" />
</intent-filter>
</receiver>
3 代码实现
public class BootBroadcastReceiver extends BroadcastReceiver {
public static final String NET_CHANGE = "net_change";
//标记当前网络状态,0为无可用网络状态,1表示有。
public static final String NET_TYPE = "net_type";
//重写onReceive方法
@Override
public void onReceive(Context context, Intent intent) {
//开机自动启动
if (intent.getAction().equals("android.intent.action.BOOT_COMPLETED")) {
//监听开机启动
//启动程序
Intent newIntent = context.getPackageManager().getLaunchIntentForPackage("cn.xaele.mineapp");
context.startActivity(newIntent);
} else if (intent.getAction().equals("android.intent.action.USER_PRESENT")) {
// 用户解锁屏幕
} else if (intent.getAction().equals("android.intent.action.ACTION_POWER_CONNECTED")) {
// 充电时
} else if (intent.getAction().equals("android.intent.action.ACTION_POWER_DISCONNECTED")) {
// 充电结束时
} else if (intent.getAction().equals("android.net.conn.CONNECTIVITY_CHANGE")) {
// 网络发生变化
ConnectivityManager connectivityManager = (ConnectivityManager) context.getSystemService(Context.CONNECTIVITY_SERVICE);
//移动数据
NetworkInfo mobNetInfo = connectivityManager.getNetworkInfo(ConnectivityManager.TYPE_MOBILE);
//wifi网络
NetworkInfo wifiNetInfo = connectivityManager.getNetworkInfo(ConnectivityManager.TYPE_WIFI);
if (!mobNetInfo.isConnected() && !wifiNetInfo.isConnected()) {
// 网络状态全部不可用
Intent netIntent = new Intent(NET_CHANGE);
netIntent.putExtra(NET_TYPE, 0);
context.sendBroadcast(netIntent);
return;
}
if (mobNetInfo.isConnected() || wifiNetInfo.isConnected()) {
Intent netIntent = new Intent(NET_CHANGE);
netIntent.putExtra(NET_TYPE, 1);
context.sendBroadcast(netIntent);
return;
}
if (mobNetInfo.isConnected() && !wifiNetInfo.isConnected()) {
// 手机没有处于wifi网络而是处于移动网络
}
}
}
}