后退时取消Android取消异步任务

时间:2017-04-22 04:49:37

标签: android

我正在从异步任务加载视频。当视频加载时间过长时,请按回来取消。

我的代码在这里

public class LiveStreaming extends AppCompatActivity {

VideoView videoView;
private myAsync sync;
ProgressDialog progressDialog;

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

    getWindow().setFlags(WindowManager.LayoutParams.FLAG_FULLSCREEN,
            WindowManager.LayoutParams.FLAG_FULLSCREEN);
    setContentView(R.layout.activity_live_streaming);


    String videourl = getIntent().getStringExtra("Link");
    videoView = (VideoView) findViewById(R.id.videoStreaming);
    progressDialog = ProgressDialog.show(this, "",
            "Loading TV...", true);
    progressDialog.setCancelable(false);
    // progressDialog.dismiss();
    MediaController mediaController = new MediaController(this);
    mediaController.setAnchorView(videoView);

    Uri video = Uri.parse(videourl);// insert video url
    videoView.setMediaController(mediaController);
    videoView.setVideoURI(video);
    videoView.requestFocus();

    sync = new myAsync();
    sync.execute();
    // PlayVideo();
}


private class myAsync extends AsyncTask<Void, Integer, Void> {

    int duration = 0;
    int current = 0;
    private volatile boolean running = true;

    @Override
    protected void onCancelled() {
        running = true;
    }

    @Override
    protected void onPreExecute() {

    }

    @Override
    protected Void doInBackground(Void... params) {

        videoView.setOnPreparedListener(new MediaPlayer.OnPreparedListener() {

            public void onPrepared(MediaPlayer mp) {
                progressDialog.dismiss();

    videoView.start();
                duration = videoView.getDuration();
            }
        });

        do {

            current = videoView.getCurrentPosition();
            System.out.println("duration - " + duration + " current- "
                    + current);

            if (sync.isCancelled())
                break;

        }

        while (current != duration || current == 0);

        return null;
    }

}

@Override
public void onBackPressed() {
    super.onBackPressed();
    if (sync!=null){
        this.finish();
    }
}

}

我调试了我的应用。

当按下后,方法未被调用。我不知道问题是什么

谢谢

2 个答案:

答案 0 :(得分:1)

删除super.onBackPressed();以使onBackPressed()正常工作。要取消异步,您可以拨打sync.cancel()

答案 1 :(得分:1)

在您的活动中声明您的异步任务。

private YourAsyncTask mTask;

实例化您要使用的异步任务

mTask = new YourAsyncTask().execute();

然后取消您要停止任务的位置

mTask.cancel(true);

希望这有帮助