3

我有一个代码,我需要获取我的 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 中的 onReceive 方法中放置了一个 BreakPoint,但此代码仅在执行 onStartCommand 后执行,并且需要将电池电量的值用于 onStartCommand。

我该怎么做?

4

3 回答 3

4

您是否将以下权限添加到您的主要文件中:

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

并将您的 onReceived 方法更改为:

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

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

registerReceiver( batteryReceiver, new IntentFilter(Intent.ACTION_BATTERY_CHANGED) );
于 2013-01-18T19:12:29.687 回答
1

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

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

于 2013-01-18T19:54:31.680 回答
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);

}
于 2013-01-21T11:57:38.757 回答