如何在Android上提供互联网时自动发送请求

时间:2014-10-06 11:26:15

标签: php android

我需要向服务器发出一些请求(对php页面的http请求)。我希望即使互联网不可用,该用户也可以发送帖子,当它可用时,应用必须发送所有未发送的帖子来自viber或whatapps等用户。我不知道这样做,我需要你的帮助。

1 个答案:

答案 0 :(得分:1)

您可以使用这种方式检查Internet是否有效

public class InternetConnection {

    // CHECK FOR INTERNET METHOD
    public static final boolean isInternetOn(Context ctx) {

        boolean isInternetOn = false;
        ConnectivityManager connMgr = (ConnectivityManager) ctx
                .getSystemService(Context.CONNECTIVITY_SERVICE);
        final android.net.NetworkInfo wifi = connMgr
                .getNetworkInfo(ConnectivityManager.TYPE_WIFI);
        final android.net.NetworkInfo mobile = connMgr
                .getNetworkInfo(ConnectivityManager.TYPE_MOBILE);
        TelephonyManager tm = (TelephonyManager) ctx
                .getSystemService(Context.TELEPHONY_SERVICE);

        if (wifi.isAvailable()&&wifi.isConnected()) {

            isInternetOn = true;
        }
        // gets the current TelephonyManager
        else if (tm.getSimState() != TelephonyManager.SIM_STATE_ABSENT) {

            // the phone has a sim card
            if (mobile != null) {

                boolean mobileDataEnabled = false; // Assume disabled
                ConnectivityManager cm = (ConnectivityManager) ctx
                        .getSystemService(Context.CONNECTIVITY_SERVICE);
                try {
                    Class<?> cmClass = Class.forName(cm.getClass().getName());
                    Method method = cmClass
                            .getDeclaredMethod("getMobileDataEnabled");
                    method.setAccessible(true);
                    mobileDataEnabled = (Boolean) method.invoke(cm);
                    if (mobileDataEnabled) {
                        isInternetOn = true;
                    }
                } catch (Exception e)
                {

                    Log.e("Error", e+"");
                }
                return isInternetOn;

            } else {
                isInternetOn = false;
            }
        } else {
            // no sim card available
            isInternetOn = false;
        }

        return isInternetOn;
    }
}