我正在尝试在我的应用程序中处理媒体按钮按下,但我尝试的任何东西似乎都工作。这是我的广播接收器:
private final BroadcastReceiver receiver = new BroadcastReceiver() {
@Override
public void onReceive(Context context, Intent intent) {
if (intent.getAction().equalsIgnoreCase("android.intent.action.MEDIA_BUTTON")) {
Log.d("EVENT", "Media button pressed");
startStop();
}
}
};
我在onCreate方法中注册了它:
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
Toolbar toolbar = (Toolbar) findViewById(R.id.toolbar);
setSupportActionBar(toolbar);
am = (AudioManager)getSystemService(Context.AUDIO_SERVICE);
am.registerMediaButtonEventReceiver(new ComponentName(getPackageName(), RemoteControlReceiver.class.getName()));
}
我还尝试过其他方法,比如创建一个单独的BroadcastReceiver类并通过AndroidManifest注册它......
编辑:我回到了“单独接收班级”这样做的方式,现在这该死的东西效果很好......让我解释一下;这是我全新的BroadcastReceiver类:public class RemoteControlReceiver extends BroadcastReceiver {
@Override
public void onReceive(Context context, Intent intent) {
if (Intent.ACTION_MEDIA_BUTTON.equals(intent.getAction())) {
KeyEvent event = (KeyEvent) intent.getParcelableExtra(Intent.EXTRA_KEY_EVENT);
Log.d("EVENT", "Key code: "+event.getKeyCode());
if ((KeyEvent.KEYCODE_HEADSETHOOK == event.getKeyCode()) && (event.getAction() == KeyEvent.ACTION_DOWN)) {
Log.d("EVENT", "Received media button press");
if (MainActivity.timer.getStarted())
MainActivity.timer.stopTimer();
else
MainActivity.timer.startTimer();
}
}
}
}
在清单中注册它:
<receiver android:name=".RemoteControlReceiver">
<intent-filter>
<action android:name="android.intent.action.MEDIA_BUTTON" />
</intent-filter>
</receiver>
这就出现在日志中:
11-23 01:47:02.848 16956-16956/com.example.andrej.ssvcounter D/EVENT: Key code: 79
11-23 01:47:02.848 16956-16956/com.example.andrej.ssvcounter D/EVENT: Received media button press
11-23 01:47:02.873 16956-16956/com.example.andrej.ssvcounter D/EVENT: Key code: 79
11-23 01:47:04.931 16956-16956/com.example.andrej.ssvcounter D/AndroidRuntime: Shutting down VM
然后整个事情崩溃了。由于某种原因,两个意图被发送,我试图用ACTION_DOWN条件过滤掉一个,但它没有帮助......