MediaPlayer服务Android

Zan*_*hna 13 android android-service android-mediaplayer

我是Android新手.我正在为Media Player创建服务,以便即使我关闭应用程序也可以继续播放歌曲.我已经为Media Player创建了活动,它具有播放,暂停,下一个,上一个,搜索栏等所有功能,还包括oncompletionlistener.一切都很棒.但现在我希望所有都应该由服务管理.

我创建了MyService类:

public class MyService extends Service {

    public static MediaPlayer mp;

    @Override
    public IBinder onBind(Intent intent) {
        // TODO Auto-generated method stub
        return null;
    }

    @Override
    public void onCreate() {
        mp = new MediaPlayer();     
    }

    @Override
    public int onStartCommand(Intent intent, int flags, int startId) {  
        return START_STICKY;
    }
Run Code Online (Sandbox Code Playgroud)

但是在我的播放器活动中,我为Songlist创建了ArrayList,我正在使用currentsongIndex并通过它我保持所有功能,如next,previous和all ..现在我在服务中如何获得歌曲列表,这也是我的活动所需要的? ?我应该在哪里创建MediaPlayer对象意味着在服务或活动?

对于MediaPlayer我已经参考了http://www.androidhive.info/2012/03/android-building-audio-player-tutorial/.对于我的媒体播放器代码,您可以参考此网站.谢谢.让我感到疑惑.我感到很困惑.很快回复我..

Mik*_*wig 7

你走在正确的轨道上.我改编自SDK Samples; 这就是我如何做到这一点并且效果很好.从您的ArrayList(在您的活动中而不是从服务)调用

onListItemClick
Run Code Online (Sandbox Code Playgroud)

并启动一个启动音乐服务的意图:

startService(new Intent(MusicService.ACTION_PLAY));
Run Code Online (Sandbox Code Playgroud)

在您的清单中,您需要添加:

 <intent-filter>
            <action android:name="com.blah.blah.action.PLAY" />
           <xxx xxx> 
 </intent-filter>
Run Code Online (Sandbox Code Playgroud)

当然,在您的音乐服务中,您需要接收意图:

public int onStartCommand(Intent intent, int flags, int startId) {
    String action = intent.getAction();
    if (action.equals(ACTION_PLAY))
        processPlayRequest();
  }
Run Code Online (Sandbox Code Playgroud)

一定要添加Intents for skip,rewind,stop等.如果有帮助请告诉我.