package gr.mybook.myasynctask;

import android.app.Activity;
import android.os.AsyncTask;
import android.os.Bundle;
import android.os.SystemClock;
import android.view.View;
import android.widget.Button;
import android.widget.ProgressBar;
import android.widget.TextView;

public class Activity_1 extends Activity {
	Button btn;
	TextView text;
	ProgressBar bar;
	
    /** Called when the activity is first created. */
    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.main_1);
        
         btn = (Button) findViewById(R.id.button1);
         bar = (ProgressBar) findViewById(R.id.progress);
         text = (TextView) findViewById(R.id.textView1);
         
         btn.setOnClickListener(new View.OnClickListener() {
            public void onClick(View v) {
               btn.setEnabled(false);
        	   new myAsyncTask().execute();
            }
         });
     }
    
    public void onClick(View view) {
    	//start executing AsyncTask
    	btn.setEnabled(false);
    	btn.setClickable(false);
		new myAsyncTask().execute();
    }
    
    private class myAsyncTask extends AsyncTask<Void, Integer, Void> {
    	int progress_status;
    	@Override
    	protected void onPreExecute() {
    		progress_status = 0;
    		text.setText("downloading 0%");
    	}
    	
    	@Override
    	protected Void doInBackground(Void...unused){
    		   while(progress_status<100){
    			    progress_status += 2;
    			    publishProgress(progress_status);
    			    SystemClock.sleep(300);
     		   }
    		   return null;
    	}
    	
    	@Override
    	  protected void onProgressUpdate(Integer... values) {
    	   super.onProgressUpdate(values);
    	   bar.setProgress(values[0]);
    	   text.setText("downloading " +values[0]+"%");
    	  }
    	   
    	@Override
    	  protected void onPostExecute(Void result) {
    	    super.onPostExecute(result);
    	    text.setText("download complete");
    	    btn.setEnabled(true);
    	  }
    }
}