2017-04-22 48 views
0

我从异步任务加载视频。当视频花费太长的时间加载然后按按钮取消。安卓取消重新按下时的异步任务

我的代码在这里

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

}

我调试我的应用程序。

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

谢谢

+0

使用sync.cancel方法来停止asynchtask –

+0

@ Divyesh Patel我已经使用它了。我的问题是当按下后退按钮时。 onBackPressed方法不叫 –

+0

请参考下面的答案。 Upvote如果它对你有帮助。感谢 –

回答

1

删除super.onBackPressed();onBackPressed()到work.And取消异步可以拨打sync.cancel()

+0

当按下后退按钮时会出现什么问题。该方法没有被调用? –

+0

是否奏效? 。您正在通过调用super.onBackpressed()来调用onBackpressed的默认功能。它通常会完成当前活动并返回,而不执行onBackpressed覆盖方法中的下一步。 –

+0

没有onBackPressed方法根本不被调用。按下后退按钮时, –

1

声明你的异步任务的活动。

private YourAsyncTask mTask; 

实例化要使用

mTask = new YourAsyncTask().execute(); 

然后你的异步任务取消要停止任务

mTask.cancel(true); 

希望这有助于

+0

按下后退按钮时会出现什么问题。该方法没有被调用? –

+0

this.finish();完成活动,你必须停止任务。 –

+0

而不是this.finish();使用sync.cancel(true); –