当活动忙于从服务器开始播放视频时,如何避免黑屏

时间:2013-03-02 11:31:40

标签: android android-mediaplayer

我在按钮点击时打开一个活动,下一个活动是从服务器播放视频,如果我点击按钮,它发生黑色,5-6秒后开始播放视频,怎么能避免黑屏。

这是我的代码:

mPreview=new SurfaceView(getApplicationContext()); 
l1.addView(mPreview); 
holder = mPreview.getHolder(); 
holder.addCallback(this);
holder.setType(SurfaceHolder.SURFACE_TYPE_PUSH_BUFFERS);
extras = getIntent().getExtras(); 

以下内容是表面法。

        path = "http://www.pixintro.com/upload/video/Benetton.mp4";
        mMediaPlayer = new MediaPlayer();
        mMediaPlayer.setDataSource(Environment.getExternalStorageDirectory()+"/Benetton.mp4");
        mMediaPlayer.setDataSource(path);
        mMediaPlayer.setDisplay(holder);
        mMediaPlayer.prepare();
        mMediaPlayer.setOnBufferingUpdateListener(this);
        mMediaPlayer.setOnCompletionListener(this);
        mMediaPlayer.setOnPreparedListener(this);
        mMediaPlayer.setOnVideoSizeChangedListener(this);
        mMediaPlayer.setAudioStreamType(AudioManager.STREAM_MUSIC);

public void onPrepared(MediaPlayer mediaplayer){
       mIsVideoReadyToBePlayed = true;
       if (mIsVideoReadyToBePlayed && mIsVideoSizeKnown){
               holder.setFixedSize(mVideoWidth, mVideoHeight);
               mMediaPlayer.start();
       }
}

2 个答案:

答案 0 :(得分:2)

您可以使用async task。处理正在doInBackground()中完成,即在后台进行。您可以显示一个进度对话框(onPreExecute()),一旦任务完成就会被解除(onPostExecute)。

public class DisplayActivity extends Activity {
     @Override
    protected void onCreate(Bundle savedInstanceState) {
        // TODO Auto-generated method stub
        super.onCreate(savedInstanceState);
        setContentView(R.layout.main_screen);
          // create surface view etc
              new Operation().execute();
}



}

 private class Operation extends AsyncTask<String, Void, String> {

    @Override
    protected String doInBackground(String... params) {
    // code to be executed in background thread 

    for(int i=0;i<5;i++) {
    try {
    Thread.sleep(1000);
    } catch (InterruptedException e) {
    // TODO Auto-generated catch block
    e.printStackTrace();
    }
    }

    return "Executed";
    } 

    @Override
    protected void onPostExecute(String result) {
    // runs on UI thread and updated UI after executing doInBackground
    progressDialog.dismiss();
    }

    @Override
    protected void onPreExecute() {
    ProgressDialog progressDialog = ProgressDialog.show(MainActivity.this, "Title ", "Loading...");
    progressDialog.show();

    }

    @Override
    protected void onProgressUpdate(Void... values) {
    // runs on UI thread and starts first

    }
    } 

答案 1 :(得分:0)

查看this界面。它包含媒体准备播放时的回调。

MediaPlayer也有一个prepareAsync方法。请阅读this了解详情