【问题标题】:BroadcastReceiver in activity活动中的广播接收器
【发布时间】:2014-10-30 10:54:44
【问题描述】:

我想更改我的活动的 KeepScreenOn 值,因此我想在活动中使用广播接收器。我在 onCreate 中注册接收器:

registerReceiver(receiver, new IntentFilter("ACTION_POWER_CONNECTED"));
            registerReceiver(receiver, new IntentFilter("ACTION_POWER_DISCONNECTED"));

并在 onPause 中取消注册:

unregisterReceiver(receiver);

接收器如下所示:

    private BroadcastReceiver receiver = new BroadcastReceiver(){
    @Override
    public void onReceive(Context context, Intent intent) {
        String action = intent.getAction();
        if (action.equals(Intent.ACTION_POWER_CONNECTED)) {
            findViewById(R.id.fullscreen_content).setKeepScreenOn(true);
        } else if (action.equals(Intent.ACTION_POWER_DISCONNECTED)) {
            media=MediaPlayer.create(context,R.raw.battery);
            media.start();
            findViewById(R.id.fullscreen_content).setKeepScreenOn(false);
        }
    }
};

没有错误,断开/连接到电源时它根本不会改变任何东西。有什么建议吗?

【问题讨论】:

  • “但它根本不起作用”,那么发生了什么?任何错误/异常?
  • 没有错误,断开/连接到电源时它根本不会改变任何东西。
  • 您是否尝试过调试检查它是否正在执行接收器块?
  • 如果还没有添加,也要添加manifest权限

标签: android broadcastreceiver


【解决方案1】:

你应该使用定义的常量,而不是字符串值:

IntentFilter(Intent.ACTION_POWER_CONNECTED)

而不是:

IntentFilter("ACTION_POWER_CONNECTED")

【讨论】:

    【解决方案2】:

    首先在你的接收器中设置调试点,看看它是否真的在触发

    如果不是那么:

    我现在没有坐在我的 IDE 中,但我认为这不会起作用,因为您使用不同的过滤器注册相同的接收器,第二个将覆盖第一个操作。

    如果您希望一个接收器具有多个操作,您应该创建一个过滤器并使用 IntentFilter addAction() 方法向其添加多个操作。然后当你的接收者被调用时,你应该使用 Intent getAction() 方法来确定触发了哪个动作。

    您也应该只在onStart 或onResume 中注册您的接收器。

    如果它正在触发:

    为了让屏幕保持开启,请在此处尝试解决方案:Keep Screen On Flag

    【讨论】:

      【解决方案3】:

      您在AndroidManifest.xml 中有注册的Receiver 操作吗?

          <receiver android:name="com.app.example.firstapp.MyReceiver">
                  <intent-filter>
                      <action android:name="android.intent.action.SCREEN_OFF"></action>
                      <action android:name="android.intent.action.SCREEN_ON"></action>
                      <action android:name="android.intent.action.ACTION_POWER_CONNECTED"></action>
                      <action android:name="android.intent.action.ACTION_POWER_DISCONNECTED"></action>
                       <action android:name="android.intent.action.ACTION_SHUTDOWN"></action>
                  </intent-filter>
              </receiver>
      

      别忘了添加权限

      <uses-permission android:name="android.permission.BATTERY_STATS"/>
      

      【讨论】:

      • 即使不是独立类也必须在Manifest中注册吗?它在我的活动中。
      • 尝试通过intent filter在receiver中注册以上所有动作。
      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2018-03-13
      相关资源
      最近更新 更多