Android 之 监控手机电量
程序员文章站
2022-03-02 19:45:01
...
package com.example.battery; import android.app.Activity; import android.content.BroadcastReceiver; import android.content.Context; import android.content.Intent; import android.content.IntentFilter; import android.os.Bundle; import android.util.Log; import android.widget.TextView; /** * 功能实现 --- 监控手机的电量 使用动态注册广播 ,实现电量的监控 : 广播地址:ACTION_BATTERY_CHANGED * * @author Administrator * */ public class MainActivity extends Activity { private TextView battery; // 应用入口 protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_main); battery = (TextView) findViewById(R.id.battery); // 获取对象 } /** * 应用结束 */ protected void onDestroy() { super.onDestroy(); unregisterReceiver(myBroadcastReceiver); // 注销广播 } /** * 应用运行 */ protected void onResume() { super.onResume(); // 动态注册广播 this.registerReceiver(myBroadcastReceiver, new IntentFilter( Intent.ACTION_BATTERY_CHANGED)); } // 广播接收者 private BroadcastReceiver myBroadcastReceiver = new BroadcastReceiver() { public void onReceive(Context context, Intent intent) { if(intent.getAction().equals(Intent.ACTION_BATTERY_CHANGED)){ // 判断是否为电量广播 // 获取电量信息 int level = intent.getIntExtra("level",0); // 当前电量 int scale = intent.getIntExtra("scale",0); // 总电量 Log.i("msg","level:"+ level+" scale:"+scale); battery.setText("当前电量:"+((level*100/scale)+"%")); } } }; }