2013-03-21 33 views
1

我嘗試執行下面的代碼,但它正在創建問題。沒有這個代碼工作正常。我想要一個對話框彈出,並要求用戶在其關閉時啓用Wifi。Alertdialog不起作用,它在Android中發生異常

@Override 
protected void onCreate(Bundle savedInstanceState) { 
    // TODO Auto-generated method stub 
    super.onCreate(savedInstanceState); 
    setContentView(R.layout.welcome); 
    Thread timer = new Thread(){ 
     public void run(){ 
      try{ 
       sleep(2000);      
      }catch(InterruptedException e){ 
       e.printStackTrace(); 
      } 
      finally{      
       showAlert();      
      } 
     } 
    }; 
    timer.start(); 
} 

} 

public void showAlert() { 

    AlertDialog.Builder alertDialogBuilder = new AlertDialog.Builder(this); 

    // set title 
    alertDialogBuilder.setTitle("Your Title"); 

    // set dialog message 
    alertDialogBuilder 
      .setMessage("Click yes to exit!") 
      .setCancelable(false) 
      .setPositiveButton("Yes", 
        new DialogInterface.OnClickListener() { 
         public void onClick(DialogInterface dialog, int id) { 
          // if this button is clicked, close 
          // current activity 
          Welcome.this.finish(); 
         } 
        }) 
      .setNegativeButton("No", new DialogInterface.OnClickListener() { 
       public void onClick(DialogInterface dialog, int id) { 
        // if this button is clicked, just close 
        // the dialog box and do nothing 
        dialog.cancel(); 
       } 
      }); 

    // create alert dialog 
    AlertDialog alertDialog = alertDialogBuilder.create(); 


     // show it 
     alertDialog.show(); 
} 

這裏是日誌歷史和註釋行內的ProgressDialog代碼也拋出了同樣的錯誤!:

11:46:57.306: E/AndroidRuntime(2140): FATAL EXCEPTION: Thread-141 
11:46:57.306: E/AndroidRuntime(2140): java.lang.RuntimeException: Can't create handler inside thread that has not called Looper.prepare() 
11:46:57.306: E/AndroidRuntime(2140): at android.os.Handler.<init>(Handler.java:197) 
11:46:57.306: E/AndroidRuntime(2140): at android.os.Handler.<init>(Handler.java:111) 
11:46:57.306: E/AndroidRuntime(2140): at android.app.Dialog.<init>(Dialog.java:107) 
11:46:57.306: E/AndroidRuntime(2140): at android.app.AlertDialog.<init>(AlertDialog.java:114) 
11:46:57.306: E/AndroidRuntime(2140): at android.app.AlertDialog$Builder.create(AlertDialog.java:931) 
11:46:57.306: E/AndroidRuntime(2140): at com.example.core4voipmobiledialer.Welcome.showAlert(Welcome.java:116) 
11:46:57.306: E/AndroidRuntime(2140): at com.example.core4voipmobiledialer.Welcome$1.run(Welcome.java:35) 

回答

2

使用runOnUiThread以顯示線程ToastAlert Dialog

runOnUiThread(new Runnable() 
{ 
    @Override 
    public void run() 
    { 
    showAlert();   
    } 
}); 

你從工作者線程調用它。您需要從主線程中調用Toast.makeText()或Alert Dialog。你也可以使用處理程序。

0
  1. 你必須把Looper.prepare()showDialog()方法內
  2. 要打開WiFi設置啓動一個新的意圖:

startActivity(new Intent(WifiManager.ACTION_WIFI_SETTINGS));

(假看到android doc關於最後一點)