我需要向用户显示进度消息。但我无法显示。这是我的代码。我的代码出了什么问题。请指导我。
public class MyProgressDemo extends Activity {
/** Called when the activity is first created. */
private Button clickBtn;
public ProgressDialog progressDialog;
Handler handler = new Handler();
@Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.main);
clickBtn = (Button) findViewById(R.id.Button01);
clickBtn.setOnClickListener(new OnClickListener() {
@Override
public void onClick(View v) {
progressDialog = ProgressDialog.show(MyProgressDemo.this, "",
"Please Wait");
processThread();
}
});
}
protected void processThread() {
handler.post(new Runnable() {
@Override
public void run() {
longTimeMethod();
UI();
progressDialog.dismiss();
}
});
}
private void longTimeMethod() {
try {
String strMethod = "MethodName";
String strUrl = "url";
String strResponse = WebserviceCall.Mobileaappstore(strUrl,
strMethod);
Log.d("RES", strResponse);
} catch (Exception e) {
Log.e("Exc", e.getMessage());
}
}
private void UI() {
TextView tv = new TextView(this);
tv.setText("This is new UI");
setContentView(tv);
}
}
答案 0 :(得分:1)
方法Handler.post,在UI线程中产生一个线程,所以你的longTimeMethod();将在UI线程中运行,阻止它。你应该这样做:
protected void processThread() {
Thread t = new Thread(){
longTimeMethod();
// Sends message to the handler so it updates the UI
handler.sendMessage(Message.obtain(mHandler, THREAD_FINISHED));
}
// Spawn the new thread as a background thread
t.start
}
您的处理程序应如下所示,以便管理消息
private Handler mHandler = new Handler() {
@Override
public void handleMessage(Message msg) {
super.handleMessage(msg);
switch (msg.what) {
case THREAD_FINISHED:
UI();
progressDialog.dismiss();
break
}
}
};
您可以使用此解决方案或AsynTask,这取决于您,两者都有效。选择最适合你的那个。
答案 1 :(得分:0)
您尝试做的完全适合Android中的AsyncTask framework。尝试通过继承AsyncTask类来实现它,负责将所有与UI相关的东西放在onPreExecute / onPostExecute方法中,并在doInBackground方法中使用长时间方法。
如果您需要活动中的内容,请将其作为参数传递给AsyncTask的构造函数,或者将AsyncTask作为活动的内部类。
答案 2 :(得分:0)
要添加到MarvinLabs的帖子,您可以像这样显示和解除ProgressDialog。
private class SubmitCommentTask extends AsyncTask<String, Void, Void> {
ProgressDialog dialog;
protected Void doInBackground(String... params) {
// Your long running code here
return null;
}
protected void onPreExecute() {
dialog = ProgressDialog.show(DetailsInfo.this, "Submitting Comment", "Please wait for the comment to be submitted.", true);
}
protected void onPostExecute(Void Result)
{
dialog.dismiss();
}
}