我有两个threads.One用于递增值。对于每个增量,我需要通知主线程。 下面是我的主要线程,这是一项活动
public class MainActivity extends Activity {
private ProgressBar progressBar;
private int progressStatus = 1;
private TextView textView;
private Handler handler = new Handler();
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
progressBar = (ProgressBar) findViewById(R.id.progressBar1);
textView = (TextView) findViewById(R.id.textView1);
ProgressUpdate b = new ProgressUpdate();
b.start();
Log.e("SAMEERA", "Satrting ProgressUpdate");
synchronized (b) {
try {
Log.e("SAMEERA", "synchronized synchronized");
Log.e("SAMEERA", "progressStatus is "+b.total);
b.wait();
Log.e("SAMEERA", "progressStatus is "+b.total);
progressBar.setProgress(progressStatus);
textView.setText(progressStatus + "/" + progressBar.getMax());
} catch (InterruptedException e) {
}
System.out.println("Total is: " + b.total);
}
}
}
下面是我的增量线程。
package com.example.zwtouch;
import android.util.Log;
public class ProgressUpdate extends Thread {
int total;
public void run() {
total=0;
synchronized (this) {
for (int i = 0; i < 100; i++) {
total += i;
try {
Thread.sleep(200);
} catch (InterruptedException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
Log.e("SAMEERA", "run run total is "+i);
notify();
}
}
}
}
如果总数增加,我需要每次都通知。但是没有发生。在for循环结束后,它调用主线程......哪里出错?
答案 0 :(得分:3)
使用Handler
ProgressUpdate
和ProgressBar
个对象填充Handler
。Handler
更新ProgressBar
public class ProgressUpdate extends Thread {
int total;
ProgressBar mProgressBar;
Handler mHandler;
public ProgressUpdate(Handler h, ProgressBar pb) {
mHandler = h;
mProgressBar = pb;
}
public void run() {
total=0;
for (int i = 0; i < 100; i++) {
// Update the progress bar via a Handler
mHandler.post(new Runnable() {
public void run() {
mProgressBar.setProgress(i);
}
});
}
}
}
像这样设置
new ProgressUpdate(handler, progressBar).start();
这是另一种方法,您可以使用AsyncTask
来实现此目标。这种方式的优点是onProgressUpdate
和onPostExecute
都在UI-Thread上运行。
将此类置于MainActivity内部
private class ProgressUpdate extends AsyncTask<Void, Integer, Integer> {
protected Integer doInBackground(Void... dummy) {
int total = 0;
for (int i = 0; i < 100; i++) {
total += i;
try {
Thread.sleep(200);
} catch (InterruptedException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
Log.e("SAMEERA", "run run total is "+i);
// Notify UI Thread
publishProgress(i);
}
return total;
}
protected void onProgressUpdate(Integer... i) {
// do something with 'i' on UI Thread
progressBar.setProgress(i);
}
protected void onPostExecute(Integer total) {
// do something with 'total' on UI Thread
// for instance
progressBar.setVisibility(View.GONE);
}
}
在onCreate上设置ProgressUpdate,如下所示
@Override
protected void onCreate(Bundle savedInstanceState) {
// ...
new ProgressUpdate().execute();
// ...
}