是否可以在其他Android应用中控制Spotify应用的播放?我只是在寻找跳轨功能(向前和向后)。
我了解Spotify Android SDK,但它似乎只允许跳过SDK播放的曲目:
com.spotify.sdk.android.playback.NativeSpotifyException: Failed SpPlaybackSkipToPrev with error code 14 (The operation is not supported if the device is not the active playback device)
为了澄清,实际的Spotify应用程序和我自己的应用程序都在同一台设备上运行
答案 0 :(得分:4)
以下是如何操作:
这将尝试播放/暂停Spotify。如果它没有运行,它将启动它并开始播放。
public void nextSong() {
int keyCode = KeyEvent.KEYCODE_MEDIA_NEXT;
if (!isSpotifyRunning()) {
startMusicPlayer();
}
Intent intent = new Intent(Intent.ACTION_MEDIA_BUTTON);
intent.setPackage("com.spotify.music");
synchronized (this) {
intent.putExtra(Intent.EXTRA_KEY_EVENT, new KeyEvent(KeyEvent.ACTION_DOWN, keyCode));
getContext().sendOrderedBroadcast(intent, null);
intent.putExtra(Intent.EXTRA_KEY_EVENT, new KeyEvent(KeyEvent.ACTION_UP, keyCode));
getContext().sendOrderedBroadcast(intent, null);
}
}
public void playPauseMusic() {
int keyCode = KeyEvent.KEYCODE_MEDIA_PLAY_PAUSE;
if (!mAudioManager.isMusicActive() && !isSpotifyRunning()) {
startMusicPlayer();
}
Intent i = new Intent(Intent.ACTION_MEDIA_BUTTON);
i.setPackage("com.spotify.music");
synchronized (this) {
i.putExtra(Intent.EXTRA_KEY_EVENT, new KeyEvent(KeyEvent.ACTION_DOWN, keyCode));
getContext().sendOrderedBroadcast(i, null);
i.putExtra(Intent.EXTRA_KEY_EVENT, new KeyEvent(KeyEvent.ACTION_UP, keyCode));
getContext().sendOrderedBroadcast(i, null);
}
}
private void startMusicPlayer() {
Intent startPlayer = new Intent(Intent.ACTION_MAIN);
startPlayer.setPackage("com.spotify.music");
startPlayer.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
getContext().startActivity(startPlayer);
if (mMusicPlayerStartTimer != null) {
mMusicPlayerStartTimer.cancel();
}
mMusicPlayerStartTimer = new Timer("MusicPlayerStartTimer", true);
mMusicPlayerStartTimer.schedule(new MusicPlayerStartTimerTask(), DateUtils.SECOND_IN_MILLIS, DateUtils.SECOND_IN_MILLIS);
}
private boolean isSpotifyRunning() {
Process ps = null;
try {
String[] cmd = {
"sh",
"-c",
"ps | grep com.spotify.music"
};
ps = Runtime.getRuntime().exec(cmd);
ps.waitFor();
return ps.exitValue() == 0;
} catch (IOException e) {
Log.e(DEBUG_TAG, "Could not execute ps", e);
} catch (InterruptedException e) {
Log.e(DEBUG_TAG, "Could not execute ps", e);
} finally {
if (ps != null) {
ps.destroy();
}
}
return false;
}
private class MusicPlayerStartTimerTask extends TimerTask {
@Override
public void run() {
if (isSpotifyRunning()) {
playPauseMusic(null);
cancel();
}
}
}
编辑:添加了完整的示例代码
答案 1 :(得分:1)
是的,您可以使用RemoteController类控制播放,或者使用Lollipop,MediaController类,或者如果支持L及更早版本,则使用MediaControllerCompat类。
然后使用KEYCODE_MEDIA_NEXT执行dispatchMediaButtonEvent()。
答案 2 :(得分:-2)
快速回答 - 不,这是不可能的。