Implement Broadcast receiver inside a Service

后端 未结 3 614
无人及你
无人及你 2020-12-18 01:33

I want to check Internet connection throughout the run time of my Android application. I tried using services but seems like it is not the best option. Is there any possible

3条回答
  •  盖世英雄少女心
    2020-12-18 02:03

    You need not to use Service or BroadCastReceiver for this purpose. Just check Connection status everyTime you need to ping the server.

    you can write a method which checks this and returns a boolean(true/false) according to connection status. Below method does the same.

    public static boolean isNetworkAvailable(Context mContext) {
    
            try {
                final ConnectivityManager conn_manager = (ConnectivityManager) mContext
                        .getSystemService(Context.CONNECTIVITY_SERVICE);
                final NetworkInfo network_info = conn_manager
                        .getActiveNetworkInfo();
    
                if (network_info != null && network_info.isConnected()) {
                    if (network_info.getType() == ConnectivityManager.TYPE_WIFI)
                        return true;
                    else if (network_info.getType() == ConnectivityManager.TYPE_MOBILE)
                        return true;
                }
    
            } catch (Exception e) {
                // TODO: handle exception
            }
            return false;
    
        }
    

提交回复
热议问题