如何使用广播接收器获得电池电量

时间:2014-02-28 10:40:08

标签: android

在我的应用程序中,我想检查电池电量是否小于特定值我希望我的应用程序使用文本到语音和服务来说明该级别。 我使用broadcastreciever完成了它,但只有当App在屏幕上运行时它才有效,并且当它在后台运行时不起作用...

public class Batteryreciever extends BroadcastReceiver {
    int level;
    @Override
    public void onReceive(Context context, Intent intent) {
if(intent.getAction().equals("android.intent.action.BATTERY_CHANGED")) { 
            level = intent.getIntExtra(BatteryManager.EXTRA_LEVEL, 0);
            if (level < 10) {
                String batterylevel = "critical battery ";
        Intent i = new Intent(context, MyService.class);
            i.putExtra("KEY1", batterylevel);
                i.putExtra("type", "battery");
            context.startService(i);
            }       
            }
    } }

5 个答案:

答案 0 :(得分:1)

使用粘性广播接收器,你可以获得电池电量,之后你告诉电池电量下降到一定水平,然后执行你想要的任务。

Link并参见This

它会有所帮助,您可以获得更多信息

答案 1 :(得分:0)

看看这个,它会为您提供所需的电池电量,以便您可以开始服务。只需使用BatteryManager.EXTRA_LEVEL作为从意图中获取级别的键

http://developer.android.com/training/monitoring-device-state/battery-monitoring.html

答案 2 :(得分:0)

使用此方法:

public static float getBatteryLevel(Context cntx) {
        Intent batteryIntent = cntx.registerReceiver(null, new IntentFilter(Intent.ACTION_BATTERY_CHANGED));
        int level = batteryIntent.getIntExtra(BatteryManager.EXTRA_LEVEL, -1);
        int scale = batteryIntent.getIntExtra(BatteryManager.EXTRA_SCALE, -1);

        // Error checking that probably isn't needed but I added just in case.
        if(level == -1 || scale == -1) {
            return 50.0f;
        }

        return ((float)level / (float)scale) * 100.0f; 
    }

答案 3 :(得分:0)

尝试此链接以获取电池信息.. http://www.tutorialforandroid.com/2009/01/getting-battery-information-on-android.html

public class Main extends Activity {
  private TextView batteryTxt;
  private BroadcastReceiver mBatInfoReceiver = new BroadcastReceiver(){
    @Override
    public void onReceive(Context ctxt, Intent intent) {
      int level = intent.getIntExtra(BatteryManager.EXTRA_LEVEL, 0);
      batteryTxt.setText(String.valueOf(level) + "%");
    }
  };

  @Override
  public void onCreate(Bundle b) {
    super.onCreate(b);
    setContentView(R.layout.main);
    contentTxt = (TextView) this.findViewById(R.id.batteryTxt);
    this.registerReceiver(this.mBatInfoReceiver, new IntentFilter(Intent.ACTION_BATTERY_CHANGED));
  }
}

答案 4 :(得分:0)

Battery broadcast receiver declared in manifest file does not work? 我的问题的答案在这里,实际上在清单中你不能注册广播接收器的电池更换..