2012-07-22 21 views
5
@Override 
public void onReceive(Context context, Intent intent) { 
int status = intent.getIntExtra(BatteryManager.EXTRA_STATUS, 
    BatteryManager.BATTERY_STATUS_UNKNOWN); 

    if (status == BatteryManager.BATTERY_STATUS_CHARGING 
     || status == BatteryManager.BATTERY_STATUS_FULL) 
     Toast.makeText(context, "Charging!", Toast.LENGTH_SHORT).show(); 
    else 
     Toast.makeText(context, "Not Charging!", Toast.LENGTH_SHORT).show(); 
} 

Manifiesto:estado de la batería no se está cargando

<receiver android:name=".receiver.BatteryReceiver"> 
    <intent-filter> 
     <action android:name="android.intent.action.ACTION_POWER_CONNECTED"/> 
     <action android:name="android.intent.action.ACTION_POWER_DISCONNECTED"/> 
     <action android:name="android.intent.action.BATTERY_CHANGED" /> 
    </intent-filter> 
</receiver> 

En este código, la tostada siempre muestra "No Carga!". Probé esto en un dispositivo real, y cuando lo conecto a una fuente de alimentación de CA o USB, todavía muestra "No cargando". Tostada.

+0

que hay algo mal con su intent.getIntExtra, comprobar que este método se está llamando desde y asegúrese de que está configurando la intención con los parámetros correctos – John

+0

¿Cuál es el estado que está obteniendo? – zmbq

+0

@John Lo estoy usando en mi manifiesto. –

Respuesta

6

No puede registrarse para ACTION_BATTERY_CHANGED a través del manifiesto, por lo que no recibirá esas transmisiones. Está intentando obtener BatteryManager extras de Intents que no tienen esos extras (por ejemplo, ACTION_POWER_CONNECTED). Como resultado, obtiene el valor predeterminado de BATTERY_STATUS_UNKNOWN.

+0

Entonces, ¿cómo registrarlo programáticamente? –

+0

@MohitDeshpande: llame a 'registerReceiver()', de la misma manera que registraría cualquier otro 'BroadcastReceiver' programmatically. Ver: https://github.com/commonsguy/cw-omnibus/tree/master/SystemEvents/OnBattery – CommonsWare

2

intente lo siguiente:

IntentFilter ifilter = new IntentFilter(Intent.ACTION_BATTERY_CHANGED); 
Intent batteryStatus = context.registerReceiver(null, ifilter); 
int status = batteryStatus.getIntExtra(BatteryManager.EXTRA_STATUS, -1); 

'status' ahora será un valor entre 1 y 5:

1 = Unknown 
2 = Charging 
3 = Discharging 
4 = Not Charging 
5 = Full 

Su código:

if (status == BatteryManager.BATTERY_STATUS_CHARGING 
    || status == BatteryManager.BATTERY_STATUS_FULL) ... 

puede escribirse:

if (status == 2 || status == 5) ... 

Ambos son idénticos porque BatteryManager.BATTERY_STATUS_CHARGING es una constante que siempre es igual a 2, y BatteryManager.BATTERY_STATUS_FULL es una constante que siempre es igual a 5.

+0

Buena respuesta, pero por favor no use números mágicos en el código: http://stackoverflow.com/questions/47882/what -is-a-magic-number-and-why-is-it-bad – kellogs

Cuestiones relacionadas