当电池电量变化时,BroadcastReceiver的onReceive未被调用

时间:2015-09-23 01:06:26

标签: android broadcastreceiver android-broadcastreceiver

我有使用BATTERY_CHANGED IntentFilter的BroadcastReceiver。当我尝试发送广播时,onReceive没有打电话。怎么了?这是清单

中的接收者描述
<receiver android:name=".receivers.BatteryReceiver">
        <intent-filter>
            <action android:name="android.intent.action.BATTERY_CHANGED"/>
        </intent-filter>
    </receiver>

我的BroadcastReceiver

public class BatteryReceiver extends BroadcastReceiver {
@Override
public void onReceive(Context context, Intent intent) {
    Log.d("tag", "onRecv");
    int level = intent.getIntExtra(BatteryManager.EXTRA_LEVEL, -1);
    int scale = intent.getIntExtra(BatteryManager.EXTRA_SCALE, -1);
    if (level != -1 && scale != -1) {
        float batteryPct = level / (float) scale;
        if (batteryPct < 30) {
            NotificationBuilder.notifyWithActions(context, R.drawable.ic_info_black_24dp,
                    context.getResources().getString(R.string.app_name),
                    context.getResources().getString(R.string.battery),
                    context.getResources().getInteger(R.integer.battery));
        }
    }
}`}

我试试

LocalBroadcastManager.getInstance(this).sendBroadcast(new Intent(Intent.ACTION_BATTERY_CHANGED));

2 个答案:

答案 0 :(得分:3)

我正在尝试这种用于电池电量检测的广播,但它不起作用。 然后,对于此任务,我使用在MainActivity中创建广播并使用操作Intent.ACTION_BATTERY_CHANGED注册它,并且不需要在manifest.xml中注册接收器,它可以更好地工作。

此处每当电池电量发生变化时,就会执行onReceive(上下文c,意图i)块中的广播呼叫和任务。

public class MainActivity extends Activity {
private BroadcastReceiver BatteryReceiver = new BroadcastReceiver() {
    public void onReceive(Context c, Intent i) {

        // Getting level of Battery   
        int level = i.getIntExtra("level", 0);
        Toast.makeText(MainActivity.this,"Battery Level:" +Integer.toString(level) + "%",
                    Toast.LENGTH_SHORT).show();
        // For any Level you have to check here.
        if (level == 100) {
            Toast.makeText(MainActivity.this, "Battery Full",
                    Toast.LENGTH_SHORT).show();
        }

    }
};

@Override
protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.main);
    // Register receiver with Action and no need to define Broadcast in manifest.xml
    registerReceiver(BatteryReceiver, new IntentFilter(Intent.ACTION_BATTERY_CHANGED));
   }
}

答案 1 :(得分:0)

您可以通过adb发送虚假系统广播:

adb shell am broadcast "intent:#Intent;action=android.intent.action.BATTERY_CHANGED;i.status=5;i.voltage=4155;i.level=100;end"