如何检查互联网是否正常工作?不意味着残疾与否?在安卓中 [英] How to check internet is working or not? not meant disabled or not? in android

查看:36
本文介绍了如何检查互联网是否正常工作?不意味着残疾与否?在安卓中的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

In my application i want to send current location and time continuously each 5min In case network is not available app has to store data (here im using sqlite to store) and send data once network enabled or internet connected.

i goggled lot but i could see only can check mobile or wifi network enabled or not. in some cases wifi or mobile network may be enabled but internet will not be work. In this case how can i find internet is working or not?

I hope you got my problem

解决方案

Try with this code it may help you :

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;
    }
}

Use this method in your base class and call it where ever you want to check network .

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;
        }
    }

这篇关于如何检查互联网是否正常工作?不意味着残疾与否?在安卓中的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆