使用Android服务中的BroadcastReceiver获取电池电量

时间:2013-01-18 18:58:14

标签: android service battery batterylevel

我有一个代码,我需要获得我的Android设备的电池电量,但我有一个大问题。我有一个Android服务,我可以获得电池电量并通过UDP发送。

这是我的服务代码:

public class Servico extends Service {

String bateria = "Nada";

/*
 * Recupera nível de bateria
 */
private BroadcastReceiver BatInfoReceiver = new BroadcastReceiver() {
    @Override
    public void onReceive(Context arg0, Intent intent) {
        int level = intent.getIntExtra(BatteryManager.EXTRA_LEVEL, 0);
        bateria = String.valueOf(level);
    }
};

public void onCreate() {
    super.onCreate();
    this.registerReceiver(this.BatInfoReceiver, new IntentFilter(Intent.ACTION_BATTERY_CHANGED));
}

@Override
public int onStartCommand(Intent intent, int flags, int startId) {
    Toast.makeText(getApplicationContext(), "Command=" + bateria + "%", Toast.LENGTH_LONG).show();
    stopSelf();
    return START_STICKY;
}

@Override
public void onDestroy() {
    super.onDestroy();
    unregisterReceiver(BatInfoReceiver);
}

@Override
public IBinder onBind(Intent arg0) {
    // TODO Auto-generated method stub
    return null;
}

}

我的问题是:我无法达到水平!我在BatInfoReceiver中将BreakPoint放入onReceive方法,但此代码仅在执行onStartCommand后执行,并且e NEED将电池级别的值用于onStartCommand。

我该怎么做?

3 个答案:

答案 0 :(得分:3)

您是否在清单文件中添加了以下权限:

<uses-permission android:name="android.permission.READ_PHONE_STATE"/>

并将您的onReceive方法更改为:

private BroadcastReceiver batteryReceiver = new BroadcastReceiver() {
        @Override
        public void onReceive( Context context, Intent intent )
            {
                int level = intent.getIntExtra( "level", 0 );
                bat= String.valueOf(level) + "%" ;
            }
    };

并获取battrey级别使用这行代码:

registerReceiver( batteryReceiver, new IntentFilter(Intent.ACTION_BATTERY_CHANGED) );

答案 1 :(得分:1)

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

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

答案 2 :(得分:1)

我的问题的解决方案是tyczj的答案,我只是适应了我的问题。

我的新代码:

public void onCreate() {
    super.onCreate();

    //registerReceiver(BatInfoReceiver, new IntentFilter(Intent.ACTION_BATTERY_CHANGED));

    IntentFilter ifilter = new IntentFilter(Intent.ACTION_BATTERY_CHANGED);
    Intent batteryStatus = getApplicationContext().registerReceiver(null, ifilter);

    // Are we charging / charged?
    int status = batteryStatus.getIntExtra(BatteryManager.EXTRA_LEVEL, -1);
    bateria = String.valueOf(status);

}