如何在Android中使用后台线程更新进度条?同时也需要更改进度条上的进度。请帮忙。
AndroidVogue
AndroidVogue
AsyncTask
来完成类似的任务。在 AsyncTask
中,有一个方法 onProgressUpdate(Integer)
,你可以在每次迭代或者在 doInBackground()
执行期间某个进度完成时调用 publishProgress()
来触发它。Thread t=new Thread()
{
public void run()
{
while(some condition)
{
sleep(1000);
Message myMessage = new Message();
myMessage.obj = "success";
handler.sendMessage(myMessage);
}
}
};
private Handler handler=new Handler()
{
@Override
public void handleMessage(Message msg)
{
String result=(String)msg.obj;
if(result.equals("success")
{
//update progress bar here
}
}
};
// this is demonstrate how to update progress bar from a thread
private ProgressBar pgb; // is a progressBar named with pgb
private int progressBarStatus = 0;// is a variable named progressBarStatus and initialize by 0
// in onCreate method find the ui component view horizontal prograssbar named progressBar2
public void load_bar(View view) // is a button OnClick
// and i am using a thread with for loop to demonstrate a task and variable progressBarStatus as status
pgb = (ProgressBar) findViewById(R.id.progressBar2) ;// find view by id
pgb.setMax(100); // at this point we the maximum value of a progress bar to make it full like we make 100 pices of it
pgb.setProgress(0); // initialize the progress bar with 0 % progress
// progress bar handler that update the status of progress bar . without handler we cant update progress bar from thread
progressBarbHandler.post(new Runnable() {
public void run() {
pgb.setProgress(progressBarStatus);
}
public void loadProgressbar()
{
progressBar.setMax(100);
progressBar.setProgress(0);
new Thread(new Runnable() {
@Override
public void run() {
for (progress = 0; progress <= 100; progress++) {
handler.post(new Runnable() {
public void run() {
progressBar.setProgress(progress);
}
});
try {
Thread.sleep(50);
} catch (Exception ex) {
}
}
}
}).start();
}
private ProgressBar pgb;
private TextView textview;
private int progressBarStatus = 0;
private Handler progressBarbHandler = new Handler();
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_next);
pgb = (ProgressBar) findViewById(R.id.progressBar2) ;
}
public void load_bar(View view)
{
pgb.setMax(100);
pgb.setProgress(0);
new Thread(new Runnable() {
@Override
public void run() {
for (progressBarStatus = 0; progressBarStatus <= 100; progressBarStatus++) {
progressBarbHandler.post(new Runnable() {
public void run() {
pgb.setProgress(progressBarStatus);
}
});
try {
Thread.sleep(50);
} catch (Exception ex) {
}
}
}
}).start();
}
yourActivity.this.runOnUiThread(new Runnable(){ public void run(){ /* 在此更新进度条 */ }})
。 - Jaiprakash Soni