【问题标题】:Pass API object via Intent to Service?通过 Intent 将 API 对象传递给服务?
【发布时间】:2019-06-22 12:17:39
【问题描述】:

我正在尝试将从我的 MainActivity 类中的 Spotify API(SpotifyAppRemote 实例)创建的对象发送到 BackgroundService(实现为 IntentService)。 由于我无法使用 parcelable 发送我的对象,因为我无法控制 API,我试图使用 GSON 从我的意图通过 putExtra 方法发送它,如下所示:

intent.putExtra("spotifyRemote", gson.toJson(mSpotifyAppRemote, SpotifyAppRemote.class));

但是,在运行时我得到一个错误:

java.lang.UnsupportedOperationException: Attempted to serialize java.lang.Class: com.spotify.protocol.types.ImageUri. Forgot to register a type adapter?

还有其他方法可以将此对象发送到我的服务吗?查找此错误消息并没有真正帮助。

这是我的 MainActivity 类的代码:

@Override
public void onConnected(SpotifyAppRemote spotifyAppRemote) {
mSpotifyAppRemote = spotifyAppRemote;
getCurrentTrack();

// Now you can start interacting with App Remote
button.setOnClickListener(new View.OnClickListener() {

    @Override
    public void onClick(final View v) {
        infoText.setText("Successfully started!");
        counter = 1;
        numSongs = Integer.parseInt(mEdit.getText().toString());
        PlayerApi playerApi = mSpotifyAppRemote.getPlayerApi();
        playerApi.seekTo(0);
        playerApi.resume();
        Intent intent = new Intent(MainActivity.this, BackgroundService.class);
        intent.putExtra("counter", counter);
        intent.putExtra("numSongs", numSongs);
        intent.putExtra("firstTrack", gson.toJson(curTrack, Track.class));
        intent.putExtra("spotifyRemote", gson.toJson(mSpotifyAppRemote, SpotifyAppRemote.class));

        startService(intent);
    }
});

}

【问题讨论】:

    标签: android android-intent spotify intentservice


    【解决方案1】:

    我通过在我的服务中声明一个静态变量并在我的 MainActivity 中设置该变量来解决这个问题,如下所示:

    BackgroundService.mSpotifyAppRemote = mSpotifyAppRemote;
    

    在我的服务中声明:

    public static SpotifyAppRemote mSpotifyAppRemote = null;
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2018-02-09
      • 1970-01-01
      相关资源
      最近更新 更多