2

I'm trying to get Battery state. I use this code :

public class BatteryLevelReceiver extends BroadcastReceiver {
SharedPreferences prefs;
int scale = -1;
int level = -1;

@Override
public void onReceive(Context context, Intent intent) {
    prefs = PreferenceManager.getDefaultSharedPreferences(context);
    level = intent.getIntExtra(BatteryManager.EXTRA_LEVEL, -1);
    scale = intent.getIntExtra(BatteryManager.EXTRA_SCALE, -1);
    // temp = intent.getIntExtra(BatteryManager.EXTRA_TEMPERATURE, -1);
    // voltage = intent.getIntExtra(BatteryManager.EXTRA_VOLTAGE, -1);
    float nivel = level / (float) scale;
    Log.e("level",level+"");
    Log.e("scale",scale+"");
    Log.e("batteryLevel",nivel+"");
}

in AndroidManifest.xml :

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

<receiver android:name="com.spg.receiver.BatteryLevelReceiver" >
        <intent-filter>
            <action android:name="android.intent.action.BATTERY_LOW" />
            <action android:name="android.intent.action.BATTERY_OKAY" />
        </intent-filter>
    </receiver>

With that code, that I got with those threads :

Get battery level and state in Android

BatteryManager stats not working on Android

But each time, level and scale have value -1.

I don't know what am I missing...

Community
  • 1
  • 1
Juliatzin
  • 18,455
  • 40
  • 166
  • 325
  • There's a couple other posts about this... try putting '0' instead of '-1' as the second argument of your level = intent.getIntExtra(BatteryManager.EXTRA_LEVEL, -1); – jesses.co.tt Jul 16 '14 at 22:56
  • Hmmm actually the 2nd argument is the default value, so it'll be interesting to see what it logs, 0 or -1 ... then at least you'll know whether intent is getting fired properly – jesses.co.tt Jul 16 '14 at 22:59
  • I changed it to 0, and now, it get me 0 all the times, so it enters well in Broadcast – Juliatzin Jul 16 '14 at 23:11

1 Answers1

2

BatteryManager provides constants for the ACTION_BATTERY_CHANGED Intent not BATTERY_LOW or BATTERY_OKAY. In addition ACTION_BATTERY_CHANGED must be registered programmatically, which you can do in onCreate. Since it can't be received by a BroadcastReceiver make sure you don't need to use a Service instead, such as you need to receive battery events at startup.

Dan S
  • 9,139
  • 3
  • 37
  • 48
  • I don't understand well the last part of your answer, but I can't find that in official documentation. Can you please tell me more??? – Juliatzin Jul 16 '14 at 23:19
  • I don't know when you need to receive this `Intent` so I'm suggesting you may need to reconsider using `BroadcastReceiver` since you cannot rely on an `Android Manifest` based `IntentFilter` to start your `BroadcastReceiever`. – Dan S Jul 16 '14 at 23:22
  • In the fifth activity, I need to take picture. If low battery, I need to know the battery state, if low, cancel the picture taking and follow the flow. – Juliatzin Jul 16 '14 at 23:24