AsyncTask

  • AsyncTask的使用---> Get
  • AsyncTask的取消问题:

`public class ProgressBarTest extends AppCompatActivity {

private ProgressBar mProgressBar;
private MyAsyncTask mTask;

@Override
protected void onCreate(@Nullable Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.progressbar);
    mProgressBar = (ProgressBar) findViewById(R.id.progressBar);
    mTask = new MyAsyncTask();
    mTask.execute();
}

@Override
protected void onPause() {
    super.onPause();
    if (mTask != null && mTask.getStatus() == AsyncTask.Status.RUNNING) {
        mTask.cancel(true);//cancel方法只是将对应的AsyncTask标记为cancel状态,并不是真正的取消线程的执行。
    }
}

class MyAsyncTask extends AsyncTask<Void, Integer, Void> {

    @Override
    protected Void doInBackground(Void... params) {
        //模拟进度更新
        for (int i = 0; i < 100; i++) {
            if (isCancelled()) {
                break;
            }
            //将进度传给ProgressBar
            publishProgress(i);
            try {
                Thread.sleep(50);
            } catch (InterruptedException e) {
                e.printStackTrace();
            }
        }
        return null;
    }

    //获取进度值

    @Override
    protected void onProgressUpdate(Integer... values) {
        if (isCancelled()) {
            return;
        }
        super.onProgressUpdate(values);
        //获取进度更新值
        mProgressBar.setProgress(values[0]);
    }
}

} `

results matching ""

    No results matching ""