如何通过媒体播放器服务获取搜索栏的活动?

时间:2011-08-29 05:31:31

标签: android service

我正在创建一个媒体播放器服务来播放来自互联网的媒体文件,如下所示:

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

但我不能:(请帮我怎么做!

修改

我找到了另一种方法来解决我的问题而不使用Bind服务:) 这是:

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

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

当然,你必须声明一个静态变量:

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

这就是全部!希望这有帮助:)

如果我对英语有误,请原谅我;),我的英语技能不好:)

2 个答案:

答案 0 :(得分:1)

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

有关Bind的更多信息,请参阅以下文档

Click here

修改

另见下面的教程

Click Here

答案 1 :(得分:1)

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

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