0

我有带有 BATTERY_CHANGED IntentFilter 的 BroadcastReceiver。当我尝试发送广播时, onReceive 不会调用。怎么了?这是我在清单中的接收器描述

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

我的广播接收器

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));
4

2 回答 2

3

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

在这里,只要电池电量发生变化,就会执行 onReceive(Context c, Intent 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));
   }
}
于 2015-09-23T04:29:25.883 回答
0

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

adb shell am broadcast "intent:#Intent;action=android.intent.action.BATTERY_CHANGED;i.status=5;i.voltage=4155;i.level=100;end"
于 2015-09-23T03:40:02.507 回答