我正在创建一个必须具有互联网连接的应用, 如果连接丢失,我需要禁用与用户的任何交互。
我通过听android.net.conn.CONNECTIVITY_CHANGE来做到这一点。 效果很好。
我想设置一个警告对话框,并从BroadcastReceiver中将整个背景变灰。
无论如何要做到这一点?
感谢。
沙哈尔。
答案 0 :(得分:0)
如果有人想知道, 我在我的主要活动中使用了广播接收器。
/*
here we handle connection lost event
show a popup over the screen to notify the user
*/
static final String ACTION = "android.net.conn.CONNECTIVITY_CHANGE";
public class ConnectionReceiver extends BroadcastReceiver {
private static final String TAG = "ConnectionReceiver";
private AlertDialog alertDialog;
public ConnectionReceiver() {
}
@Override
public void onReceive(Context context, Intent intent) {
if (intent.getAction().equals("android.net.conn.CONNECTIVITY_CHANGE")) {
ConnectivityManager cm =
(ConnectivityManager) context.getSystemService(Context.CONNECTIVITY_SERVICE);
NetworkInfo activeNetwork = cm.getActiveNetworkInfo();
boolean isConnected = activeNetwork != null &&
activeNetwork.isConnectedOrConnecting();
if (isConnected) {
try {
if (alertDialog != null && alertDialog.isShowing())
alertDialog.dismiss();
} catch (Exception e) {
e.printStackTrace();
}
} else {
if (alertDialog == null || !alertDialog.isShowing()) {
AlertDialog.Builder builder = new AlertDialog.Builder(context);
builder.setTitle("No internet connection");
builder.setMessage("check your connection.");
builder.setCancelable(false);
alertDialog = builder.create();
alertDialog.show();
}
}
}
}
}