gpt4 book ai didi

android - 如何通过主 Activity 了解 session 中媒体播放器的状态

转载 作者:行者123 更新时间:2023-11-30 00:45:28 24 4
gpt4 key购买 nike

我如何知道我的媒体播放器是否通过服务运行或停止运行。目前我正在使用操作调用该服务。

如何在我的 MainActivity 中检查媒体播放器状态?这样我就可以对 UI 进行适当的更改!

下面是我实现媒体播放器的服务代码。

    public class MyService extends Service implements MediaPlayer.OnPreparedListener {

private static final String ACTION_PLAY = "com.demo.tron.mediaplayerasaservice.PLAY";
private static final String ACTION_STOP = "com.demo.tron.mediaplayerasaservice.STOP";

public MediaPlayer mMediaPlayer = null;

public int onStartCommand(Intent intent, int flags, int startId) {

if (intent.getAction().equals(ACTION_PLAY)) {
mMediaPlayer = new MediaPlayer(); // initialize it here
mMediaPlayer.setOnPreparedListener(this);
try{
mMediaPlayer.setDataSource("http://mp3channels.webradio.antenne.de:80/antenne");
}
catch (IOException e)
{
Toast.makeText(this, e.getMessage(), Toast.LENGTH_SHORT).show();
}
mMediaPlayer.prepareAsync(); // prepare async to not block main thread
}
else if (intent.getAction().equals(ACTION_STOP)){
if (mMediaPlayer.isPlaying())
{
mMediaPlayer.stop();
mMediaPlayer.reset();
}
}

return START_STICKY;
}

@Nullable
@Override
public IBinder onBind(Intent intent) {
return null;
}

/** Called when MediaPlayer is ready */
@Override
public void onPrepared(MediaPlayer player) {
mMediaPlayer.start();
}
}

这是通过 MAIN ACTIVITY 调用媒体播放器服务的代码:

button.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
Intent intent=new Intent(MainActivity.this,MyService.class);
intent.setAction("com.demo.tron.mediaplayerasaservice.PLAY");
startService(intent);
}
});

最佳答案

您需要检查服务是否已经在运行,然后采取适当的措施:

private boolean isServiceRunning(Class<?> serviceClass) {
ActivityManager manager = (ActivityManager) getSystemService(Context.ACTIVITY_SERVICE);
for (ActivityManager.RunningServiceInfo service : manager.getRunningServices(Integer.MAX_VALUE)) {
if (serviceClass.getName().equals(service.service.getClassName())) {
return true;
}
}
return false;
}

然后像这样在任何地方调用 isServiceRunning 方法:

isServiceRunning(YourServiceClass.class)

定义一个 PlayerConstants 类来跟踪玩家状态。它将包含所有静态变量:

public class PlayerConstants {
//List of Songs
public static ArrayList<MediaItem> SONGS_LIST = new ArrayList<MediaItem>();
//song number which is playing right now from SONGS_LIST
public static int SONG_NUMBER = 0;
//song is playing or paused
public static boolean SONG_PAUSED = true;
}

现在您需要检查服务是否正在运行,如果正在运行,歌曲可以暂停或已经播放,您可以从 PlayerConstants 获取暂停状态,否则歌曲正在播放。如果服务未运行,则不会播放任何歌曲。因此,您可以处理您的 UI。

关于android - 如何通过主 Activity 了解 session 中媒体播放器的状态,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/41857710/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com