电池指示器为Android

时间:2012-03-06 07:04:04

标签: android power-management

我有以下示例代码来指示电池电量。当我运行代码时,它给了我一个强制关闭错误。任何人都知道为什么?

public class ActActivity extends Activity {


      private BroadcastReceiver _batteryinfo = new BroadcastReceiver() {

            @Override
            public void onReceive(Context context, Intent intent) {
                int iBatLevel = intent.getIntExtra(BatteryManager.EXTRA_LEVEL, 0);
                /*ProgressBar _batPB = (ProgressBar) findViewById(R.id.progressBar);
                _batPB.setProgress(iBatLevel);
                TextView _batText = (TextView) findViewById(R.id.batterylevel);
                _batText.setText("Battery level:"+Integer.toString(iBatLevel)+"%");
                */
                Toast.makeText(context, iBatLevel, Toast.LENGTH_SHORT).show();

            }
        };


    /** Called when the activity is first created. */
    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.main);
        registerReceiver(_batteryinfo, new IntentFilter(Intent.ACTION_BATTERY_CHANGED));
    }

}

我的清单文件中有以下内容虽然我在某处读取了动态接收器创建所不需要的内容。

<receiver android:name=".service.BatteryActivity">
         <intent-filter>
            <action android:name="android.intent.action.BATTERY_CHANGED" />
        </intent-filter>
    </receiver> 

2 个答案:

答案 0 :(得分:0)

使用此代码

   this.registerReceiver(this.mBatInfoReceiver,new      
   IntentFilter(Intent.ACTION_BATTERY_CHANGED));

private BroadcastReceiver mBatInfoReceiver = new BroadcastReceiver()  {
      @Override
      public void onReceive(Context arg0, Intent intent) {          
          int level = intent.getIntExtra("level", 0);      
      } 
}

答案 1 :(得分:0)

检查此链接我认为您需要在清单中添加权限 http://developer.android.com/reference/android/Manifest.permission.html#BATTERY_STATS

public static final String BATTERY_STATS 自:API Level 1

允许应用程序收集电池统计信息 常量值:“android.permission.BATTERY_STATS”

也 在onReceive内部,基于版本&lt;级别“项目(电池级别)检索数据。 5,或使用BatteryManager.EXTRA_LEVEL版本&gt; = 5。