我想问一些我的应用程序不了解的问题。我从服务器上获取了一些数据,并使用Google的Volley库将其显示在recyclerview中。到目前为止,一切都很好:)。

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

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;
    }
}
}


有任何想法吗?

谢谢,

西奥

最佳答案

创建一个CheckInternet Java类并调用其方法

    public class CheckInternet {

    public static boolean isNetwork(Context context) {

        ConnectivityManager connectivityManager
                = (ConnectivityManager) context.getSystemService(Context.CONNECTIVITY_SERVICE);
        NetworkInfo activeNetworkInfo = connectivityManager.getActiveNetworkInfo();
        return activeNetworkInfo != null && activeNetworkInfo.isConnected();
    }

    public static boolean isConnectedNetwork(Context context) {
        ConnectivityManager cm = (ConnectivityManager) context.getSystemService(Context.CONNECTIVITY_SERVICE);
        return cm.getActiveNetworkInfo() != null && cm.getActiveNetworkInfo().isConnectedOrConnecting();

    }
}


在你的活动中

     if (CheckInternet.isNetwork(Activity.this)) {
         //internet is connected do something
     }else{
        //do something, net is not connected
     }

关于android - 检查是否有互联网连接,我们在Stack Overflow上找到一个类似的问题:https://stackoverflow.com/questions/39762423/

10-12 04:22