如何在运行时获取 Android 中的电池统计信息?
Posted
技术标签:
【中文标题】如何在运行时获取 Android 中的电池统计信息?【英文标题】:How to obtain Battery Stats in Android at runtime? 【发布时间】:2010-02-15 13:04:36 【问题描述】:我想在我的应用中显示电池电量统计信息。如何获取电池电量、电池电压等信息?
【问题讨论】:
android Battery in SDK 的可能重复项 【参考方案1】: BroadcastReceiver batteryLevelReceiver = new BroadcastReceiver()
public void onReceive(Context context, Intent intent)
context.unregisterReceiver(this);
int rawlevel = intent.getIntExtra("level", -1);
int scale = intent.getIntExtra("scale", -1);
int level = -1;
if (rawlevel >= 0 && scale > 0)
level = (rawlevel * 100) / scale; /* This is your battery level */
;
IntentFilter batteryLevelFilter = new IntentFilter(Intent.ACTION_BATTERY_CHANGED);
registerReceiver(batteryLevelReceiver, batteryLevelFilter);
或查看这个人(他编写了我发布的代码):http://mihaifonoage.blogspot.com/2010/02/getting-battery-level-in-android-using.html
【讨论】:
【参考方案2】:this 有什么帮助吗?
public class Main extends Activity
private TextView contentTxt;
private BroadcastReceiver mBatInfoReceiver = new BroadcastReceiver()
@Override
public void onReceive(Context arg0, Intent intent)
// TODO Auto-generated method stub
int level = intent.getIntExtra("level", 0);
contentTxt.setText(String.valueOf(level) + "%");
;
@Override
public void onCreate(Bundle icicle)
super.onCreate(icicle);
setContentView(R.layout.main);
contentTxt = (TextView) this.findViewById(R.id.monospaceTxt);
this.registerReceiver(this.mBatInfoReceiver,
new IntentFilter(Intent.ACTION_BATTERY_CHANGED));
另外,请参阅this。
【讨论】:
以上是关于如何在运行时获取 Android 中的电池统计信息?的主要内容,如果未能解决你的问题,请参考以下文章
Android:如何在状态栏中获取电池图标资源 ID 或完整文件路径/名称?