簡體   English   中英

按下后,Android取消異步任務

[英]Android Cancel Async task when back pressed

我正在從異步任務加載視頻。 如果視頻加載時間過長,請后退以取消。

我的代碼在這里

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

}

我調試了我的應用程序。

當按下時,則不會調用方法。 我不知道是什么問題

謝謝

刪除super.onBackPressed(); onBackPressed()工作。要取消異步,可以調用sync.cancel()

在活動中聲明異步任務。

private YourAsyncTask mTask;

在要使用的地方實例化異步任務

mTask = new YourAsyncTask().execute();

然后取消要停止任務的位置

mTask.cancel(true);

希望這可以幫助

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM