我开发了一款Android音乐播放器,但有一点我正在努力。我有带媒体按钮的耳机。在this和this等各种帖子的帮助下,我有一个RemoteControlReceiver,它可以成功响应使用Toast按下的按钮。我需要的是BroadcastReciever与我的Activity或更好的背景音乐服务(与活动绑定)进行通信。
项目的相关部分(如果有点困惑道歉 - 我一直在尝试这么多选项)是:
在我的清单中:
<!-- Broadcast Receivers -->
<receiver android:name=".RemoteControlReceiver">
<intent-filter android:priority="1000000000" >
<action android:name="android.intent.action.MEDIA_BUTTON" />
</intent-filter>
</receiver>
在RemoteControlReceiver.class中:
public class RemoteControlReceiver extends BroadcastReceiver {
// Constructor is mandatory
public RemoteControlReceiver ()
{
super ();
}
@Override
public void onReceive(Context context, Intent intent) {
if (Intent.ACTION_MEDIA_BUTTON.equals(intent.getAction())) {
KeyEvent event = intent.getParcelableExtra(Intent.EXTRA_KEY_EVENT);
if (event == null) {
return;
}
if (event.getAction() == KeyEvent.ACTION_DOWN) {
Toast.makeText(context, "ACTION_DOWN PRESSED!!!", Toast.LENGTH_SHORT).show();
}
}
}
}
在我的活动中:
private final RemoteControlReceiver myReceiver = new RemoteControlReceiver();
@Override
public void onResume() {
super.onResume();
// Media button on headphones
IntentFilter filter = new IntentFilter(Intent.ACTION_MEDIA_BUTTON);
registerReceiver(myReceiver, filter);
}
public void onPause()
{
super.onPause();
unregisterReceiver(myReceiver);
}
我已经尝试将其添加到RemoteControlReceiver.class:
Intent myIntent = new Intent(context, MainActivity.class);
myIntent.putExtra("action", "togglePlay");
myIntent.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
context.startActivity(myIntent);
然后在我的MainActivity / OnCreate中:
// Pick up extras passed by BroadcastReceiver
Bundle extras = getIntent().getExtras();
if (extras != null) {
String action = extras.getString("action","");
Toast.makeText(context, "Action="+action, Toast.LENGTH_SHORT).show();
clickAction(action);
}
Toast确认这是有效的,但是......这会启动一项新活动,而不是与现有活动进行通信。我也试过这个:
Intent myIntent = new Intent(context, MainActivity.class);
myIntent.putExtra("action", "togglePlay");
myIntent.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK | Intent.FLAG_ACTIVITY_SINGLE_TOP);
context.startActivity(myIntent);
但没有显示Toast(我假设因为FLAG_ACTIVITY_SINGLE_TOP表示OnCreate未通过?)。
我的问题不在于“我做错了什么”(我确信答案是“我们从哪里开始?”)但是真的“这是让我的服务回应的正确方法是什么按下媒体按钮“?