如何接收外部应用程序的广播元数据?

How do I receive an external app's broadcast metadata?

我正在尝试向我的应用程序添加一项功能,该功能接收来自 Spotify 的广播 data/intent-actions 并使用该数据执行某些操作。但是,我不确定如何进行。在前面的问题的帮助下,我已经能够拼凑出以下代码,但是这些问题没有详细说明 如何实际启动数据接收。我有一个广播接收器:

<receiver
    android:name=".Receiver"
    android:enabled="true"
    android:exported="true">

    <intent-filter>
        <action android:name="com.spotify.music.playbackstatechanged"/>
        <action android:name="com.spotify.music.metadatachanged"/>
        <action android:name="com.spotify.music.queuechanged"/>
    </intent-filter>

</receiver>

我有一个广播接收器class(全部设置):

public class Receiver extends BroadcastReceiver {

    static final class BroadcastTypes {
        static final String SPOTIFY_PACKAGE = "com.spotify.music";
        static final String PLAYBACK_STATE_CHANGED = SPOTIFY_PACKAGE + ".playbackstatechanged";
        static final String METADATA_CHANGED = SPOTIFY_PACKAGE + ".metadatachanged";
    }

    @Override
    public void onReceive(Context context, Intent intent) {

        long timeSentInMs = intent.getLongExtra("timeSent", 0L);
        String action = intent.getAction();

        if (action.equals(BroadcastTypes.METADATA_CHANGED)) {

            String trackId = intent.getStringExtra("id");
            String artistName = intent.getStringExtra("artist");
            String albumName = intent.getStringExtra("album");
            String trackName = intent.getStringExtra("track");
            int trackLengthInSec = intent.getIntExtra("length", 0);

            //send data to main class?

        } else if (action.equals(BroadcastTypes.PLAYBACK_STATE_CHANGED)) {

           boolean playing = intent.getBooleanExtra("playing", false);
            int positionInMs = intent.getIntExtra("playbackPosition", 0);

            //send data to main class?
        }
    }
}

我的main中还有以下方法activity:

public void mute(AudioManager audioManager){

    audioManager.setStreamMute(am.STREAM_SYSTEM, true);

}

public void unMute(AudioManager audioManager){

    audioManager.setStreamMute(am.STREAM_SYSTEM,false);

}

我想在接收和分析来自我的接收器 class 的广播数据后调用它。

总结:

So now I am not sure how I can actually start the acquisition of data from Spotify in my main activity (whether I have to manually "call" my receiver, or whether it will automatically listen for Broadcasts in the background while my main Activity is running).

如能详细说明,将不胜感激。

只需通过清单静态注册接收器class。该应用程序将自动侦听接收器意图过滤器中定义的意图操作,例如

在接收到指定操作之一时,应用程序将自动启动后台线程以 运行 onReceive 方法。

据我所知,您已经为静态接收器注册设置了所有必需的部分。

但请注意从 Android 3.1 开始,如果用户从未启动相应的应用程序,或者如果用户通过Android 菜单

还要确保 Spotify 已启用媒体通知:https://developer.spotify.com/technologies/spotify-android-sdk/android-media-notifications/#enabling-media-notifications