擷取Android裝置電池電量狀態

來源:互聯網
上載者:User

Android開發人員可以利用BroadcastReceiver機制,擷取電池電量變化的ACTION_BATTERY_CHANGED intent,進而擷取當前android裝置的電池狀態。
具體操作步驟:
1. 建立一個監聽ACTION_BATTERY_CHANGED事件的intentFilter。
2. 建立一個BroadcastReceiver對象,該對象可以接收broadcast intent。
3. 註冊BroadcastReceiver對象來監聽ACTION_BATTERY_CHANGED事件。
4. 在BroadcastReceiver對象中,重寫onReceive方法,在onReceive方法的傳入參數intent裡擷取需要的電池狀態資訊。

5. 在生命週期結束時,取消step4中的註冊。

package com.chen.battery;import android.os.BatteryManager;import android.os.Bundle;import android.app.Activity;import android.content.BroadcastReceiver;import android.content.Context;import android.content.Intent;import android.content.IntentFilter;import android.view.Menu;import android.view.TextureView;import android.widget.TextView;public class MainActivity extends Activity {@Overrideprotected void onDestroy() {// TODO Auto-generated method stubsuper.onDestroy();}private TextView batterLevel;private BroadcastReceiver batteryLevelRcvr;private IntentFilter batteryLevelFilter;@Overrideprotected void onCreate(Bundle savedInstanceState) {super.onCreate(savedInstanceState);setContentView(R.layout.activity_main);batterLevel = (TextView)findViewById(R.id.batteryLevel);monitorBatteryState();}private void monitorBatteryState(){batteryLevelRcvr = new BroadcastReceiver(){@Overridepublic void onReceive(Context context, Intent intent) {// TODO Auto-generated method stubStringBuilder sb = new StringBuilder();int rawlevel = intent.getIntExtra("level", -1);int scale = intent.getIntExtra("scale", -1);int status = intent.getIntExtra("status", -1);int health = intent.getIntExtra("health", -1);int level = -1;if(rawlevel >= 0 && scale > 0){level = (rawlevel*100)/scale;}sb.append("電池狀態: ");sb.append(level + "%  ");switch (status) {case BatteryManager.BATTERY_STATUS_UNKNOWN:sb.append("[沒有安裝電池]");break;case BatteryManager.BATTERY_STATUS_CHARGING:sb.append("[正在充電]");break;default:if(level <= 10)sb.append("[電量過低,請充電]");else if (level <= 100) {sb.append("[未串連充電器]");}break;}sb.append(' ');batterLevel.setText(sb.toString());}};batteryLevelFilter = new IntentFilter(Intent.ACTION_BATTERY_CHANGED);registerReceiver(batteryLevelRcvr, batteryLevelFilter);}}
相關文章

聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在5個工作日內處理。

如果您發現本社區中有涉嫌抄襲的內容,歡迎發送郵件至: info-contact@alibabacloud.com 進行舉報並提供相關證據,工作人員會在 5 個工作天內聯絡您,一經查實,本站將立刻刪除涉嫌侵權內容。

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.