サービスを介してメディアプレーヤーが動作しているかどうかを確認するにはどうすればよいですか?私は現在、アクションを使用してサービスを呼び出しています。メインアクティビティを介してセッション中のメディアプレーヤーのステータスを確認する方法
MainActivityでメディアプレーヤーのステータスを確認するにはどうすればよいですか?私はUIに適切な変更を加えることができます!
以下は、mediaplayerを実装した私のサービスコードです。
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();
}
}
これは、主な活動を通じて、メディア・プレーヤ・サービスを呼び出すコードです:あなたはサービスがすでに実行されているかどうかをチェックし、適切な行動を取る必要があり
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);
}
});
サービスがアクティブかどうかを調べる方法はあまり良くありません。また、定数を設定した後、MainActivityにプレーヤーの実行状況を知らせるにはどうすればよいですか? 1秒ごとに更新するハンドラを用意する必要がありますか? – IteratioN7T
プレーヤーの状態の変化、つまり次回/前回の曲、再生/一時停止の曲、投稿するハンドラのメッセージを投稿するには、ハンドラが必要です歌の進行状況の更新について毎秒活動へのメッセージ。アクティビティが作成されると、サービスが実行されているかどうか、実行されていない場合、ソングが再生されていない場合、サービスが実行中の場合、曲がポーズ状態にあるかプレーヤー定数からチェックされていないかを確認します。 –
はい、またアンサーを更新しました – IteratioN7T