如何通过主要活动了解会话中媒体播放器的状态

时间:2017-01-25 17:18:23

标签: android android-activity android-service android-mediaplayer

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

如何检查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);
            }
        });

1 个答案:

答案 0 :(得分:1)

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

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获得暂停状态,否则歌曲正在播放。如果服务未运行,则不播放任何歌曲。因此,您可以处理您的用户界面。