Broadcast receiver for Battery isn't working

1.4k views Asked by At

I'm trying to use a BroadcastReceiver for the battery state, and do something when its level is below 20% and it's not charging. The problem is that it just doesn't work when the battery goes 20%.

Here's the code, I hope somebody can help me:

public class BatteryStateReceiver extends Activity {
    AccionesExecuter Ejecutor = new AccionesExecuter();
    /** Called when the activity is first created. */
    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);        
        this.registerReceiver(this.batteryInfoReceiver, new IntentFilter(Intent.ACTION_BATTERY_CHANGED));
    }

    private BroadcastReceiver batteryInfoReceiver = new BroadcastReceiver() {
        @Override
        public void onReceive(Context contexto, Intent intent) {
            Log.e("ReceiverBatería", "Recibió");
            int  level= intent.getIntExtra(BatteryManager.EXTRA_LEVEL,0);
            int  plugged= intent.getIntExtra(BatteryManager.EXTRA_PLUGGED,0);

            if(level <= 20 && plugged == 0)
            {
                Log.e("If", "Entró");
                Action ac = new Action(0, 0, 0, false);
                //ACTIONS
                ActionsSQLite base = new ActionsSQLite(contexto, "Actions", null,1);
                SQLiteDatabase db1 = base.getReadableDatabase();
                db1 = contexto.openOrCreateDatabase("Actions",SQLiteDatabase.OPEN_READONLY, null);

                String query = "SELECT * FROM Actions WHERE IdEvento = 2";
                Cursor c1 = db1.rawQuery(query, null);

                try{
                    if(c1!=null){

                        int i = c1.getColumnIndexOrThrow("Id");
                        int j = c1.getColumnIndexOrThrow("IdAccion");
                        int k = c1.getColumnIndexOrThrow("IdEvento");
                        int l = c1.getColumnIndexOrThrow("Activa");
                        boolean esActiva;

                        //Nos aseguramos de que existe al menos un registro
                        while(c1.moveToNext()){
                            if (c1.getInt(l) == 0){
                                esActiva = false;
                            } else
                            {
                                esActiva = true;
                            }
                            //Recorremos el cursor hasta que no haya más registros
                            ac = new Action(c1.getInt(i), c1.getInt(j), c1.getInt(k), esActiva);
                            if (esActiva == true){ //Si está activa, la ejecuta, sino no
                            Ejecutor.execute(contexto, ac.getIdAccion());
                            Log.e("Action ejecutada, Id: ", String.valueOf(ac.getId()));
                            }
                        }
                    }
                    else 
                        Toast.makeText(contexto, 
                                  "No hay nada :(", Toast.LENGTH_LONG).show();
                  }
                  catch (Exception e){
                    Log.i("bdActions", "Error al abrir o crear la base de datos" + e); 
                  }

                  if(db1!=null){
                        db1.close();
                }   
            }


        }
    };


}
3

There are 3 answers

1
Rituraj suman On BEST ANSWER

Create a Broadcast class named as broadcast

public class broadcast extends BroadcastReceiver {

    @Override
    public void onReceive(Context context, Intent intent) {
        // TODO Auto-generated method stub

        Toast.makeText(context, "Broadcast recieved", Toast.LENGTH_LONG).show();

    }
}

in your manifest file Please add

<receiver android:name="com.example.baterry.broadcast" >
            <intent-filter>
                <action android:name="android.intent.action.BATTERY_LOW" >
                </action>
            </intent-filter>

Hopefully it will work perfectly for your requirement.

1
William Price On

According to the BatteryManager API docs, EXTRA_LEVEL appears to be an integer value but does not necessarily represent a percentage. Instead, it is relative to EXTRA_SCALE, which is the maximum possible value.

You cannot compare to a hardcoded magic number like 20. To convert to a percentage you'll need to do the math yourself.

int level = intent.getIntExtra(BatteryManager.EXTRA_LEVEL, 0);
int scale = intent.getIntExtra(BatteryManager.EXTRA_SCALE, 1);
int percent_level = (level * 100) / scale;
0
toidiu On

The docs explain it pretty decently. Try registering for battery updates in the Manifest directly rather than registering for the broadcast programatically.

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

Note: There is currently no way to register for a specific battery level. For example android determines when to broadcast "android.intent.action.ACTION_BATTERY_LOW" and this might differ depending on temperature, phone...

You can register for different intents and then determine the exact battery level using: http://developer.android.com/training/monitoring-device-state/battery-monitoring.html#CurrentLevel

Also to be a 'nice' developer try and revise which battery intents you need. Waking up your phone too often consumes battery and users wont appreciate this.

Lastly:

Noticed that you have some SQL code in there. This most likely could potentially not complete unless you have a wake lock in the Broadcast Receiver.