我正在尝试将 BroadcastReceiver 用于电池状态,并在其电量低于 20% 且未充电时执行某些操作。问题是当电池电量不足 20% 时它就无法工作。
这是代码,我希望有人可以帮助我:
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();
}
}
}
};
}