Android : How to get info of currently playing music using broadcastreceiver while the app isn't running?

on Tuesday, April 14, 2015


I would like to receive broadcasts from music players while the app is in the background.


I found the following code 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();
}
};


And it works, but only while the activity is running. So I tried to make a static broadcastreceiver:



<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>


The class:



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();
}
}


And it doesn't work. I started searching and I found this question, which claims that the code above should work. But it doesn't, onReceive is not called when I start playing music or skip a track. Imust be doing something very wrong, but I can't figure out what.


Any help would be appreciated. Thanks.


0 comments:

Post a Comment