国产探花免费观看_亚洲丰满少妇自慰呻吟_97日韩有码在线_资源在线日韩欧美_一区二区精品毛片,辰东完美世界有声小说,欢乐颂第一季,yy玄幻小说排行榜完本

首頁 > 系統 > Android > 正文

Android獲取手機電池電量用法實例

2020-04-11 11:25:01
字體:
來源:轉載
供稿:網友

本文實例講述了Android獲取手機電池電量用法。分享給大家供大家參考。具體如下:

原理概述:

手機電池電量的獲取在應用程序的開發中也很常用,Android系統中手機電池電量發生變化的消息是通過Intent廣播來實現的,常用的Intent的Action有  Intent.ACTION_BATTERY_CHANGED(電池電量發生改變時)、Intent.ACTION_BATTERY_LOW(電池電量達到下限時)、和Intent.ACTION_BATTERY_OKAY(電池電量從低恢復到高時)。

當需要在程序中獲取電池電量的信息時,需要為應用程序注冊BroadcastReceiver組件,當特定的Action事件發生時,系統將會發出相應的廣播,應用程序就可以通過BroadcastReceiver來接受廣播,并進行相應的處理。

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("現在的電量是"+percent+"%。");    }  }}

運行結果:

希望本文所述對大家的Android程序設計有所幫助。

發表評論 共有條評論
用戶名: 密碼:
驗證碼: 匿名發表
主站蜘蛛池模板: 鄂托克旗| 彝良县| 塔河县| 宿迁市| 辉县市| 定结县| 水富县| 伊金霍洛旗| 西华县| 黔东| 许昌市| 巴林左旗| 剑阁县| 呼和浩特市| 墨脱县| 商南县| 晋城| 翁牛特旗| 二连浩特市| 思茅市| 镶黄旗| 贵南县| 温宿县| 井研县| 法库县| 泾源县| 桐柏县| 集贤县| 西吉县| 延吉市| 萝北县| 秭归县| 三亚市| 博客| 湖口县| 江门市| 凤庆县| 咸宁市| 濮阳县| 镇宁| 曲阜市|