如何检查我的服务是否在Android中在后台播放音频?

时间:2014-11-28 08:41:10

标签: android audio service

我有一项服务,通过startForeground()和持续通知在后台播放远程音频流。我有一个问题,让我的活动知道音频当前是否正在运行,所以我可以显示播放或停止按钮。这是启动音频的onStartCommand调用:

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

    if (intent.getAction().equals(ACTION_PLAY)) {

        if(mMediaPlayer != null && mMediaPlayer.isPlaying())
            return START_STICKY;

        String url = intent.getStringExtra("live_url");
        mMediaPlayer = new MediaPlayer();
        mMediaPlayer.setAudioStreamType(AudioManager.STREAM_MUSIC);

        try {
            mMediaPlayer.setDataSource(url);
        } catch (IOException e) {
            e.printStackTrace();
            return START_STICKY;
        }

        mMediaPlayer.setWakeMode(getApplicationContext(), PowerManager.PARTIAL_WAKE_LOCK);
        mMediaPlayer.setOnPreparedListener(this);
        mMediaPlayer.setOnErrorListener(this);
        mMediaPlayer.prepareAsync(); // prepare async to not block main thread

        wifiLock = ((WifiManager) getSystemService(Context.WIFI_SERVICE))
                .createWifiLock(WifiManager.WIFI_MODE_FULL, "mylock");

        wifiLock.acquire();
    }
    else if (intent.getAction().equals(ACTION_STOP)) {
        doRelease();
    }
    return START_STICKY;
}

和onPrepared():

public void onPrepared(MediaPlayer player) {

    player.setOnCompletionListener(new MediaPlayer.OnCompletionListener() {
        @Override
        public void onCompletion(MediaPlayer mediaPlayer) {
            doRelease();
        }
    });

    player.start();

    PendingIntent pi = PendingIntent.getActivity(getApplicationContext(), REQUEST_CODE,
            new Intent(getApplicationContext(), ActivityMain.class),
            PendingIntent.FLAG_UPDATE_CURRENT);

    NotificationCompat.Builder mBuilder =
        new NotificationCompat.Builder(getApplicationContext())
            .setSmallIcon(R.drawable.ic_launcher)
            .setContentTitle(getString(R.string.app_name))
            .setContentText(getString(R.string.playing_live))
            .setTicker("test")
            .setOngoing(true)
            .setContentIntent(pi);

    startForeground(NOTIFICATION_ID, mBuilder.build());
}

2 个答案:

答案 0 :(得分:0)

考虑使用Bound Service。这样您的活动就可以调用您服务的方法,例如您创建的方法,它会返回mMediaPlayer.isPlaying()的值。

从您的活动的onStart()方法调用绑定服务的方法,以适当地更新您的用户界面。

答案 1 :(得分:0)

如果您查看Bound Service文档中的示例代码,您会看到一个getRandomNumber()方法,用于使用该服务的客户端。

这应该会让您知道您可以在服务类中定义自己的方法,通常在您的情况下使用包装方法来解决您的问题

public class MediaPlayerService extends Service{
  private MediaPlayer mediaPlayer;
  ..
  public boolean isPlaying() {
    return mediaPlayer.isPlaying();
  }
}

希望有所帮助。干杯!