2011-08-29 59 views
2

我创建一个媒体播放器服务,从互联网上播放媒体文件,如:如何从mediaplayer服务中获取seekbar的活动?

public class MyService extends Service{ 
private static final String TAG = "MyService"; 
MediaPlayer mediaPlayer;  
@Override 
public IBinder onBind(Intent intent) { 
    return null; 
} 

@Override 
public void onCreate() { 
    Toast.makeText(this, "My Service Created", Toast.LENGTH_LONG).show(); 
    Log.d(TAG, "onCreate"); 

    mediaPlayer = new MediaPlayer(); 
    mediaPlayer.setAudioStreamType(AudioManager.STREAM_MUSIC); 
} 

@Override 
public void onDestroy() { 
    Toast.makeText(this, "My Service Stopped", Toast.LENGTH_LONG).show(); 
    Log.d(TAG, "onDestroy"); 
    mediaPlayer.stop(); 
} 

@Override 
public void onStart(Intent intent, int startid) { 
    Toast.makeText(this, "My Service Started", Toast.LENGTH_LONG).show(); 
    Log.d(TAG, "onStart"); 
    String rtsp; 
    Bundle re= intent.getExtras(); 
    rtsp=re.getString("rtsp"); 
    try { 
     mediaPlayer.setDataSource(rtsp); 
     mediaPlayer.prepare(); 
    } catch (IllegalArgumentException e) { 
     // TODO Auto-generated catch block 
     e.printStackTrace(); 
    } catch (IllegalStateException e) { 
     // TODO Auto-generated catch block 
     e.printStackTrace(); 
    } catch (IOException e) { 
     // TODO Auto-generated catch block 
     e.printStackTrace(); 
    }  
    mediaPlayer.start(); 

} 
} 

现在我想从活动这样的搜索条:

SeekBar seekbar= (SeekBar)findviewbyid(R.id.seekbar); 

但我做不到“T :(请帮我该怎么做!

编辑

我发现了另一个的方式来解决我的问题,而无需使用绑定服务:) 这就是:

在服务类中,创建这样一个静态方法:

public static void setMainActivity(Player_Activity mainActivity) 
{ 
    MAIN_ACTIVITY=mainActivity; 
} 

Ofcourse,您必须声明静态varible:

private static Player_Activity MAIN_ACTIVITY; 

接下来,在您的活动,您可以调用startService()之前,必须调用此方法的主要活动设置为您服务是这样的:

MyService.setMainActivity(Player_Activity.this); 
Intent myservice= new Intent(this,MyService.class); 
startService(myservice); 

终于可以与您的活动做任何事情在你的服务是这样的:

final TextView tv_test=(TextView)MAIN_ACTIVITY.findViewById(R.id.textview); 

这一切!希望这有助于:)

原谅我,如果我得到一些英文错误),我的英语水平不是很好:)

+0

你需要** **绑定的服务活动 – Samuel

+0

感谢,但我不知道怎么来的,我是一个新手:) –

回答

1

您正在播放媒体服务,以便与服务进行通信,你必须与bind活动服务。

更多有关Bind参见下面的文档

Click here

编辑

参看下面的教程

Click Here

+0

谢谢@Dharmendra我会试试:) –

+1

@ Han Tran:我想你需要知道如何处理这个回应。 [**链接**](http://meta.stackexchange.com/questions/5234/how-does-accepting-an-answer-work) – Samuel

+0

@Dharmendra我读了你的链接,但我不明白如何解决我的问题,有没有关于我的问题的任何TUT或文章? –

0

我知道它已经被回答。但我尝试了下面的代码,这对我有用。可能对某人有用。

public class MediaPlayerService extends Service implements MediaPlayer.OnPreparedListener,MediaPlayer.OnCompletionListener{ 
String ExactPath; 
int total,CurrentPosition; 
MediaPlayer mp; 
private final IBinder mBinder=new LocalBinder(); 
public class LocalBinder extends Binder { 
    MediaPlayerService getService(){ 
     return MediaPlayerService.this; 
    } 
} 

@Override 
public IBinder onBind(Intent intent) { 

    return mBinder; 
} 



@Override 
public void onCreate() { 
    mp=new MediaPlayer(); 
    mp.setAudioStreamType(AudioManager.STREAM_MUSIC); 
    mp.setOnPreparedListener(this); 

} 

@Override 
public int onStartCommand(Intent intent, int flags, int startId) { 
    ExactPath=intent.getStringExtra("pos"); 
    PrepareMediaPlayer(); 
    if(!mp.isPlaying()){ 
     mp.start(); 
    }else{ 
     mp.pause(); 
    } 
    return START_STICKY; 
} 
public void PrepareMediaPlayer(){ 

    try { 
     mp.setDataSource(ExactPath); 
     mp.prepareAsync(); 

    } catch (IOException e) { 
     e.printStackTrace(); 
    }catch (IllegalStateException e){ } 
    catch(IllegalFormatException e){ } 

} 

@Override 
public void onPrepared(MediaPlayer mediaPlayer) { 
    mp.start(); 


} 

@Override 
public void onCompletion(MediaPlayer mediaPlayer) { 
    stopSelf(); 
} 



public int seekBarGetCurrentPosition(){ //This method is created to get SongCurrentPosition from mediaplayer for seekbar 
    if(mp!=null&&mp.isPlaying()){ 
     CurrentPosition=mp.getCurrentPosition(); 
    } 
    return CurrentPosition; 
} 


@Override 
public void onDestroy() { 
    if(mp.isPlaying()){ 
     mp.stop(); 
    } 
    mp.release(); 
} 

}

注:在服务类我越来越MediaPlayer的持续时间有问题。当我的活动请求服务期限时,我的结果不正确。所以我已经实现了一个从活动中获得持续时间的方法。希望你可以修复服务本身的持续时间。但是这个代码为我工作。

然后在你的Activity中,在onCreate()方法之后。

/**The below method songDuration() is created as substitution for getMediaPlayerDuration() method 
* if getMediaPlayerDuration() failed to get the duration from mediaPlayer via service this method 
* helps to avoid returning zero or null value . Because it has been observed that service takes 
* quite a long time to return a value, if it is called frequently with in a span of seconds say, pressing 
* Next button continuously. 
*/ 
public int songDuration(){ 
    MediaMetadataRetriever mmr=new MediaMetadataRetriever(); 
    mmr.setDataSource(path); 
    String Dur=mmr.extractMetadata(MediaMetadataRetriever.METADATA_KEY_DURATION); 
    Integer Duration=Integer.parseInt(Dur); 
    return Duration; 


} 




@Override 
protected void onStart() { 
    super.onStart(); 
    Intent intent=new Intent(Player.this,MediaPlayerService.class); 
    bindService(intent,mServiceConnection, Context.BIND_AUTO_CREATE); 
    getSeekBarStatus();//This method is called onBinding process so that it gets updated with player. 

} 

@Override 
protected void onStop() { 
    super.onStop(); 
    if(ServiceBinding){ 
     unbindService(mServiceConnection); 
     ServiceBinding=false; 
    } 
} 

//This method gets the MediaPlayer Duration from service. 
public int getMediaPlayerDuration(){ 
    if(ServiceBinding){ 
     if(mediaPlayerServiceObject.mp!=null){ 
      Duration=mediaPlayerServiceObject.seekBarDuration(); 
     } 
    } 
    return Duration; 
} 
    //This method get MediaPlayerCurrent Position from service 
public int getMediaPlayerCurrentPosition(){ 
    if(ServiceBinding){ 
     if(mediaPlayerServiceObject.mp!=null){ 
      currentPosition=mediaPlayerServiceObject.seekBarGetCurrentPosition(); 
     } 
    } 
    return currentPosition; 
} 
    //This method is used to update seekBar status by getting Player Current Position from service. 
public void getSeekBarStatus(){ 
    new Thread(new Runnable() { 
     @Override 
     public void run() { 

      int total=songDuration(); 
      int CurrentPosition=0; 
      seekBar.setMax(total); 

      while(CurrentPosition<total){ 
       try { 
        Thread.sleep(1000); 
        CurrentPosition=getMediaPlayerCurrentPosition(); 
        Log.d(TAG,String.valueOf(CurrentPosition)); 
       } catch (InterruptedException e) { 
        return; 
       }seekBar.setProgress(CurrentPosition); 
      } 
     } 
    }).start(); 

    seekBar.setOnSeekBarChangeListener(new SeekBar.OnSeekBarChangeListener() { 
     @Override 
     public void onProgressChanged(final SeekBar seekBar, int ProgressValue, boolean fromUser) { 
      // if(fromUser){ 
      // mp.seekTo(ProgressValue); 
      //} 
      final long Minutes=((ProgressValue/1000)/60); 
      final int Seconds=((ProgressValue/1000)%60); 
      SongProgress.setText(Minutes+":"+Seconds); 


     } 

     @Override 
     public void onStartTrackingTouch(SeekBar seekBar) { 

     } 

     @Override 
     public void onStopTrackingTouch(SeekBar seekBar) { 

     } 
    }); 

} 


private ServiceConnection mServiceConnection=new ServiceConnection() { 
    @Override 
    public void onServiceConnected(ComponentName componentName, IBinder iBinder) { 
     MediaPlayerService.LocalBinder binder=(MediaPlayerService.LocalBinder)iBinder; 
     mediaPlayerServiceObject=binder.getService(); 
     ServiceBinding=true; 
     getSeekBarStatus(); 

    } 

    @Override 
    public void onServiceDisconnected(ComponentName componentName) { 
     stopService(PlayerServiceIntent); 
     onStop(); 
     ServiceBinding=false; 
    } 
};