检查是否有互联网连接

时间:2016-09-29 05:54:29

标签: android wifi

我想在我的应用程序中询问一些我不理解的内容。我从我的服务器获取一些数据,并使用谷歌的Volley库在recyclerview中显示它们。到目前为止很好:)。

接下来,我从列表中获取这些数据,并通过内容提供商将它们添加到SQLite。最后,如果没有互联网连接,我应该从手机的存储库中读取它们(现在我应该收到一条Toast消息,说明没有互联网连接)。这就是事情。当我关闭wifi时,NoInternet Activity不会启动。但是,当我将手机置于飞行模式时,NoInternet活动确实会启动。这是我的代码。

public class AnnouncementsFragment extends Fragment {
public String titleForContentProvider;
public String imageForContentProvider;
public String articleForContentProvider;
public static final String TAG = "AelApp";
private ArrayList<MyModel> listItemsList;
private static final String IMAGE_URL = "http://www.theo-android.co.uk/ael/cms/announcement_images/";
RecyclerView myList;
private AnnouncementsAdapter adapter;

public AnnouncementsFragment() {
    // Required empty public constructor
}


@Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
                         Bundle savedInstanceState) {
    // Inflate the layout for this fragment
    getActivity().setTitle("Ανακοινώσεις");

    View rootView = inflater.inflate(R.layout.fragment_announcements, container, false);
    listItemsList = new ArrayList<>();

    myList = (RecyclerView) rootView.findViewById(R.id.listview_announcements);
    final LinearLayoutManager linearLayoutManager = new LinearLayoutManager(getActivity());
    myList.setHasFixedSize(true);
    myList.setLayoutManager(linearLayoutManager);
    adapter = new AnnouncementsAdapter(getActivity(), listItemsList);
    myList.setAdapter(adapter);

    if (isOnline()) {
        updateAnnouncementsList();
    }else{
        Intent i = new Intent(getActivity(), NoInternet.class);
        startActivity(i);
    }

    return rootView;
}
public void updateAnnouncementsList() {
    listItemsList.clear();


    // Instantiate the RequestQueue.
    RequestQueue queue = Volley.newRequestQueue(getActivity());

    // Request a string response from the provided URL.
    JsonArrayRequest jsObjRequest = new JsonArrayRequest(Request.Method.GET, URL.GET_ANNOUNCEMENTS, new Response.Listener<JSONArray>() {

        @Override
        public void onResponse(JSONArray response) {

            Log.d(TAG, response.toString());
            //hidePD();

            // Parse json data.
            // Declare the json objects that we need and then for loop through the children array.
            // Do the json parse in a try catch block to catch the exceptions
            try {

                for (int i = 0; i < response.length(); i++) {

                    JSONObject post = response.getJSONObject(i);

                    MyModel item = new MyModel();
                    item.setTitle(post.getString("title"));
                    item.setImage(IMAGE_URL + post.getString("announcement_image"));
                    item.setArticle(post.getString("article"));

                    listItemsList.add(item);
                    //Getting the string values out of the JSON response.
                    titleForContentProvider = post.getString("title");
                    imageForContentProvider = post.getString("announcement_image");
                    articleForContentProvider = post.getString("article");
                    //I added them as a key value pair.
                    ContentValues values = new ContentValues();
                    values.put(AELProvider.title,titleForContentProvider);
                    values.put(AELProvider.image,imageForContentProvider);
                    values.put(AELProvider.article,articleForContentProvider);
                    //A Content Resolver that allows the app to
                    //to insert data to the database after
                    //using the Uri defined in the Content Provider
                    Uri uri = getActivity().getContentResolver().insert(AELProvider.CONTENT_URL, values);
                    Log.d("Announcements",uri.toString());
                    Toast.makeText(getContext(), "Announcement added", Toast.LENGTH_LONG)
                            .show();

                }
            } catch (JSONException e) {
                e.printStackTrace();
            }

            // Update list by notifying the adapter of changes
            adapter.notifyDataSetChanged();
        }
    }, new Response.ErrorListener() {
        @Override
        public void onErrorResponse(VolleyError error) {
            VolleyLog.d(TAG, "Error: " + error.getMessage());
            //hidePD();
        }
    });
    queue.add(jsObjRequest);

}

protected boolean isOnline() {
    ConnectivityManager cm = (ConnectivityManager)getActivity().getSystemService(Context.CONNECTIVITY_SERVICE);
    NetworkInfo netInfo = cm.getActiveNetworkInfo();
    if (netInfo != null && netInfo.isConnectedOrConnecting()) {
        return true;
    } else {
        return false;
    }
}
}

有什么想法吗?

谢谢,

西奥。

4 个答案:

答案 0 :(得分:5)

你可以试试这个:

public class Common extends BroadcastReceiver
{
    public static boolean internet_status = false;
    public static void checkInternetConenction(Context context) {
        internet_status = false;
        ConnectivityManager check = (ConnectivityManager) context.getSystemService(Context.CONNECTIVITY_SERVICE);
        if (check != null) {
            NetworkInfo[] info = check.getAllNetworkInfo();
            if (info != null)
                for (int i = 0; i < info.length; i++) {
                    if (info[i].getState() == NetworkInfo.State.CONNECTED) {
                        internet_status = true;
                    }
                }
        }
    }

    @Override
    public void onReceive(Context context, Intent intent)
    {
        checkInternetConenction(context);
    }
}

在Android Menifest文件中添加接收器:

<receiver android:name=".Common" >
            <intent-filter>
                <action android:name="android.net.conn.CONNECTIVITY_CHANGE" >
                </action>
            </intent-filter>
        </receiver>

在您的活动中将布尔值设置为false:

static boolean internet_status = false;

&安培;使用以下方法检查连接:

if(Common.internet_status)
                    {
                        //Do your stuff here
                    }
                    else
                    {
                        Toast.makeText(YourActivity.this, "Internet connection is not available", Toast.LENGTH_LONG).show();
                    }

答案 1 :(得分:1)

只需查看

import android.content.Context;
import android.net.ConnectivityManager;
import android.net.NetworkInfo;
import android.telephony.TelephonyManager;

/**
 * Check device's network connectivity and speed 
 * @author emil http://stackoverflow.com/users/220710/emil
 *
 */
public class Connectivity {

    /**
     * Get the network info
     * @param context
     * @return
     */
    public static NetworkInfo getNetworkInfo(Context context){
        ConnectivityManager cm = (ConnectivityManager) context.getSystemService(Context.CONNECTIVITY_SERVICE);
        return cm.getActiveNetworkInfo();
    }

    /**
     * Check if there is any connectivity
     * @param context
     * @return
     */
    public static boolean isConnected(Context context){
        NetworkInfo info = Connectivity.getNetworkInfo(context);
        return (info != null && info.isConnected());
    }

    /**
     * Check if there is any connectivity to a Wifi network
     * @param context
     * @param type
     * @return
     */
    public static boolean isConnectedWifi(Context context){
        NetworkInfo info = Connectivity.getNetworkInfo(context);
        return (info != null && info.isConnected() && info.getType() == ConnectivityManager.TYPE_WIFI);
    }

    /**
     * Check if there is any connectivity to a mobile network
     * @param context
     * @param type
     * @return
     */
    public static boolean isConnectedMobile(Context context){
        NetworkInfo info = Connectivity.getNetworkInfo(context);
        return (info != null && info.isConnected() && info.getType() == ConnectivityManager.TYPE_MOBILE);
    }

    /**
     * Check if there is fast connectivity
     * @param context
     * @return
     */
    public static boolean isConnectedFast(Context context){
        NetworkInfo info = Connectivity.getNetworkInfo(context);
        return (info != null && info.isConnected() && Connectivity.isConnectionFast(info.getType(),info.getSubtype()));
    }

    /**
     * Check if the connection is fast
     * @param type
     * @param subType
     * @return
     */
    public static boolean isConnectionFast(int type, int subType){
        if(type==ConnectivityManager.TYPE_WIFI){
            return true;
        }else if(type==ConnectivityManager.TYPE_MOBILE){
            switch(subType){
            case TelephonyManager.NETWORK_TYPE_1xRTT:
                return false; // ~ 50-100 kbps
            case TelephonyManager.NETWORK_TYPE_CDMA:
                return false; // ~ 14-64 kbps
            case TelephonyManager.NETWORK_TYPE_EDGE:
                return false; // ~ 50-100 kbps
            case TelephonyManager.NETWORK_TYPE_EVDO_0:
                return true; // ~ 400-1000 kbps
            case TelephonyManager.NETWORK_TYPE_EVDO_A:
                return true; // ~ 600-1400 kbps
            case TelephonyManager.NETWORK_TYPE_GPRS:
                return false; // ~ 100 kbps
            case TelephonyManager.NETWORK_TYPE_HSDPA:
                return true; // ~ 2-14 Mbps
            case TelephonyManager.NETWORK_TYPE_HSPA:
                return true; // ~ 700-1700 kbps
            case TelephonyManager.NETWORK_TYPE_HSUPA:
                return true; // ~ 1-23 Mbps
            case TelephonyManager.NETWORK_TYPE_UMTS:
                return true; // ~ 400-7000 kbps
            /*
             * Above API level 7, make sure to set android:targetSdkVersion 
             * to appropriate level to use these
             */
            case TelephonyManager.NETWORK_TYPE_EHRPD: // API level 11 
                return true; // ~ 1-2 Mbps
            case TelephonyManager.NETWORK_TYPE_EVDO_B: // API level 9
                return true; // ~ 5 Mbps
            case TelephonyManager.NETWORK_TYPE_HSPAP: // API level 13
                return true; // ~ 10-20 Mbps
            case TelephonyManager.NETWORK_TYPE_IDEN: // API level 8
                return false; // ~25 kbps 
            case TelephonyManager.NETWORK_TYPE_LTE: // API level 11
                return true; // ~ 10+ Mbps
            // Unknown
            case TelephonyManager.NETWORK_TYPE_UNKNOWN:
            default:
                return false;
            }
        }else{
            return false;
        }
    }

}

答案 2 :(得分:0)

试试这段代码

protected boolean isOnline() {  
 ConnectivityManager connectivityManager 
          = (ConnectivityManager) getSystemService(Context.CONNECTIVITY_SERVICE);
    NetworkInfo activeNetworkInfo = connectivityManager.getActiveNetworkInfo();
    return activeNetworkInfo != null && activeNetworkInfo.isConnected();
}

答案 3 :(得分:0)

您可以查看以下内容:

protected boolean isOnline() {

ConnectivityManager connMgr = (ConnectivityManager)
        getSystemService(Context.CONNECTIVITY_SERVICE);
NetworkInfo networkInfo = connMgr.getActiveNetworkInfo();
return (networkInfo != null && networkInfo.isConnected()); 

}

https://developer.android.com/training/basics/network-ops/managing.html