2011-08-29 60 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; 
    } 
};