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.
与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…