Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
282 views
in Technique[技术] by (71.8m points)

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

I managed to get my headset buttons get recognized by my app when pressed, but one of the buttons needs to call a method that's in MyCustomActivity. The problem is onReceive's 1st parameter is a Context that cannot be cast to Activity and so I am forced to implement my BroadcastReceiver as an inner class inside MyCustomActivity.

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

For the independent class, this was simple:

<receiver android:name=".RemoteControlReceiver">
    <intent-filter>
        <action android:name="android.intent.action.MEDIA_BUTTON" />
    </intent-filter>
</receiver>

What is the trick/syntax to do the same for MyCustomActivity's mReceiver?

  private BroadcastReceiver mReceiver = new BroadcastReceiver() {
    @Override
    public void onReceive(Context ctx, Intent intent) {
         // ...
        }
  }
See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Answer

0 votes
by (71.8m points)

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.


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...