Android獲取手機電池電量用法實例
本文實例講述了Android獲取手機電池電量用法。分享給大家供大家參考。具體如下:
原理概述:
手機電池電量的獲取在應(yīng)用程序的開發(fā)中也很常用,Android系統(tǒng)中手機電池電量發(fā)生變化的消息是通過Intent廣播來實現(xiàn)的,常用的Intent的Action有 Intent.ACTION_BATTERY_CHANGED(電池電量發(fā)生改變時)、Intent.ACTION_BATTERY_LOW(電池電量達到下限時)、和Intent.ACTION_BATTERY_OKAY(電池電量從低恢復(fù)到高時)。
當需要在程序中獲取電池電量的信息時,需要為應(yīng)用程序注冊BroadcastReceiver組件,當特定的Action事件發(fā)生時,系統(tǒng)將會發(fā)出相應(yīng)的廣播,應(yīng)用程序就可以通過BroadcastReceiver來接受廣播,并進行相應(yīng)的處理。
main.xml布局文件:
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:orientation="vertical"
android:layout_width="fill_parent"
android:layout_height="fill_parent">
<ToggleButton android:id="@+id/tb"
android:layout_width="fill_parent"
android:layout_height="wrap_content"
android:textOn="停止獲取電量信息"
android:textOff="獲取電量信息" />
<TextView android:id="@+id/tv"
android:layout_width="fill_parent"
android:layout_height="wrap_content" />
</LinearLayout>
BatteryActivity類:
package com.ljq.activity;
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.widget.CompoundButton;
import android.widget.TextView;
import android.widget.ToggleButton;
import android.widget.CompoundButton.OnCheckedChangeListener;
public class BatteryActivity extends Activity {
private ToggleButton tb=null;
private TextView tv=null;
private BatteryReceiver receiver=null;
@Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.main);
receiver=new BatteryReceiver();
tv=(TextView)findViewById(R.id.tv);
tb=(ToggleButton)findViewById(R.id.tb);
tb.setOnCheckedChangeListener(new OnCheckedChangeListener(){
public void onCheckedChanged(CompoundButton compoundButton, boolean isChecked) {
//獲取電池電量
if(isChecked){
IntentFilter filter=new IntentFilter(Intent.ACTION_BATTERY_CHANGED);
registerReceiver(receiver, filter);//注冊BroadcastReceiver
}else {
//停止獲取電池電量
unregisterReceiver(receiver);
tv.setText(null);
}
}
});
}
private class BatteryReceiver extends BroadcastReceiver{
@Override
public void onReceive(Context context, Intent intent) {
int current=intent.getExtras().getInt("level");//獲得當前電量
int total=intent.getExtras().getInt("scale");//獲得總電量
int percent=current*100/total;
tv.setText("現(xiàn)在的電量是"+percent+"%。");
}
}
}
運行結(jié)果:

希望本文所述對大家的Android程序設(shè)計有所幫助。
相關(guān)文章
解決Android Studio突然不顯示logcat日志的問題
這篇文章主要介紹了解決Android Studio突然不顯示logcat日志的問題,具有很好的參考價值,希望對大家有所幫助。一起跟隨小編過來看看吧2020-04-04
Kotlin 協(xié)程與掛起函數(shù)及suspend關(guān)鍵字深入理解
這篇文章主要為大家介紹了Kotlin 協(xié)程與掛起函數(shù)及suspend關(guān)鍵字深入理解,有需要的朋友可以借鑒參考下,希望能夠有所幫助,祝大家多多進步,早日升職加薪2022-12-12
Android利用Theme自定義Activity間的切換動畫
這篇文章主要為大家詳細介紹了Android利用Theme自定義Activity間的切換動畫,感興趣的小伙伴們可以參考一下2016-09-09

