开发者

How to get seekbar in activity from mediaplayer service?

I'm creating a mediaplayer service to play a media file from internet, like this:

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();

}
}

Now I want to get the seekbar from the activity like this:

SeekBar se开发者_运维百科ekbar= (SeekBar)findviewbyid(R.id.seekbar);

But I can't :( Please help me how to do that!

EDIT

I found another way to solve my problem without using Bind service :) Here it is:

In your service class, create a static method like this:

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

Ofcourse, you must declare a static varible:

private static Player_Activity  MAIN_ACTIVITY;

Next, in your activity, before you call the startService(), you must call this method to set the main activity to your service like this:

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

And finally you can do anything with your activity in your service like this:

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

That's all! Hope this help :)

Forgive me if I get some mistake about English ;), my English skill is not good :)


I know that it has been already answered. But I tried the below code which worked for me.May be useful for someone.

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();
}

}

Note:In service class I had issue in getting MediaPlayer duration. I am not getting correct result when my activity requests duration from service. So I have implemented a method which gets the duration right from the activity. Hope you can fix duration in service itself. But this code worked for me.

Then in your Activity, after onCreate() method.

 /**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;
    }
};


You are playing media in service so to communicate with service you have to bind activity with service.

For more information about Bind see below document

Click here

EDIT

Also see below tutorial

Click Here

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜