繁体   English   中英

从Activity调用BroadcastReceiver

[英]calling BroadcastReceiver from Activity

我是android编程的新手; 抱歉,如果我的问题很简单:)我正在尝试编写代码以监视手机上的电池电量,如果是,则降低电池电量(例如,%15),创建一条消息,要求用户插入充电器。 我知道我需要使用BroadcastReceiver类,并且要在MainActivity类中使用它。 这是我的代码:

public class MainActivity extends Activity{
BroadcastReceiver br = new BroadcastReceiver() {
    @Override
    public void onReceive(final Context context, Intent intent) {
        String intentAction = intent.getAction();
        Log.d("receiver", intentAction);
        int level = intent.getIntExtra("level", 0);
        if (level < 15){
            Log.d("receiver", "battery level low");
        }

        if (Intent.ACTION_BATTERY_OKAY.equalsIgnoreCase(intentAction)) {
            Log.d("receiver", "battery level okay");
        }
    }
};
......

但是似乎从未调用过onReceive方法,因为我在Android Studio调试窗口上从未看到Log.d("receiver", intentAction)消息。 我也在onResume注册了br ,并在onPause取消了注册:

public void onResume() {
    super.onResume();
    filter.addAction("receiver");
    registerReceiver(br, filter);
}

public void onPause() {
    super.onPause();
    unregisterReceiver(br);
}

但是我仍然没有收到任何消息。 有人可以帮我吗? 我还应该在AndroidManifest.xml添加一些内容吗?

您在onResume()代码是错误的。 您将必须按以下方式对其进行更新。

    filter.addAction(Intent.ACTION_BATTERY_LOW);
    filter.addAction(Intent.ACTION_BATTERY_OKAY);
    registerReceiver(br, filter);

包含docs中提到的ACTION_BATTERY_LOWACTION_BATTERY_OKAY过滤器。

如果您不想使用BroadcastReceiver,那就不要使用它。 电池意图是粘性意图,因此您可以在不需要BroadcastReceiver的情况下进行检查,而且我也不认为将接收器置于活动状态是个好主意。 您可以像这样检查活动中的电池内容,而无需编辑清单

IntentFilter filter = new IntentFilter(Intent.ACTION_BATTERY_CHANGED);
Intent batteryStatus = context.registerReceiver(null, filter);
int level = batteryStatus.getIntExtra(BatteryManager.EXTRA_LEVEL, -1);
int scale = batteryStatus.getIntExtra(BatteryManager.EXTRA_SCALE, -1);
float batteryPct = level / (float)scale;
if(batteryPct < 15){
    //do your stuff
}

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM