-2

我编写了一个代码,它使用互联网将数据插入到我的数据库中,但是如果与互联网的连接不可用,如果数据库不为空,我的应用程序会从数据库中获取数据。

如何编写代码来检查我的应用程序的 Internet 连接性?

4

6 回答 6

2

使用以下代码检查互联网。

public boolean check_Internet(Context mContext) {
        ConnectivityManager mConnectivityManager = (ConnectivityManager) mContext.getSystemService(Context.CONNECTIVITY_SERVICE);
        NetworkInfo mNetworkInfo = mConnectivityManager.getActiveNetworkInfo();

        if (mNetworkInfo != null && mNetworkInfo.isConnectedOrConnecting())
            return true;
        else
            return false;
    }

还要在 AndroidManifest.xml 文件中添加以下权限

<uses-permission android:name="android.permission.ACCESS_NETWORK_STATE" />
于 2013-08-14T11:58:44.520 回答
2

我有一个网络工具给你。

public final class NetworkUtils {
public static final byte CONNECTION_OFFLINE = 1;
public static final byte CONNECTION_WIFI = 2;
public static final byte CONNECTION_ROAMING = 3;
public static final byte CONNECTION_SLOW = 4;
public static final byte CONNECTION_FAST = 5;

private static String sUserId;

private NetworkUtils() {}


/**
 * Check if the device is connected to the internet (mobile network or
 * WIFI).
 */
public static boolean isOnline(Context _context) {
    boolean online = false;

    TelephonyManager tmanager = (TelephonyManager) _context.getSystemService(Context.TELEPHONY_SERVICE);
    if (tmanager != null) {
        if (tmanager.getDataState() == TelephonyManager.DATA_CONNECTED) {
            // Mobile network
            online = true;
        } else {
            // WIFI
            ConnectivityManager cmanager = (ConnectivityManager) _context
                    .getSystemService(Context.CONNECTIVITY_SERVICE);
            if (cmanager != null) {
                NetworkInfo info = cmanager.getActiveNetworkInfo();
                if (info != null)
                    online = info.isConnected();
            }
        }
    }

    return online;
}

/**
 * Get the User Agent String in the format
 * AppName + AppVersion + Model + ReleaseVersion + Locale
 */
public static String getUserAgentString(Context _c, String _appName) {
    if(_appName == null)
        _appName = "";

    String agent = _appName + " " + BackendUtil.getAppVersionString(_c) + " (" + Build.MODEL + "; Android "
            + Build.VERSION.RELEASE + "; " + Locale.getDefault() + ")";

    if(agent.startsWith(" "))
        agent = agent.substring(1);

    return agent;
}

/**
 * Evaluate the current network connection and return the
 * corresponding type, e.g. CONNECTION_WIFI.
 */
public static byte getCurrentNetworkType(Context _context){
    NetworkInfo netInfo = ((ConnectivityManager) _context.getSystemService(Context.CONNECTIVITY_SERVICE)).getActiveNetworkInfo();

    if(netInfo == null)
        return CONNECTION_OFFLINE;

    if(netInfo.getType() == ConnectivityManager.TYPE_WIFI)
        return CONNECTION_WIFI;

    if(netInfo.isRoaming())
        return CONNECTION_ROAMING;

    if(!(netInfo.getType() == ConnectivityManager.TYPE_MOBILE 
            &&  (netInfo.getSubtype() == TelephonyManager.NETWORK_TYPE_UMTS 
              || netInfo.getSubtype() == TelephonyManager.NETWORK_TYPE_HSDPA
              || netInfo.getSubtype() == TelephonyManager.NETWORK_TYPE_HSUPA
              || netInfo.getSubtype() == TelephonyManager.NETWORK_TYPE_HSPA 
              || netInfo.getSubtype() == 13 // NETWORK_TYPE_LTE
              || netInfo.getSubtype() == 15))) // NETWORK_TYPE_HSPAP  
         {

        return CONNECTION_SLOW;
    }

    return CONNECTION_FAST;
}


/**
 * Return the current IP adresse of the device or null if it could not be
 * found.
 */
public static String getIpAdress() {
    String result = null;
    try {
        for (Enumeration<NetworkInterface> interfaces = NetworkInterface.getNetworkInterfaces(); interfaces.hasMoreElements();) {
            NetworkInterface iface = interfaces.nextElement();
            for (Enumeration<InetAddress> adresses = iface.getInetAddresses(); adresses.hasMoreElements();) {
                InetAddress ip = adresses.nextElement();
                if (!ip.isLoopbackAddress())
                    result = ip.getHostAddress();
            }
        }
    } catch (SocketException _e) {
        LL.error("Could not find device's ip adress");
    }
    return result;
}


/**
 * Return a MD5 hash of the device id.
 */
public static synchronized String getUserId(Context _context) {
    if (sUserId == null) {
        TelephonyManager tm = (TelephonyManager) _context.getSystemService(Context.TELEPHONY_SERVICE);
        String id = tm.getDeviceId();
        try {
            MessageDigest digester = MessageDigest.getInstance("MD5");
            digester.update(id.getBytes());
            byte[] digest = digester.digest();

            // Convert to hex string
            BigInteger converter = new BigInteger(1, digest);
            String md5 = converter.toString(16);
            while (md5.length() < 32)
                md5 = "0" + md5;
            sUserId = md5;
        } catch (NoSuchAlgorithmException _e) {
            LL.error("Could not find MD5");
        }
    }
    return sUserId;
}

}

于 2013-08-14T12:04:12.103 回答
1
if (InetAddress.getByName("www.google.com").isReachable(2000)){ // 2000 = timeout
    // connection is available. google is a good candidate
} else {
    // no connection
}
于 2013-08-14T11:59:25.177 回答
1

http://www.androidhive.info/2012/07/android-detect-internet-connection-status/

按照教程...会帮助你...

于 2013-08-14T12:05:14.867 回答
1
Boolean online = isOnline();

        if (online == false) {
            AlertDialog.Builder alertDialogBuilder = new AlertDialog.Builder(
                    context);

            // set title
            alertDialogBuilder.setTitle("Cellular Data is Turned Off!");

            // set dialog message
            alertDialogBuilder
                    .setMessage(
                            "Please turn on cellular data or use Wi-Fi to access data!")
                    .setCancelable(false)
                    .setNeutralButton("Settings",
                            new DialogInterface.OnClickListener() {
                                public void onClick(DialogInterface dialog,
                                        int whichButton) {

                                    startActivity(new Intent(
                                            android.provider.Settings.ACTION_WIRELESS_SETTINGS));
                                }
                            })
                    .setPositiveButton("Ok",
                            new DialogInterface.OnClickListener() {
                                public void onClick(DialogInterface dialog,
                                        int id) {
                                    dialog.cancel();
                                }
                            });

            // create alert dialog
            AlertDialog alertDialog = alertDialogBuilder.create();

            // show it
            alertDialog.show();
于 2013-08-14T12:07:22.643 回答
1

创建如下方法:

public boolean checkInternet() { 
        ConnectivityManager conMan = (ConnectivityManager) getSystemService(Context.CONNECTIVITY_SERVICE); 
        State mobile = conMan.getNetworkInfo(0).getState(); 
        State wifi = conMan.getNetworkInfo(1).getState(); 
        if (mobile == NetworkInfo.State.CONNECTED || wifi== NetworkInfo.State.CONNECTED) 
            return true; 
        else 
            return false; 
        }

在 Activity 或 Service 中,您可以这样做:

if(CheckInternet)
{
     // do your work
}
else
{
      Thread t = new Thread() {
                            @Override
                            public void run() {
                                try 
                                {
                                    //check if connected!
                                    while (!checkInternet()) 
                                    {
                                        //Wait to connect
                                        Thread.sleep(5000);                     
                                    }
                                    //do Your Work here
                                   } catch (Exception e) {
                                }
                            }
                        };
                        t.start();
}

还要在 AndroidManifest.xml 文件中添加以下权限

<uses-permission android:name="android.permission.ACCESS_NETWORK_STATE" />
于 2013-08-14T12:10:38.890 回答