Android:网络连接检查始终失败

时间:2016-07-19 07:21:58

标签: java android

在我的应用程序中有一个带有天气活动的模块。当用户单击并激活天气功能时,会检查网络连接。问题是,直接启动时,我的Toast消息“无网络连接”与Android对话框启用。

当用户点击“启用”时,没有任何内容可以在选项中激活(Everything is on)。 当用户单击“取消”时,对话框消失,应用程序正在运行。

以下是我的活动代码:

@Override
public void onNewIntent(Intent intent) {
    super.onNewIntent(intent);
    setIntent(intent);
}

@Override
public void onStart() {
    super.onStart();
    EasyTracker.getInstance(this).activityStart(this);
    // Connect the client.
    mLocationClient.connect();

    // Registers BroadcastReceiver to track network connection changes.
    mNetworkReceiver = new NetworkReceiver() {
        private MyAlertDialog enableNetworkDialog = null;

        @Override
        public void onNoConnectivity() {
            Toast.makeText(MainActivity.this,
                    getString(R.string.network_disabled), Toast.LENGTH_LONG)
                    .show();

            // If the dialog already prompted, do nothing
            if (enableNetworkDialog != null
                    && enableNetworkDialog.isShowing())
                return;

            // Prompt a dialog for user to open the network settings screen
            enableNetworkDialog = new MyAlertDialog(MainActivity.this,
                    null, getString(R.string.network_disabled), false);
            enableNetworkDialog.setPositiveButton("Enable",
                    new OnClickListener() {
                        @Override
                        public void onClick(DialogInterface dialog,
                                int which) {
                            toggleNetworkSourceSetting();
                        }
                    });
            enableNetworkDialog.setNegativeButton("Cancel",
                    new OnClickListener() {
                        @Override
                        public void onClick(DialogInterface dialog,
                                int which) {
                            dialog.dismiss();
                        }
                    });
            enableNetworkDialog.show();
        }

        @Override
        public void onConnect() {
            if (enableNetworkDialog != null
                    && enableNetworkDialog.isShowing())
                enableNetworkDialog.dismiss();
        }

        @Override
        public void onNetworkChange() {
        }

        @Override
        public void onReconnect() {
        }
    };
}

更新:这是我的清单:

 <!-- Grant the network access permission -->
<uses-permission android:name="android.permission.ACCESS_NETWORK_STATE" />
<uses-permission android:name="android.permission.ACCESS_WIFI_STATE" />
<uses-permission android:name="android.permission.INTERNET" />

这是我的logcat剪切:

[ 07-19 10:43:17.876 18037:18037 D/         ]
                                                              Current Network Info : NetworkInfo: type: mobile_supl[HSPA+, type_ext: mobile_supl], state: DISCONNECTED/DISCONNECTED, reason: dataDisabled, extra: internet.telekom, roaming: false, failover: false, isAvailable: true, isConnectedToProvisioningNetwork: false, isIpv4Connected: false, isIpv6Connected: false

[ 07-19 10:43:17.876 18037:18037 D/         ]
                                                              No network is available

07-19 10:43:19.778 18037-18037/bakteriusdeveloper.master D/Network Connection: mobile is available

更新超级方法:

    /**
 * The subclass of the BroadcastReeiver is used to detect the change of
 * connectivity.
 * 
 */
public class NetworkReceiver extends BroadcastReceiver {

    public NetworkReceiver() {
        super();
    }

    public void onNoConnectivity() {
    };

    public void onNetworkChange() {
    };

    public void onConnect() {
    };

    public void onReconnect() {
    };

    public void toggleNetworkSourceSetting() {
        startActivity(new Intent(
                android.provider.Settings.ACTION_WIRELESS_SETTINGS));
    }

    @Override
    public void onReceive(Context context, Intent intent) {
        ConnectivityManager conn = (ConnectivityManager) context
                .getSystemService(Context.CONNECTIVITY_SERVICE);
        NetworkInfo activNetworkInfo = conn.getActiveNetworkInfo();

        String failMessage = intent
                .getStringExtra(ConnectivityManager.EXTRA_REASON);
        Logger.printMessage(getClass().getSimpleName(), failMessage,
                Logger.DEBUG);
        Boolean isNoConnectivity = intent.getBooleanExtra(
                ConnectivityManager.EXTRA_NO_CONNECTIVITY, false);
        Boolean isFailOver = intent.getBooleanExtra(
                ConnectivityManager.EXTRA_IS_FAILOVER, false);
        Logger.printMessage(getClass().getSimpleName(), "is Failover: "
                + isFailOver, Logger.DEBUG);
        Boolean isNetworkChanged = false;

        NetworkInfo otherNetworkInfo = (NetworkInfo) intent
                .getParcelableExtra(ConnectivityManager.EXTRA_OTHER_NETWORK_INFO);
        NetworkInfo networkInfo = (NetworkInfo) intent
                .getParcelableExtra(WifiManager.EXTRA_NETWORK_INFO);

        Logger.printMessage(getClass().getSimpleName(),
                "Current Network Info : " + networkInfo, Logger.DEBUG);
        Logger.printMessage(getClass().getSimpleName(),
                "Other Network Info : " + otherNetworkInfo, Logger.DEBUG);

        if (networkInfo != null && networkInfo.isConnected()) {
            if (isFailOver) {
                Logger.printMessage(getClass().getSimpleName(),
                        "Network is re-connected and available now",
                        Logger.DEBUG);
                onReconnect();
                return;
            } else {
                Logger.printMessage(getClass().getSimpleName(),
                        "Network is available", Logger.DEBUG);
                onConnect();
                return;
            }

        } else if (networkInfo != null
                && !networkInfo.isConnectedOrConnecting()) {
            // do application-specific task(s) based on the current network
            // state, such
            // as enabling queuing of HTTP requests when currentNetworkInfo
            // is connected etc.
            if (otherNetworkInfo != null
                    && otherNetworkInfo.isConnectedOrConnecting()) {
                isNetworkChanged = true;
            } else {
                Logger.printMessage(getClass().getSimpleName(),
                        "No network is available", Logger.DEBUG);
                onNoConnectivity();
                return;
            }
        }

        // No network is active OR no network is available
        if (activNetworkInfo == null || isNoConnectivity) {
            if (isNetworkChanged) {
                Logger.printMessage(getClass().getSimpleName(),
                        "Change network connectivity", Logger.DEBUG);
                onNetworkChange();
                return;
            } else {
                Logger.printMessage(getClass().getSimpleName(),
                        "No network is available", Logger.DEBUG);
                onNoConnectivity();
                return;
            }
        }
    }
}

我的要求怎么了?有什么想法吗?

2 个答案:

答案 0 :(得分:0)

您可以在onResume中注册NetworkReceiver而不是onStart,并检查它是否有效

答案 1 :(得分:0)

确保在AndroidManifest.xml中添加了网络权限:

<uses-permission android:name="android.permission.INTERNET" />

在清单中注册广播接收器:

<receiver
            android:name=".NetworkReceiver"
            android:enabled="true">
            <intent-filter>
                <action android:name="android.net.conn.CONNECTIVITY_CHANGE" />
            </intent-filter>
</receiver>

然后是NetworkReceiver类:

public class NetworkReceiver extends BroadcastReceiver {

    private static volatile boolean connected;

    @Override
    public void onReceive(final Context context, final Intent intent) {
        Log.d("Network", "Network changed");
        if (intent.getExtras() != null) {
            update();
        }
    }

    public static void update() {
        ConnectivityManager connectivityManager = (ConnectivityManager) ApplicationLoader
                .applicationContext.getSystemService(Context.CONNECTIVITY_SERVICE);
        NetworkInfo networkInfo = connectivityManager.getActiveNetworkInfo();
        connected = networkInfo != null && networkInfo.isConnected();
    }

    public static boolean isConnected() {
        return connected;
    }
}

然后,如果要检查网络状态调用:

NetworkReceiver.update(); // Updates network status
if (NetworkReceiver.isConnected()) {
    // do whatever you want.
}