how to check internet connection in asynctask in android

后端 未结 4 1004
一整个雨季
一整个雨季 2021-01-14 23:33
@Override
    protected void onCreate(Bundle savedInstanceState) {
        // TODO Auto-generated method stub
        super.onCreate(savedInstanceState);
        req         


        
4条回答
  •  星月不相逢
    2021-01-15 00:12

    You should use a broadcast receiver as mentioned in other SO answers, but since you have asked how to do this otherwise, here you go:

     * Checks for an existing network connectivity
     * 
     * @param context
     *            The {@link Context} which is needed to tap
     *            {@link Context#CONNECTIVITY_SERVICE}
     * @return True if network connection is available
     */
    public static boolean isNetworkAvailable(Context context) {
        ConnectivityManager connectivity = (ConnectivityManager) context
                .getSystemService(Context.CONNECTIVITY_SERVICE);
    
        if (connectivity == null) {
            return false;
        } 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;
                    }
                }
            }
        }
        return false;
    }
    

    Will need additional permission to be specified in the manifest file

提交回复
热议问题