我用以下代码制作了广播接收器。
public class MediaButtonsIntentReceiver extends BroadcastReceiver {
public MediaButtonsIntentReceiver() {
super();
}
@Override
public void onReceive(Context context, Intent intent) {
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){
int keycode = event.getKeyCode();
if(keycode==KeyEvent.KEYCODE_VOLUME_UP){
Toast.makeText(context, "hiii bro", Toast.LENGTH_SHORT).show();
}
else if(keycode==KeyEvent.KEYCODE_VOLUME_DOWN){
Toast.makeText(context, "hiii bro", Toast.LENGTH_SHORT).show();
}
else if(keycode==KeyEvent.KEYCODE_MEDIA_NEXT){
Toast.makeText(context, "hiii bro", Toast.LENGTH_SHORT).show();
}
else if(keycode==KeyEvent.KEYCODE_MEDIA_PREVIOUS){
Toast.makeText(context, "hiii bro", Toast.LENGTH_SHORT).show();
}
}
abortBroadcast();
}
}
在我的主要活动中,我已经注册了10000优先级的广播接收器。
public class MainActivity extends AppCompatActivity {
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
IntentFilter filter = new IntentFilter(Intent.ACTION_MEDIA_BUTTON);
MediaButtonsIntentReceiver r = new MediaButtonsIntentReceiver();
filter.setPriority(10000);
registerReceiver(r, filter);
}
}
在清单
中 <receiver
android:name=".MediaButtonsIntentReceiver">
<intent-filter><action android:name="android.intent.action.MEDIA_BUTTON">
</action> </intent-filter>
</receiver>
<uses-permission android:name="android.permission.BLUETOOTH"/>
我不知道为什么它不起作用。我想让它在我的手机屏幕被锁定时运行。