How do I register in manifest an *inner* MEDIA_BUTTON BroadcastReceiver?

ε祈祈猫儿з 提交于 2019-11-28 14:04:20

You don't, if it's meant to be part of the Activity, you register it dynamically:

BroadcastReceiver receiver;

@Override
protected void onCreate (Bundle b)
{
  super.onCreate (b);
  IntentFilter filter = new IntentFilter(Intent.ACTION_MEDIA_BUTTON);    
  filter.setPriority(10000);  
  receiver = new BroadcastReceiver() {
    @Override
    public void onReceive(Context ctx, Intent intent) {
      // ...
    }
  };
  registerReceiver (receiver, filter);
}

Then don't forget to unregister in onPause() (to avoid leaking).

@Override
protected void onPause()
{ 
  try{
    unregisterReceiver (receiver);
  }
  catch (IllegalStateException e)
  {
    e.printStackTrace();
  }
  super.onPause();
}

This dynamic registration does mean however, that if your Activity isn't in the foreground, the button won't work. You can try unregistering in onDestroy() instead, but the surest way to avoid leaking is onPause().

Alternatively, to make the button respond no matter what, consider making a Service, and having that register your receiver.

So far so good but how do I register this inner MediaButtonEventReceiver in the manifest?

You can't. You can register it dynamically by calling registerReceiver() on the activity, though.

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!