如何检查音乐是否从哪个音乐应用播放?

时间:2015-04-22 10:09:07

标签: android android-intent android-activity android-music-player

如何检查音乐在Android设备中播放的音乐应用程序?

使用AudioManager,我们可以检查音乐是否正在播放。但它没有提供正在播放的音乐应用程序的详细信息。

  

AudioManager am =   (AudioManager)this.getSystemService(Context.AUDIO_SERVICE);

如果在设备中播放音乐,则

am.isMusicActive()会返回 true 。但我想要播放它的音乐应用名称。

参考文献:

  

How do you check if music is playing by using a broadcast receiver?

     

Android development : To find out which app is playing music currently

例如,如果我从Google音乐播放器播放音乐。然后我必须能够将音乐应用程序名称设为“Google音乐播放器”。

任何对此的回复都将不胜感激。谢谢!

1 个答案:

答案 0 :(得分:0)

尝试此操作以获取当前播放曲目的文件路径:

public Cursor query(Context context, Uri uri, String[] projection, String selection, String[] selectionArgs, String sortOrder, int limit) {
    try {
        ContentResolver resolver = context.getContentResolver();
        if (resolver == null) return null;
        if (limit > 0) uri = uri.buildUpon().appendQueryParameter("limit", "" + limit).build();
        return resolver.query(uri, projection, selection, selectionArgs, sortOrder);
    } catch (UnsupportedOperationException ex) { return null; }
}
private BroadcastReceiver mReceiver = new BroadcastReceiver() {
    @Override
    public void onReceive(Context context, Intent intent) {
        String path = intent.getStringExtra("track").replaceAll("'","''");
        Cursor c = query(context, MediaStore.Audio.Media.EXTERNAL_CONTENT_URI,
                new String[] { MediaStore.Audio.Media.DATA }, MediaStore.Audio.Media.TITLE + "='" + path + "'",
                null, null, 0);
        try {
            if (c == null || c.getCount() == 0) return;
            int size = c.getCount();
            if (size != 1) return;
            c.moveToNext();

            // Here's the song path
            String songPath = c.getString(0);
            Log.d("ROAST_APP", "" + songPath);
        } finally {
            if (c != null) c.close();
        }
    }
};

@Override
protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.activity_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);
}

来源:
Track info of currently playing music
Needletagger