2014-12-19 48 views
1

我正在嘗試使用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(); 
       } 
      } 


     } 
    }; 


} 
+0

你爲什麼使用SQLite? – 2014-12-19 05:33:59

+0

在AndroidManifest.xml中註冊'BroadcastReceiver'並使用Service('IntentService')而不是'BroadcastReceiver'的onReceive'方法在應用程序不運行時更新db – 2014-12-19 05:36:25

+0

我該怎麼做?你可以請發表一個修改後的代碼的答案嗎?如果BatteryManager不應該註冊,我如何在AndroidManifest.xml中註冊? – 2014-12-19 05:43:39

回答

0

在manifest文件創建命名爲廣播

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> 

希望這將很好地工作爲您的要求。

+0

這正是我想要做的!謝謝! – 2014-12-19 06:00:55

+0

歡迎光臨dude.nice知道!!!! – 2014-12-19 06:02:34

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; 
+0

我該怎麼做數學? – 2014-12-19 05:49:43

0

該文檔解釋它很體面。嘗試直接在Manifest中註冊電池更新,而不是以編程方式註冊廣播。

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

注: 目前還沒有一種爲特定的電池水平註冊。例如安卓確定何時播出的「android.intent.action.ACTION_BATTERY_LOW」,並根據溫度,電話這可能會有所不同...

您可以爲不同的意圖註冊,然後使用確定確切的電池電量:http://developer.android.com/training/monitoring-device-state/battery-monitoring.html#CurrentLevel

也是一個'不錯'的開發者嘗試和修改你需要的電池意圖。喚醒你的手機往往會消耗電池,用戶不會理解這一點。

最後:

注意到,你有一些SQL代碼在那裏。除非在廣播接收器中有一個喚醒鎖定,否則這種情況很可能不會完成。