2013-02-27 28 views
2

我想在互聯網離線時顯示對話框,但我嘗試這樣做時出現錯誤...我的代碼如下... 你能告訴我我做錯了什麼嗎?顯示互聯網設置的對話窗口

這裏是代碼,我怎麼查是網絡啓用與否:

if (!isOnline()) 
    { 
     showNoConnectionDialog(getApplicationContext()); 
     //Toast.makeText(getApplicationContext(), "Internet connection is disabled!", Toast.LENGTH_LONG).show(); 
    } 

這個代碼是如何顯示在我的應用程序的對話框:

public static void showNoConnectionDialog(Context ctx1) 
{ 
    final Context ctx = ctx1; 
    AlertDialog.Builder builder = new AlertDialog.Builder(ctx); 
    builder.setCancelable(true); 
    builder.setMessage(R.string.no_connection); 
    builder.setTitle(R.string.no_connection_title); 
    builder.setPositiveButton(R.string.settings_button_text, new DialogInterface.OnClickListener() { 
     public void onClick(DialogInterface dialog, int which) 
     { 
      ctx.startActivity(new Intent(Settings.ACTION_WIRELESS_SETTINGS)); 
     } 
    }); 

    builder.setNegativeButton(R.string.cancel_button_text, new DialogInterface.OnClickListener() 
    { 
     public void onClick(DialogInterface dialog, int which) 
     { 
      return; 
     } 
    }); 

    builder.setOnCancelListener(new DialogInterface.OnCancelListener() 
    { 
     public void onCancel(DialogInterface dialog) { 
      return; 
     } 
    }); 

    builder.show(); 
} 

public boolean isOnline() 
{ 
    ConnectivityManager cm = (ConnectivityManager) getSystemService(Context.CONNECTIVITY_SERVICE); 
    NetworkInfo netInfo = cm.getActiveNetworkInfo(); 
    if (netInfo != null && netInfo.isConnectedOrConnecting()) 
    { 
     return true; 
    } 
    return false; 
} 
+1

什麼是錯誤您收到? – Waqas 2013-02-27 19:35:04

+0

請添加LogCat – 2013-02-27 19:36:27

+0

您不能將彈出窗口添加到應用程序,請嘗試發送您的活動的上下文。 – yahya 2013-02-27 19:38:47

回答

1

它爲我工作。

替換此

if (!isOnline()) 
    { 
     showNoConnectionDialog(getApplicationContext()); // Error is here... 
     //Toast.makeText(getApplicationContext(), "Internet connection is disabled!", Toast.LENGTH_LONG).show(); 
    } 

if (!isOnline()) 
    { 
     showNoConnectionDialog(this); 
     //Toast.makeText(getApplicationContext(), "Internet connection is disabled!", Toast.LENGTH_LONG).show(); 
    } 

享受:)

相關問題