Skip to content

Instantly share code, notes, and snippets.

@MostafaAnter
Created July 1, 2015 18:29
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save MostafaAnter/af751fc66392c7f6ac89 to your computer and use it in GitHub Desktop.
Save MostafaAnter/af751fc66392c7f6ac89 to your computer and use it in GitHub Desktop.
Handel AsyncTask with Horizontal progress Bar
package com.mostafaanter.manageasynctaskwithhorizontalprogressbar;
import android.os.AsyncTask;
import android.support.v7.app.ActionBarActivity;
import android.os.Bundle;
import android.text.method.ScrollingMovementMethod;
import android.view.Menu;
import android.view.MenuItem;
import android.view.View;
import android.widget.ProgressBar;
import android.widget.TextView;
public class MainActivity extends ActionBarActivity {
private TextView tv ;
private ProgressBar pb;
private int prograssStatus = 0;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
tv = (TextView)findViewById(R.id.textView);
tv.setMovementMethod(new ScrollingMovementMethod());
pb = (ProgressBar)findViewById(R.id.progressBar);
pb.setVisibility(View.INVISIBLE);
}
@Override
public boolean onCreateOptionsMenu(Menu menu) {
// Inflate the menu; this adds items to the action bar if it is present.
getMenuInflater().inflate(R.menu.menu_main, menu);
return true;
}
@Override
public boolean onOptionsItemSelected(MenuItem item) {
// Handle action bar item clicks here. The action bar will
// automatically handle clicks on the Home/Up button, so long
// as you specify a parent activity in AndroidManifest.xml.
int id = item.getItemId();
//noinspection SimplifiableIfStatement
if (id == R.id.action_settings) {
MyTask myTask = new MyTask();
myTask.execute("Param1", "Param2", "Param3");
return true;
}
return super.onOptionsItemSelected(item);
}
private void updateText(String task) {
tv.append(task + "\n");
}
private class MyTask extends AsyncTask<String, String, String>{
@Override
protected void onPreExecute() {
updateText("Starting Task..");
pb.setVisibility(View.VISIBLE);
}
@Override
protected String doInBackground(String... params) {
for(int i=0; i<params.length; i++){
prograssStatus += 34;
publishProgress("Working with Param" + params[i]);
try {
Thread.sleep(1000);
} catch (InterruptedException e) {
e.printStackTrace();
}
pb.setProgress(prograssStatus);
}
return "Task Done.";
}
@Override
protected void onPostExecute(String s) {
updateText(s);
prograssStatus = 0;
pb.setVisibility(View.INVISIBLE);
}
@Override
protected void onProgressUpdate(String... values) {
updateText(values[0]);
}
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment