我希望在应用程序处于后台时收到音乐播放器的广播。
我找到了以下代码here:
@Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.main);
IntentFilter iF = new IntentFilter();
iF.addAction("com.android.music.metachanged");
iF.addAction("com.android.music.playstatechanged");
iF.addAction("com.android.music.playbackcomplete");
iF.addAction("com.android.music.queuechanged");
registerReceiver(mReceiver, iF);
}
private BroadcastReceiver mReceiver = new BroadcastReceiver() {
@Override
public void onReceive(Context context, Intent intent) {
String action = intent.getAction();
String cmd = intent.getStringExtra("command");
Log.v("tag ", action + " / " + cmd);
String artist = intent.getStringExtra("artist");
String album = intent.getStringExtra("album");
String track = intent.getStringExtra("track");
Log.v("tag", artist + ":" + album + ":" + track);
Toast.makeText(CurrentMusicTrackInfoActivity.this, track, Toast.LENGTH_SHORT).show();
}
};
它可以工作,但只有在活动运行时才有效。所以我试着制作一个静态广播接收器:
<receiver
android:name=".receiver.MusicBroadcastReceiver"
android:exported="false">
<intent-filter>
<action android:name="com.android.music.metachanged" />
<action android:name="com.android.music.playstatechanged" />
<action android:name="com.android.music.playbackcomplete" />
<action android:name="com.android.music.queuechanged" />
</intent-filter>
</receiver>
班级:
public class MusicBroadcastReceiver extends BroadcastReceiver {
public MusicBroadcastReceiver() {
}
@Override
public void onReceive(Context context, Intent intent) {
String action = intent.getAction();
String cmd = intent.getStringExtra("command");
Log.v("tag ", action + " / " + cmd);
String artist = intent.getStringExtra("artist");
String album = intent.getStringExtra("album");
String track = intent.getStringExtra("track");
Log.v("tag", artist + ":" + album + ":" + track);
Toast.makeText(context, track, Toast.LENGTH_SHORT).show();
}
}
它不起作用。 我开始搜索,然后发现this question,声称上面的代码应该有用。但事实并非如此,当我开始播放音乐或跳过曲目时,不会调用onReceive。 Imust会做一些非常错误的事,但我无法弄清楚是什么。
任何帮助将不胜感激。感谢。
答案 0 :(得分:1)
尝试设置android:exported="true"
http://developer.android.com/guide/topics/manifest/receiver-element.html
android:exports
广播接收机是否可以从其应用之外的来源接收消息 - &#34; true&#34;如果它可以,&#34;假&#34;如果不。如果&#34; false&#34;,广播接收者可以接收的唯一消息是由具有相同用户ID的相同应用程序的组件发送的消息。