獲取手機(jī)是否在充電通過系統(tǒng)廣播憔古,然后攔截器通知去獲取充電狀態(tài)改變。
/**
* 是否在充電
*/
public static boolean isPlugged(Context context) {
//創(chuàng)建過濾器攔截電量改變廣播
IntentFilter intentFilter = new IntentFilter(Intent.ACTION_BATTERY_CHANGED);
//通過過濾器來獲取電量改變intent 電量改變是系統(tǒng)廣播所以無需去設(shè)置所以receiver傳null即可
Intent intent = context.registerReceiver(null, intentFilter);
//獲取電量信息
int isPlugged = intent.getIntExtra(BatteryManager.EXTRA_PLUGGED, -1);
//電源充電
boolean acPlugged = BatteryManager.BATTERY_PLUGGED_AC == isPlugged;
//usb充電
boolean usbPlugged = BatteryManager.BATTERY_PLUGGED_USB == isPlugged;
//無線充電
boolean wirePlugged = BatteryManager.BATTERY_PLUGGED_WIRELESS == isPlugged;
//滿足充電即返回true
return acPlugged || usbPlugged || wirePlugged;
}
獲取手機(jī)是否是wifi狀態(tài)吮成,通過獲取ConnectivityManager服務(wù)獲取當(dāng)前網(wǎng)絡(luò)狀態(tài)
/**
* 是否為wifi鏈接狀態(tài)
*/
public static boolean isWifi(Context context) {
//獲取網(wǎng)絡(luò)狀態(tài)管理
ConnectivityManager connectivityManager = (ConnectivityManager)
context.getSystemService(Context.CONNECTIVITY_SERVICE);
//根據(jù)網(wǎng)絡(luò)狀態(tài)管理來獲取當(dāng)前網(wǎng)絡(luò)信息
NetworkInfo activeNetworkInfo = connectivityManager.getActiveNetworkInfo();
//根據(jù)網(wǎng)絡(luò)信息獲取當(dāng)前是否wifi鏈接
if (activeNetworkInfo != null && activeNetworkInfo.isConnected() &&
activeNetworkInfo.getType() == ConnectivityManager.TYPE_WIFI) {
return true;
}
return false;
}