如何检查互联网是否有效?不是指残疾人吗?在android中

时间:2013-12-20 13:13:30

标签: android performance android-intent connection

在我的应用程序中,我希望每隔5分钟连续发送当前位置和时间如果网络不可用,应用程序必须存储数据(此处我使用sqlite存储)并在网络启用或互联网连接后发送数据。

我很高兴,但我能看到只能检查移动或wifi网络是否启用。在某些情况下,可能会启用WiFi或移动网络,但互联网将无法正常工作。在这种情况下,我怎么能发现互联网是否正常工作?

我希望你能解决我的问题

6 个答案:

答案 0 :(得分:2)

尝试使用此代码可能会对您有所帮助:

import android.content.Context;
import android.net.ConnectivityManager;
import android.net.NetworkInfo;

public class NetworkUtils {
    public static boolean isNetworkAvailable(Context context) {
        ConnectivityManager connection = (ConnectivityManager) context
                .getSystemService(Context.CONNECTIVITY_SERVICE);
        NetworkInfo nInfo = null;
        if (connection != null) {
            nInfo = connection.getActiveNetworkInfo();
        }
        if (nInfo == null || !nInfo.isConnectedOrConnecting()) {
            return false;
        }

        if (nInfo == null || !nInfo.isConnected()) {
            return false;
        }
        if (nInfo != null
                && ((nInfo.getType() == ConnectivityManager.TYPE_MOBILE) || (nInfo
                        .getType() == ConnectivityManager.TYPE_WIFI))) {
            if (nInfo.getState() != NetworkInfo.State.CONNECTED
                    || nInfo.getState() == NetworkInfo.State.CONNECTING) {
                return false;
            }
        }
        return true;
    }
}

在基类中使用此方法,并在需要检查网络的地方调用它。

public boolean isNetworkAvailable() {
        if (NetworkUtils.isNetworkAvailable(getActivity())) {
            return true;
        } else {
            BaseDialogue.showCustomDialogue(getActivity(), getResources()
                    .getString(R.string.app_name),
                    "No Network",
                    getResources().getString(android.R.string.ok),
                    getResources().getString(android.R.string.cancel), null);
            return false;
        }
    }

答案 1 :(得分:2)

ConnectivityManager的getActiveNetworkInfo()方法返回一个NetworkInfo实例,表示它可以找到的第一个连接的网络接口,如果没有连接,则返回null。检查此方法是否返回null应该足以判断是否有可用的Internet连接。

private boolean isNetworkAvailable() {
ConnectivityManager connectivityManager 
      = (ConnectivityManager) getSystemService(Context.CONNECTIVITY_SERVICE);
NetworkInfo activeNetworkInfo = connectivityManager.getActiveNetworkInfo();
return activeNetworkInfo != null && activeNetworkInfo.isConnected();

}

您还需要:

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

在您的Android清单中。

请注意,拥有有效的网络接口并不能保证特定的网络服务可用。网络问题,服务器停机时间,低信号,强制网络门户,内容过滤器等都可能阻止您的应用访问服务器。例如,在收到Twitter服务的有效回复之前,您无法确定您的应用是否可以访问Twitter。

答案 2 :(得分:1)

这就是我正在使用的:

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

需要此权限:

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

答案 3 :(得分:1)

你也可以这样:

在您的包中创建两个java文件:NetworkConnectivity.javaNetworkMonitorListener.java,如下所示:

<强> NetworkConnectivity.java

public class NetworkConnectivity {

    private static NetworkConnectivity sharedNetworkConnectivity = null;

    private Activity activity = null;

    private final Handler handler = new Handler();
    private Runnable runnable = null;

    private boolean stopRequested = false;
    private boolean monitorStarted = false;

    private static final int NETWORK_CONNECTION_YES = 1;
    private static final int NETWORK_CONNECTION_NO = -1;
    private static final int NETWORK_CONNECTION_UKNOWN = 0;

    private int connected = NETWORK_CONNECTION_UKNOWN;

    public static final int MONITOR_RATE_WHEN_CONNECTED_MS = 5000;
    public static final int MONITOR_RATE_WHEN_DISCONNECTED_MS = 1000;

    private final List<NetworkMonitorListener> networkMonitorListeners = new ArrayList<NetworkMonitorListener>();

    private NetworkConnectivity() {
    }

    public synchronized static NetworkConnectivity sharedNetworkConnectivity() {
        if (sharedNetworkConnectivity == null) {
            sharedNetworkConnectivity = new NetworkConnectivity();
        }

        return sharedNetworkConnectivity;
    }

    public void configure(Activity activity) {
        this.activity = activity;
    }

    public synchronized boolean startNetworkMonitor() {
        if (this.activity == null) {
            return false;
        }

        if (monitorStarted) {
            return true;
        }

        stopRequested = false;
        monitorStarted = true;

        (new Thread(new Runnable() {
            @Override
            public void run() {
                doCheckConnection();
            }
        })).start();

        return true;
    }

    public synchronized void stopNetworkMonitor() {
        stopRequested = true;
        monitorStarted = false;
    }

    public void addNetworkMonitorListener(NetworkMonitorListener l) {
        this.networkMonitorListeners.add(l);
        this.notifyNetworkMonitorListener(l);
    }

    public boolean removeNetworkMonitorListener(NetworkMonitorListener l) {
        return this.networkMonitorListeners.remove(l);
    }

    private void doCheckConnection() {

        if (stopRequested) {
            runnable = null;
            return;
        }

        final boolean connectedBool = this.isConnected();
        final int _connected = (connectedBool ? NETWORK_CONNECTION_YES
                : NETWORK_CONNECTION_NO);

        if (this.connected != _connected) {

            this.connected = _connected;

            activity.runOnUiThread(new Runnable() {
                @Override
                public void run() {
                    notifyNetworkMonitorListeners();
                }
            });
        }

        runnable = new Runnable() {
            @Override
            public void run() {
                doCheckConnection();
            }
        };

        handler.postDelayed(runnable,
                (connectedBool ? MONITOR_RATE_WHEN_CONNECTED_MS
                        : MONITOR_RATE_WHEN_DISCONNECTED_MS));
    }

    public boolean isConnected() {
        try {
            ConnectivityManager cm = (ConnectivityManager) activity
                    .getSystemService(Context.CONNECTIVITY_SERVICE);
            NetworkInfo netInfo = cm.getActiveNetworkInfo();

            if (netInfo != null && netInfo.isConnected()) {
                return true;
            } else {
                return false;
            }
        } catch (Exception e) {
            return false;
        }
    }

    private void notifyNetworkMonitorListener(NetworkMonitorListener l) {
        try {
            if (this.connected == NETWORK_CONNECTION_YES) {
                l.connectionEstablished();
            } else if (this.connected == NETWORK_CONNECTION_NO) {
                l.connectionLost();
            } else {
                l.connectionCheckInProgress();
            }
        } catch (Exception e) {
        }
    }

    private void notifyNetworkMonitorListeners() {
        for (NetworkMonitorListener l : this.networkMonitorListeners) {
            this.notifyNetworkMonitorListener(l);
        }
    }

}

<强> NetworkMonitorListener.java

public interface NetworkMonitorListener {

    public void connectionEstablished();
    public void connectionLost();
    public void connectionCheckInProgress();
}

最后,在您的活动中使用此类,如下所示:例如:

        NetworkConnectivity.sharedNetworkConnectivity().configure(this);
        NetworkConnectivity.sharedNetworkConnectivity().startNetworkMonitor();
        NetworkConnectivity.sharedNetworkConnectivity()
                .addNetworkMonitorListener(new NetworkMonitorListener() {
                    @Override
                    public void connectionCheckInProgress() {
                        // Okay to make UI updates (check-in-progress is rare)
                    }

                    @Override
                    public void connectionEstablished() {
                        // Okay to make UI updates -- do something now that
                        // connection is avaialble

                    }

                    @Override
                    public void connectionLost() {
                        // Okay to make UI updates -- bummer, no connection

                    }
                });

通过这种方式,您可以实时检查互联网连接,并采取相应的行动。

答案 4 :(得分:1)

public class InternetData {
    Activity activity;
    ConnectivityManager connManager;
    NetworkInfo mWifi;

    public InternetData(Activity activity){
        this.activity = activity;
        connManager = (ConnectivityManager) activity.getSystemService(Context.CONNECTIVITY_SERVICE);
        mWifi = connManager.getNetworkInfo(ConnectivityManager.TYPE_WIFI);      
    }

    public boolean hasInternetConnection(){
        if(mWifi.isConnected())
            return true;

        return false;
    }
}

答案 5 :(得分:0)

尝试在项目中实现此方法:

private boolean netCheckin() {
    try {
        ConnectivityManager nInfo = (ConnectivityManager) getSystemService(
            Context.CONNECTIVITY_SERVICE);
        nInfo.getActiveNetworkInfo().isConnectedOrConnecting();
        Log.d(tag, "Net avail:"
            + nInfo.getActiveNetworkInfo().isConnectedOrConnecting());
        ConnectivityManager cm = (ConnectivityManager) getSystemService(
            Context.CONNECTIVITY_SERVICE);
        NetworkInfo netInfo = cm.getActiveNetworkInfo();
        if (netInfo != null && netInfo.isConnectedOrConnecting()) {
            Log.d(tag, "Network Available");
            return true;
        } else {
            Log.d(tag, "Network Not Available");
            return false;
        }
    } catch (Exception e) {
        return false;
    }
}

并在AndroidManifest文件中检查是否提供了互联网权限。