1

我正在尝试使用 Android 3.0+ 中的广播接收器来捕获 ACTION_MEDIA_BUTTON 意图。

我的接收器是我的 MainActivity 类的静态内部类。它是静态的,因为它是在我的 AndroidManifest.xml 中注册的,它必须找到类。但是,这意味着当按下播放/暂停按钮时,我的 BroadcastReceiver 无法返回我的活动。onReceive 方法被调用,但由于该类是静态的,我无法通知我的活动。

使用对我的活动或 Handler 对象的引用也不起作用,因为我无法获取 Android 系统正在调用的 BroadcastReceiver 对象。

动态声明接收器也应该可以工作,但这在 Android 3.0+ 上不起作用,出于某种奇怪的原因。它与以下内容有关:

AudioManager.registerMediaButtonEventReceiver(ComponentName)

需要调用哪个。

我的课的一些插图:

   public class MainActivity extends Activity {

        public static class MicReceiver extends BroadcastReceiver {
            // onReceive is called
                // How do I inform MainActivity of the press?
        }
    }

您对修复有任何想法吗?

谢谢!

[编辑] 请参阅下面的代码以动态注册我的接收器:(这目前不起作用)

mReceiver = new RemoteControlReceiver();

IntentFilter filter = new IntentFilter(Intent.ACTION_MEDIA_BUTTON);
filter.setPriority(2147483647);
registerReceiver(mReceiver, filter);

AudioManager am = (AudioManager)getSystemService(Context.AUDIO_SERVICE);
am.registerMediaButtonEventReceiver(new ComponentName(getPackageName(), RemoteControlReceiver.class.getName()));
4

3 回答 3

2

AFAIK,registerMediaButtonEventReceiver()如果您想在后台接收媒体按钮事件。前台活动可以使用标准onKeyDown()回调找到有关媒体按钮事件的信息。

于 2013-06-09T17:53:36.653 回答
0

Declaring receiver in Manifest will try to instantiate the receiver and call onRecieve(), even when activity is not around.

To make it an activity bound receiver, make it a non static class and instantiate it in onCreate(). Then, register and unregister it in onResume() and onPause() respectively. Since class is non static and registered only when activity is active, you can safely call parent activity methods from inner receiver class.

于 2013-06-09T16:50:58.367 回答
0

如果您想在 BroadcastReceiver 中处理某些内容,代码应如下所示

public class MainActivity extends Activity {

        public static class MicReceiver extends BroadcastReceiver {

    public MicReceiver() {
        // TODO Auto-generated constructor stub
        super();
    }
    @Override
    public void onReceive(Context context, Intent intent) {
        // TODO Auto-generated method stub

        String intentAction = intent.getAction();
        if (!Intent.ACTION_MEDIA_BUTTON.equals(intentAction)) {
            return;
        }
        KeyEvent event = (KeyEvent)intent.getParcelableExtra(Intent.EXTRA_KEY_EVENT);
        if (event == null) {
            return;
        }
        int action = event.getAction();
        if (action == KeyEvent.ACTION_DOWN) {

          Toast.makeText(context, "BUTTON PRESSED! ", Toast.LENGTH_SHORT).show(); 
        }
        abortBroadcast();
    }



        }
    }
于 2014-10-13T05:06:55.727 回答