我将尝试在特定的Activity中显示警报,当充电状态发生变化时。
这是我的receiver类:
public class BatteryChargeReceiver extends BroadcastReceiver {
private String TAG = "receiver";
private ChargeReceiverCallback callback;
public BatteryChargeReceiver(ChargeReceiverCallback callback) {
this.callback =callback;
Log.v(TAG,"Inside Constructor (Callback)");
}
public interface ChargeReceiverCallback {
public void onReceive(Intent intent);
}
@Override
public void onReceive(Context context, Intent intent) {
callback.onReceive(intent);
}
以下是我在MainActivity的onResume中实例化它的方式。MainActivity实现了我的接口并重写了onReceive(intent)方法。我发现无论何时,intent.getIntExtra(BatteryManager.EXTRA_STATUS, -1) 都不会返回除-1以外的任何内容。
BatteryChargeReceiver batteryReceiver = new BatteryChargeReceiver(this);
IntentFilter filterPower = new IntentFilter("android.intent.action.ACTION_POWER_CONNECTED");
registerReceiver(batteryReceiver, filterPower);
BatteryManager.EXTRA_PLUGGED
:intent.getIntExtra(BatteryManager.EXTRA_PLUGGED, -1)
- ozbek"android.intent.action.ACTION_POWER_DISCONNECTED"
广播。 - ozbekEXTRA_PLUGGED
额外参数(而不是EXTRA_STATUS
),您应该相应地更新您的问题内容。onReceive()
中的代码运行完毕后立即被销毁。