我用 aHandler
来达到这个效果。Activity
在你创建的那个中创建它ProgressDialog
,然后将它传递给Handler
你想要从中获得进度的方法。然后您可以向调用方发送一条消息Activity
以更新进度:
public class ClassA extends Activity {
...
private static final int HANDLER_MESSAGE_PERFORM_DIALOG_UPDATE = 0;
...
new Thread(new Runnable()
{
public void run()
{
B objB = new objB();
objB.DownloadFile(handler);
}
}).start();
...
private Handler handler = new Handler(){
@Override
public void handleMessage(Message msg) {
switch(msg.what){
case Constants.HANDLER_MESSAGE_PERFORM_DIALOG_UPDATE:
progress.setProgress(msg.arg1);
break;
default:
Log.w("TAG_NAME","handleMessage / Message type not recognised / msg.what = "+String.valueOf(msg.what));
}
}
};
}
Class B
{
public void DownloadFile(Handler handler)
{
... some work [preparing SOAP request]
while(response.read())
{
//send calculated progress to Class A to update the progress value
sendMessage(handler,HANDLER_MESSAGE_PERFORM_DIALOG_UPDATE,progress);
}
}
private void sendMessage(Handler handler,int what, int arg1){
Message msg = Message.obtain();
msg.what = what;
msg.arg1 = arg1;
handler.sendMessage(msg);
}
}