电池的广播接收器不工作

时间:2014-12-19 05:31:32

标签: android android-intent broadcastreceiver batterymanager

我正在尝试将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();
                }   
            }


        }
    };


}

3 个答案:

答案 0 :(得分:0)

根据BatteryManager API docsEXTRA_LEVEL似乎是整数值,但不一定代表百分比。相反,它相对于EXTRA_SCALE,这是最大可能值。

您无法与20之类的硬编码幻数进行比较。要转换为百分比,您需要自己进行数学运算。

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

答案 1 :(得分:0)

创建一个名为broadcast

的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();

    }
}
清单文件中的

请添加

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

希望它能完美地满足您的要求。

答案 2 :(得分:0)

文档解释得相当不错。尝试直接在Manifest中注册电池更新,而不是以编程方式注册广播。

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

注意: 目前无法注册特定的电池电量。例如,android确定何时广播“android.intent.action.ACTION_BATTERY_LOW”,这可能因温度,手机而有所不同......

您可以注册不同的意图,然后使用以下方法确定准确的电池电量:http://developer.android.com/training/monitoring-device-state/battery-monitoring.html#CurrentLevel

同样要成为一名'好'的开发人员,请尝试修改您需要的电池意图。通常唤醒手机会消耗电池,用户不会对此感到欣慰。

<强>最后:

注意到那里有一些SQL代码。除非您在广播接收器中有唤醒锁定,否则这很可能无法完成。