第五章、AsyncTaskとProgressBarの練習(Android)

3362 ワード



    


package com.example.demo07;

import android.app.Activity;
import android.os.AsyncTask;
import android.os.Bundle;
import android.util.Log;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.Button;
import android.widget.ProgressBar;
import android.widget.Toast;

public class MainActivity extends Activity implements OnClickListener {

	Button button_start, button_stop;
	ProgressBar pd;
	MyTask as;

	@Override
	protected void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
		setContentView(R.layout.activity_main);
		//      
		init();

	}

	private void init() {
		button_start = (Button) this.findViewById(R.id.main_start);
		button_stop = (Button) this.findViewById(R.id.main_stop);
		pd = (ProgressBar) this.findViewById(R.id.main_progress);
		button_start.setOnClickListener(this);
		button_stop.setOnClickListener(this);

	}

	//     
	@Override
	public void onClick(View arg0) {

		//      
		if (button_start.getId() == arg0.getId()) {
			as = new MyTask();
			// execute()        。         。
			//      doInBackground        ,            
			as.execute();
			
			//      
		} else if (button_stop.getId() == arg0.getId()) {
			as.cancel(true);
		}

	}

	//       AsyncTask
	class MyTask extends AsyncTask {

		@Override
		protected void onPreExecute() {
			// TODO Auto-generated method stub
			super.onPreExecute();
			Log.i("qing", "onPreExecute");
		}

		@Override
		protected String doInBackground(String... arg0) {

			/*****************************************
			 *        ,     try  ,          sleep,
			 *   AsyncTask cancel()      AsyncTask    ,
			 *      AsyncTask          Thread.sleep(),
			 *      cancel()    ,    。

そうでないと、*はcancel()メソッドを実行しますが、ループします.しかしこのAsyncTaskは止まらない.try { for (int i = 0; i <= 100; i++) { Thread.sleep(100); publishProgress(i); } } catch (InterruptedException e) { e.printStackTrace(); } return null; } @Override protected void onProgressUpdate(Integer... values) {//TODO Auto-generated method stub pd.setProgress(values[0]); Log.i("q", "onProgressUpdate"); } @Override protected void onPostExecute(String result){//TODO Auto-generated method stub Toast.makeText(getApplication()、「進捗完了」,Toast.LENGTH_SHOP).show();Log.i("q","onPostExecute");}@Override protected void onCancelled() {//TODO Auto-generated method stub super.onCancelled(); Log.i("q", "onCancelled"); } } }
デバッグスクリーンショット: