Activity中的android Asynctask调用方法

时间:2013-05-18 20:43:24

标签: android android-asynctask android-activity

我正在通过AsyncTask从ftp-server下载视频并将其保存在设备上。下载后(onPostExecute)我想直接在我的活动视频中播放视频,但问题是无法调用我的playVideo方法,因为它不是静态的,而是我试图在onResume()方法中调用它,使用get()方法,但我的ASynctask中的进度条不会显示,然后应用程序崩溃。有什么建议吗?

先谢谢你

公共类PlayStreamedVideo扩展了Activity {

final String TAG = "PlayStreamedVideo";
private VideoView videoView;
private MediaController mediaController;
private DownloadVideo download;

@Override
public void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);

    setContentView(R.layout.guessvideo);
    setRequestedOrientation(ActivityInfo.SCREEN_ORIENTATION_PORTRAIT);

    download = new DownloadVideo(PlayStreamedVideo.this, SAVE_PATH);
    download.execute();

}
    @Override
    protected void onResume(){
        try {
            while(download.get() == false){
                Log.d(TAG, "1");
            }
            playVideo();
        } catch (InterruptedException e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
        } catch (ExecutionException e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
        }
        super.onResume();   
    }

public void playVideo() {
    try {
        videoView = (VideoView) findViewById(R.id.streamedVideoSurface);
        mediaController = new MediaController(this);
        videoView.setVideoURI(Uri.parse(SAVE_PATH));
        videoView.setMediaController(mediaController);
        videoView.start();
    } catch (Exception e) {
        // Log.e(TAG, "error: " + e.getMessage(), e);
    }
}

2 个答案:

答案 0 :(得分:0)

在我看来,你不应该在onResume方法中调用该函数。您可以将指向活动的指针传递给asynctask,然后在执行后调用play函数:

download = new DownloadVideo(PlayStreamedVideoActivity, SAVE_PATH);

您传递的内容是第一个参数是上下文,而不是代表您的活动的实例。

然后将函数调用到onPostExecute中,如下所示:

PlayStreamedVideoActivity.playVideo();

请记住修改你的asynctask构造函数。

答案 1 :(得分:0)

我认为将videoView声明为PlayStreamedVideo类的成员更容易。 将声明放在onCreate():

    videoView = (VideoView) findViewById(R.id.streamedVideoSurface);
    mediaController = new MediaController(this);
    videoView.setMediaController(mediaController);

然后从onPostExecute()调用:

    videoView.setVideoURI(Uri.parse(SAVE_PATH));
    videoView.start();