MyTask.java
public class MyTask extends AsyncTask<Void,Integer,String> { private Context context; private Button buttonDownload; private TextView textViewDownload; ProgressDialog progressDialog; public void setButtonDownload(Button button) { this.buttonDownload=button; } public void setTextViewDownload(TextView textView) { this.textViewDownload=textView; } public MyTask(Context context) { this.context=context; } @Override protected String doInBackground(Void... params) { int i=0; synchronized (this) { while (i<101) { try { wait(100); i++; this.publishProgress(i); } catch (InterruptedException e) { e.printStackTrace(); } } } return "Download Completed."; } @Override protected void onPreExecute() { super.onPreExecute(); buttonDownload.setEnabled(false); textViewDownload.setText("Downloading..."); progressDialog=new ProgressDialog(context); progressDialog.setTitle("Downloading ...."); progressDialog.setMax(100); progressDialog.setProgress(0); progressDialog.setProgressStyle(ProgressDialog.STYLE_HORIZONTAL); progressDialog.show(); } @Override protected void onPostExecute(String s) { super.onPostExecute(s); textViewDownload.setText(s); buttonDownload.setEnabled(true); progressDialog.hide(); } @Override protected void onProgressUpdate(Integer... values) { super.onProgressUpdate(values); Integer progress=values[0]; progressDialog.setProgress(progress); } @Override protected void onCancelled(String s) { super.onCancelled(s); if (s.isEmpty()) { textViewDownload.setText("Download Canceled."); } } }
MainActivity.java
public class MainActivity extends AppCompatActivity { TextView textViewDownload; Button buttonDownload; @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_main); textViewDownload= (TextView) findViewById(R.id.textViewDownload); buttonDownload= (Button) findViewById(R.id.buttonDownload); buttonDownload.setOnClickListener(new View.OnClickListener() { @Override public void onClick(View v) { MyTask myTask=new MyTask(MainActivity.this); myTask.setButtonDownload(buttonDownload); myTask.setTextViewDownload(textViewDownload); myTask.execute(); } }); } }
References
https://github.com/mhdr/AndroidSamples/tree/master/050