ACTION_BATTERY_CHANGED不起作用

时间:2018-03-25 13:55:50

标签: java android apk

我的电池状态应用在Androidstudio中遇到了一个小问题。我有以下接收器:

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

PowerConnectionReceiver仅适用于ACTION_POWER_ *事件。电池更换事件无效

public class PowerConnectionReceiver extends BroadcastReceiver {
public void onReceive(Context context, Intent intent) {

    if (intent.getAction().equals(Intent.ACTION_POWER_CONNECTED)) 
        Toast.makeText(context, "Loading", Toast.LENGTH_SHORT).show();  

    else if (intent.getAction().equals(Intent.ACTION_POWER_DISCONNECTED)) 
        Toast.makeText(context, "not loading", Toast.LENGTH_SHORT).show();

    Toast.makeText(context, "test toast", Toast.LENGTH_SHORT).show();
}
}



Intent intent = getApplicationContext().registerReceiver(null, new IntentFilter(Intent.ACTION_BATTERY_CHANGED));

1 个答案:

答案 0 :(得分:0)

您忘记了实例化PowerConnectionReceiver

Intent intent = getApplicationContext().registerReceiver(null, new IntentFilter(Intent.ACTION_BATTERY_CHANGED));

应该是

Intent intent = getApplicationContext().registerReceiver(PowerConnectionReceiver() , new IntentFilter(Intent.ACTION_BATTERY_CHANGED));

更好的方法是保留引用,以便您可以在onStop()中重新注册。

相关问题