Android ContentProvider check network access

那年仲夏 提交于 2019-12-08 13:59:31
Rakhita
// check internet connectivity
public static boolean isNetworkAvailable(Context context) {

    boolean networkStatus;
    try {
        ConnectivityManager connectivityManager = (ConnectivityManager) context
            .getSystemService(Context.CONNECTIVITY_SERVICE);
        NetworkInfo activeNetworkInfo = connectivityManager
            .getActiveNetworkInfo();

        networkStatus = (activeNetworkInfo != null && activeNetworkInfo.isConnected()) ? true : false;

    } catch (Exception e) {
        e.printStackTrace();
        DinotaLogger.log(e, Level.SEVERE);
        networkStatus = false;
    }

    return networkStatus;
}

Please make sure to put in manifest file. If you are using an emulator to check this, press F8 to disable network access. This works fine with android 2.3.3 emulator.

dokkaebi

I think you want ConnectivityManager. There's an example here.

That explains how to register for notifications. To check directly, you can get a ConnectivityManager instance:

ConnectivityManager mgr = (ConnectivityManager) context.getSystemService(Context.CONNECTIVITY_SERVICE);
NetworkInfo info = mgr.getActiveNetworkInfo();
boolean is_connected = info.isConnected();
boolean is_available = info.isAvailable();

this code should help you to query if the data network is available or not:

   public static boolean isDataNetworkAvailable(Context context){
        try{
            ConnectivityManager connectivityManager = (ConnectivityManager) context.getSystemService(Context.CONNECTIVITY_SERVICE);
            NetworkInfo activeNetworkInfo = connectivityManager.getActiveNetworkInfo();
            return activeNetworkInfo != null;
        }
        catch (Exception e) { return false; }
    }

It will tell you in boolean that your android is connected to internet.

I used that:

public boolean isNetworkAvailable() {
            try{
                Context context = getApplicationContext();
                ConnectivityManager connectivity = (ConnectivityManager) 
                context.getSystemService(Context.CONNECTIVITY_SERVICE);
                if (connectivity == null) {

                }else{
                    NetworkInfo[] info = connectivity.getAllNetworkInfo();
                    if (info != null) {
                        for (int i = 0; i < info.length; i++) {
                            if (info[i].getState() == NetworkInfo.State.CONNECTED) {
                                return true;
                            }
                        }
                    }
                }
            }catch (Exception e) {
                System.out.println("error");
            }
            return false;
        }

Also put:

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

this line to your android manifest.

I Used this in my application.

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!