AsyncTask超时控制

来源:互联网 发布:ios10gamecenter数据 编辑:程序博客网 时间:2024/05/20 02:27

     在用AsyncTask进行异步任务的时候,有的时候想控制在多长时间,异步任务没有完成,就取消该异步任务。实现方法主要是在开一个工作者线程,然后在这个线程中,对异步任务的状态判断,根据返回值判断异步任务十分正确完成。具体代码为:

 Context mContext;   @Override   protected void onCreate(Bundle savedInstanceState) {   super.onCreate(savedInstanceState);         mContext = this;   //async task   final RunTask tsk = new RunTask ();    tsk.execute();   //setting timeout thread for async task   Thread thread1 = new Thread(){   public void run(){    try {     tsk.get(30000, TimeUnit.MILLISECONDS); //set time in milisecond(in this timeout is 30 seconds    } catch (Exception e) {     tsk.cancel(true);            ((Activity) mContext).runOnUiThread(new Runnable()     {       @SuppressLint("ShowToast")      public void run()       {       Toast.makeText(mContext, "Time Out.", Toast.LENGTH_LONG).show();       finish(); //will close the current activity comment if you don't want to close current activity.               }     });    }   }  };  thread1.start();   }
代码中,主要是对异步任务接口中get方法以及cancel接口的时候。

0 0
原创粉丝点击