获得G1的电池电量信息

Reading of Battery level on G1

转自 http://www.maximyudin.com/2009/01/05/android/reading-of-battery-level-on-g1/

用1.5sdk编译后试着在自己的G1(已经升级到1。5版本)里跑了一下,果然能得到电池电量。 high

Activity code:

package maximyudin.BatteryLevel;
 
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.TextView;
 
public class BatteryLevel extends Activity {
     private TextView tvBatteryLevel;
 
     private BroadcastReceiver mBatteryInfoReceiver = new BroadcastReceiver() {
          @Override
          public void onReceive(Context context, Intent intent) {
               String action = intent.getAction();
               if (Intent.ACTION_BATTERY_CHANGED.equals(action)) {
 
                    int level = intent.getIntExtra("level", 0);
                    int scale = intent.getIntExtra("scale", 100);
 
                    tvBatteryLevel.setText("Battery level: "
                              + String.valueOf(level * 100 / scale) + "%");
               }
          }
     };
 
     @Override
     public void onResume() {
          super.onResume();
 
          registerReceiver(mBatteryInfoReceiver, new IntentFilter(
                    Intent.ACTION_BATTERY_CHANGED));
     }
 
     @Override
     public void onPause() {
          super.onPause();
 
          unregisterReceiver(mBatteryInfoReceiver);
     }
 
    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.main);
 
        tvBatteryLevel = (TextView) findViewById(R.id.tvBatteryLevel);
    }
}

Activity layout:

<?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"
    >
<TextView  
    android:layout_width="fill_parent"
    android:layout_height="wrap_content"
    android:id="@+id/tvBatteryLevel" android:text="Battery level:"/>
</LinearLayout>
评论
成就一亿技术人!
拼手气红包6.0元
还能输入1000个字符
 
红包 添加红包
表情包 插入表情
 条评论被折叠 查看
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值