• android 电量


    引用:http://onetiger.net/?p=1057

    在android中,要获得手机的电量的话,可以通过intent广播去实现,监听
    action_battery_changed,例子如下:

    package com.liao;
    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 BatteryLevelActivity extends Activity {
    /** Called when the activity is first created. */
    private TextView batterLevel;

    @Override
    /**
    * Called when the current activity is first created.
    */
    public void onCreate(Bundle icicle) {
    super.onCreate(icicle);
    setContentView(R.layout.main);
    batterLevel = (TextView) this.findViewById(R.id.batteryLevel);
    batteryLevel();
    }

    private void batteryLevel() {
    BroadcastReceiver batteryLevelReceiver = new BroadcastReceiver() {
    public void onReceive(Context context, Intent intent) {
    context.unregisterReceiver(this);
    int rawlevel = intent.getIntExtra("level", -1);//获得当前电量
    int scale = intent.getIntExtra("scale", -1);
    //获得总电量
    int level = -1;
    if (rawlevel >= 0 && scale > 0) {
    level = (rawlevel * 100) / scale;
    }
    batterLevel.setText("Battery Level Remaining: " + level + "%");
    }
    };
    IntentFilter batteryLevelFilter = new IntentFilter(Intent.ACTION_BATTERY_CHANGED);
    registerReceiver(batteryLevelReceiver, batteryLevelFilter);
    }

    }

    如果是2。0后的SDK,也可以这样:
    public void onReceive(Context context, Intent intent) {
    context.unregisterReceiver(this);
    int rawlevel = intent.getIntExtra(BatteryManager.EXTRA_LEVEL, -1);
    int scale = intent.getIntExtra(BatteryManager.EXTRA_SCALE, -1);

    就是修改一下类而已

  • 相关阅读:
    [Leetcode Weekly Contest]285
    [Leetcode Weekly Contest]286
    [Leetcode Weekly Contest]284
    [Leetcode Weekly Contest]287
    阿凡达机器人简介
    PS常用组合键
    PhotoshopCS6 后退多步
    如何卸载Creative Cloud?
    五月实际
    SSO 方案演进
  • 原文地址:https://www.cnblogs.com/sode/p/2758456.html
Copyright © 2020-2023  润新知