2010-12-16 75 views
0

我需要显示进度消息给用户。但我无法显示。这里是我的代码。我的代码出了什么问题。指导我做。如何在Android中显示进度对话框?

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); 
} 

}

回答

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,这是你的,这两种工作。选择一个最适合你的人。

+0

感谢您的亲切帮助! – RMK 2010-12-18 06:48:18

0

什么你想做到完美适合在Android中AsyncTask framework。尝试通过继承AsyncTask类来实现它,负责将所有UI相关的东西放入onPreExecute/onPostExecute方法中,并且在doInBackground方法中使用长时间方法。

如果您需要活动的内容,请将其作为参数传递给AsyncTask的构造函数,或者将AsyncTask作为活动的内部类。

+0

感谢您的亲切帮助! – RMK 2010-12-18 09:49:56

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(); 
    } 
} 
+0

感谢您的亲切帮助! – RMK 2010-12-18 09:49:17