1 监控电量状态
需求
比如:360手机助手,当充上电的时候,才会自动清理手机垃圾,自动备份上传图片、联系人等到云端。
原理
通过监控电量状态来进行电量管理。
- 获取手机的当前充电状
- 判断只有当前手机为充电状态时 才去执行一些非常耗电的操作。
是否充电代码
private boolean checkForPower() {
//获取电池的充电状态
IntentFilter filter = new IntentFilter(Intent.ACTION_BATTERY_CHANGED);
Intent intent = registerReceiver(null, filter);
//BatteryManager
int chargePlug = intent.getIntExtra(BatteryManager.EXTRA_PLUGGED, -1);
boolean usb = chargePlug == BatteryManager.BATTERY_PLUGGED_USB;
boolean ac = chargePlug == BatteryManager.BATTERY_PLUGGED_AC;
//无线充电---API>=17
boolean wireless = false;
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.JELLY_BEAN_MR1) {
wireless = chargePlug == BatteryManager.BATTERY_PLUGGED_WIRELESS;
}
return (usb||ac||wireless);
}
Demo
2 下载时使用WakeLock
public class WakeLockActivity extends AppCompatActivity {
TextView wakelock_text;
PowerManager pw;
PowerManager.WakeLock mWakelock;
@Override
protected void onCreate(@Nullable Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.wake_lock_activity);
wakelock_text = findViewById(R.id.wakelock_text);
pw = (PowerManager) getSystemService(POWER_SERVICE);
mWakelock = pw.newWakeLock(PowerManager.PARTIAL_WAKE_LOCK, "mywakelock");
}
public void execut(View view){
wakelock_text.setText("正在下载....");
for(int i=0;i<10;i++){
mWakelock.acquire();//唤醒CPU
wakelock_text.append("连接中……");
//下载
if(isNetWorkConnected()) {
new SimpleDownloadTask().execute();
}else{
wakelock_text.append("没有网络连接。");
}
}
}
private boolean isNetWorkConnected() {
ConnectivityManager connectivityManager = (ConnectivityManager) getSystemService(Context.CONNECTIVITY_SERVICE);
NetworkInfo networkInfo = connectivityManager.getActiveNetworkInfo();
return (networkInfo!=null&&networkInfo.isConnected());
}
/**
* Uses AsyncTask to create a task away from the main UI thread. This task creates a
* HTTPUrlConnection, and then downloads the contents of the webpage as an InputStream.
* The InputStream is then converted to a String, which is displayed in the UI by the
* onPostExecute() method.
*/
private class SimpleDownloadTask extends AsyncTask<Void, Void, String> {
@Override
protected String doInBackground(Void... voids) {
int len = 50;
try {
URL url = new URL("https://www.baidu.com");
HttpURLConnection conn = (HttpURLConnection) url.openConnection();
conn.setReadTimeout(10000);
conn.setConnectTimeout(15000);
conn.setRequestMethod("GET");
conn.connect();
int response = conn.getResponseCode();
Log.d("SimpleDownloadTask", "The response is: " + response);
InputStream is = conn.getInputStream();
// Convert the input stream to a string
Reader reader = new InputStreamReader(is,"UTF-8");
char[] buffer = new char[len];
reader.read(buffer);
return new String(buffer);
} catch (Exception e) {
e.printStackTrace();
return "Unable to retrieve web page.";
}
}
@Override
protected void onPostExecute(String s) {
wakelock_text.append("\n" + s + "\n");
releaseWakeLock();
}
}
private void releaseWakeLock() {
if(mWakelock.isHeld()){
mWakelock.release();
wakelock_text.append("释放锁!");
}
}
}