2013-10-03 55 views
0

此代碼來自一本書。進度對話似乎在非UI線程中顯示。ProgressDialog顯示在非UI線程中

但正如我所知,只在UI線程這是可能的。

我想知道爲什麼可以在非Ui線程中顯示ProgressDialog。

public class BackWork3 extends Activity 
{ 
    TextView mResult; 
    public void onCreate(Bundle savedInstanceState) 
    { 
     super.onCreate(savedInstanceState); 
     setContentView(R.layout.backwork); 
     mResult = (TextView)findViewById(R.id.result); 
    } 
    public void mOnClick(View v) 
    { 
     int start = 0, end = 100; 
     int result; 
     WaitDlg dlg = new WaitDlg(BackWork3.this, "WaitTest", "Now calculating"); 
     dlg.start(); 
     result = Accumulate(start, end); 
     mResult.setText("" + result); 
     WaitDlg.stop(dlg); 
    } 
    int Accumulate(int start, int end) 
    { 
     int sum = 0; 
     for (int i = start; i <= end; i++) 
     { 
      sum += i; 
      try { Thread.sleep(20); } catch (InterruptedException e) {;} 
     } 
     return sum; 
    } 
} 
class WaitDlg extends Thread 
{ 
    Context mContext; 
    String mTitle; 
    String mMsg; 
    ProgressDialog mProgress; 
    Looper mLoop; 

    WaitDlg(Context context, String title, String msg) 
    { 
     mContext = context; 
     mTitle = title; 
     mMsg = msg; 

     setDaemon(true); 
    } 

    public void run() 
    { 
     Looper.prepare(); 
     mProgress = new ProgressDialog(mContext); 
     mProgress.setProgressStyle(ProgressDialog.STYLE_SPINNER); 
     mProgress.setTitle(mTitle); 
     mProgress.setMessage(mMsg); 
     mProgress.setCancelable(false); 
     mProgress.show(); 

     mLoop = Looper.myLooper(); 
     Looper.loop(); 
    } 


    static void stop(WaitDlg dlg) 
    { 
     dlg.mProgress.dismiss(); 

     try { Thread.sleep(100); } catch (InterruptedException e) {;} 

     dlg.mLoop.quit(); 
    } 
} 
//------------------------------------------------------------------------------ 
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android" 
android:orientation="vertical" 
android:layout_width="match_parent" 
android:layout_height="match_parent" 
> 
<Button 
android:id="@+id/start" 
android:layout_width="wrap_content" 
android:layout_height="wrap_content" 
android:onClick="mOnClick" 
android:text="Start" 
/> 
<TextView 
android:id="@+id/result" 
android:layout_width="match_parent" 
android:layout_height="wrap_content" 
android:textSize="40sp" 
android:text="result" 
/> 
</LinearLayout> 

回答

0

該代碼是使用Looper非UI線程內部的創建一個處理程序和該活套成爲該處理程序的參考。這樣你就可以在非UI線程中使用UI元素。

根據Docs。

Looper.Prepare(): 

Initialize the current thread as a looper. This gives you a chance to create handlers that then reference this looper, before actually starting the loop. 

希望這有助於

+0

我是這麼認爲的,但是當我拼命地跑這個代碼,它沒有任何問題的作品 –

+0

我拼命地跑4.1.2 –

+0

@ user2810413如果我的回答解決您的查詢好心紀念這個問題解決了通過接受答案:) –