我想在我的應用程序中使用BroadcastReceiver獲得互聯網連接狀態。如果沒有互聯網可用,我想顯示一個AlertDialog框。
這裏是我的廣播接收器:
public class ConnectivityChangedReceiver extends BroadcastReceiver{
@Override
public void onReceive(Context context, Intent intent)
{
ConnectivityManager connectivityManager = (ConnectivityManager) context.getSystemService(Context.CONNECTIVITY_SERVICE);
NetworkInfo networkInfo = connectivityManager.getActiveNetworkInfo();
if (networkInfo != null && networkInfo.isConnected()) {
} else {
showInternetAlertDialog(context);
}
}
public void showInternetAlertDialog(Context context){
AlertDialog.Builder builder = new AlertDialog.Builder(context);
builder.setMessage("You have no internet connection.")
.setPositiveButton("Retry", new DialogInterface.OnClickListener() {
public void onClick(DialogInterface dialog, int id) {
dialog.dismiss();
}
}
});
builder.show();
return;
}
}
我有太多定義了這個接收器在我的清單。我已經定義了在清單中訪問網絡狀態的權限。
<receiver android:name="com.lisnx.service.ConnectivityChangedReceiver"
android:label="NetworkConnection">
<intent-filter>
<action android:name="android.net.conn.CONNECTIVITY_CHANGE"/>
</intent-filter>
</receiver>
但是,當互聯網不見了,AlertDialog盒試圖打開,我得到以下異常:
10-19 16:25:21.474 E/AndroidRuntime(6864): android.view.WindowManager$BadTokenException: Unable to add window -- token null is not for an application
10-19 16:25:21.474 E/AndroidRuntime(6864): at android.view.ViewRoot.setView(ViewRoot.java:509)
10-19 16:25:21.474 E/AndroidRuntime(6864): at android.view.WindowManagerImpl.addView(WindowManagerImpl.java:177)
10-19 16:25:21.474 E/AndroidRuntime(6864): at android.view.WindowManagerImpl.addView(WindowManagerImpl.java:91)
10-19 16:25:21.474 E/AndroidRuntime(6864): at android.app.Dialog.show(Dialog.java:241)
我認爲它的語境的問題,但我不能找出究竟是什麼問題。請幫助我。任何解決方案將不勝感激。提前Thanx。
你確定傳入的上下文不是null嗎? – Shine
錯誤的標記異常通常與您在創建Dialog實例時所處的上下文(您在傳入錯誤類型的上下文時同時使用Toast和ProgressDialog)相關聯。 根據我的經驗,當你從'Activity'實例化一個對話框並且你傳遞'getApplicationContext()'而不是'this'時會發生這種情況。雖然我沒有'BroadcastReceiver's的使用經驗,所以我不確定這裏的情況是否一樣。 – Closeratio