使用异步任务来实现
话不多说上代码
activity_progress.xml
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:tools="http://schemas.android.com/tools"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:paddingBottom="@dimen/activity_vertical_margin"
android:paddingLeft="@dimen/activity_horizontal_margin"
android:paddingRight="@dimen/activity_horizontal_margin"
android:paddingTop="@dimen/activity_vertical_margin"
tools:context=".Progress" >
<ProgressBar
android:id="@+id/progressBar"
style="?android:attr/progressBarStyleHorizontal"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:layout_centerInParent="true"/>
<TextView
android:id="@+id/textView1"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_alignRight="@+id/progressBar"
android:layout_below="@+id/progressBar"
android:layout_marginRight="45dp"
android:layout_marginTop="14dp"
android:text="TextView" />
</RelativeLayout>
Progress.java
package com.example.asynctaskdemo;
import android.os.AsyncTask;
import android.os.Bundle;
import android.app.Activity;
import android.content.Intent;
import android.view.Menu;
import android.widget.ProgressBar;
import android.widget.TextView;
public class Progress extends Activity {
ProgressBar progressBar;
TextView textView;
MyAsyncTask myAsyncTask;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_progress);
progressBar=(ProgressBar) findViewById(R.id.progressBar);
textView=(TextView) findViewById(R.id.textView1);
myAsyncTask=new MyAsyncTask();
myAsyncTask.execute();
}
@Override
protected void onPause() {
super.onPause();
//能够执行另一个异步任务时把上一个异步任务取消掉
if (myAsyncTask!=null && myAsyncTask.getStatus()==AsyncTask.Status.RUNNING){
myAsyncTask.cancel(true);
}
}
class MyAsyncTask extends AsyncTask<Void, Integer, Void>{
@Override
protected void onPostExecute(Void result) {
// TODO Auto-generated method stub
super.onPostExecute(result);
startActivity(new Intent(Progress.this,MainActivity.class));
Progress.this.finish();
}
@Override
protected Void doInBackground(Void... params) {
for(int i=0;i<100;i++){
if (isCancelled()){
break;
}
publishProgress(i);
try {
Thread.sleep(100);
} catch (InterruptedException e) {
e.printStackTrace();
}
}
return null;
}
@Override
protected void onProgressUpdate(Integer... values) {
super.onProgressUpdate(values);
if (isCancelled()){
return;
}
progressBar.setProgress(values[0]+1);
textView.setText(values[0]+1+"%");
}
}
}