Here is a most exhaustive example:
public class ScreenSplash extends Activity {
@Override
protected void onCreate(final Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.screen_splash);
final ProgressBar progress = (ProgressBar)findViewById(R.id.progress);
final TextView textview = (TextView)findViewById(R.id.text);
new MyWorker(this, progress, textview).execute();
}
}
final class MyWorker extends AsyncTask<Void, Integer, Void> {
private static final int titles[] = {R.string.splash_load_timezone,
R.string.splash_load_memory,
R.string.splash_load_genres,
R.string.splash_load_channels,
R.string.splash_load_content};
private static final int progr[] = {30, 15, 20, 25, 20};
private int index;
private final Activity parent;
private final ProgressBar progress;
private final TextView textview;
public MyWorker(final Activity parent, final ProgressBar progress, final TextView textview) {
this.parent = parent;
this.progress = progress;
this.textview = textview;
}
@Override
protected void onPreExecute() {
int max = 0;
for (final int p : progr) {
max += p;
}
progress.setMax(max);
index = 0;
}
@SuppressWarnings("unchecked")
@Override
protected Void doInBackground(final Void... params) {
/* Load timezone. this is very slow - may take up to 3 seconds. */
...
publishProgress();
/* Get more free memory. */
...
publishProgress();
/* Load channels map. */
...
publishProgress();
/* Load genre names. */
...
publishProgress();
/* Preload the 1st screen's content. */
...
publishProgress();
return null;
}
@Override
protected void onProgressUpdate(final Integer... values) {
textview.setText(titles[index]);
progress.incrementProgressBy(progr[index]);
++index;
}
@Override
protected void onPostExecute(final Void result) {
parent.finish();
}
}
For shownig/hiding your progress bar use progress.setVisibility(View.VISIBLE)
and progress.setVisibility(View.GONE)
. There is also View.INVISIBLE
constant; its difference from GONE
is that your progress bar is not drawn but still occupies its space (usefull for some layouts).
与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…