如何在android应用程序运行时在后台连续检查互联网连接

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/21254555/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-20 04:13:48  来源:igfitidea点击:

How to check internet connectivity continuously in background while android application running

android

提问by Manish

I want to check internet connectivity continuously in background while my android application running. I mean from starting of the application to the end of the application. How can i do it? What should be the approach?

我想在我的 android 应用程序运行时在后台连续检查互联网连接。我的意思是从申请开始到申请结束。我该怎么做?应该采取什么方法?

回答by vasurb

I know I am late to answer this Question. But here is a way to monitor the Network Connection Continuously in an Activity/Fragment.

我知道我回答这个问题迟到了。但这里有一种在活动/片段中连续监视网络连接的方法。

We will use Network Callback to monitor our connection in an Activity/Fragment

我们将使用网络回调来监视活动/片段中的连接

first, declare two variable in class

首先,在类中声明两个变量

// to check if we are connected to Network
boolean isConnected = true;

// to check if we are monitoring Network
private boolean monitoringConnectivity = false;

Next, We will write the Network Callback Method

接下来,我们将编写网络回调方法

private ConnectivityManager.NetworkCallback connectivityCallback
            = new ConnectivityManager.NetworkCallback() {
        @Override
        public void onAvailable(Network network) {
            isConnected = true;
            LogUtility.LOGD(TAG, "INTERNET CONNECTED");
        }

        @Override
        public void onLost(Network network) {
            isConnected = false;
            LogUtility.LOGD(TAG, "INTERNET LOST");
        }
    };

Now Since we have written our Callback we will Now write a method which will monitor our Network Connection, and in this method, we will register our NetworkCallback.

现在既然我们已经编写了我们的回调,我们现在将编写一个方法来监控我们的网络连接,在这个方法中,我们将注册我们的 NetworkCallback。

// Method to check network connectivity in Main Activity
    private void checkConnectivity() {
        // here we are getting the connectivity service from connectivity manager
        final ConnectivityManager connectivityManager = (ConnectivityManager) getSystemService(
                Context.CONNECTIVITY_SERVICE);

        // Getting network Info
        // give Network Access Permission in Manifest
        final NetworkInfo activeNetworkInfo = connectivityManager.getActiveNetworkInfo();

        // isConnected is a boolean variable
        // here we check if network is connected or is getting connected
        isConnected = activeNetworkInfo != null && activeNetworkInfo.isConnectedOrConnecting();

        if (!isConnected) {
            // SHOW ANY ACTION YOU WANT TO SHOW
            // WHEN WE ARE NOT CONNECTED TO INTERNET/NETWORK
            LogUtility.LOGD(TAG, " NO NETWORK!");
// if Network is not connected we will register a network callback to  monitor network
            connectivityManager.registerNetworkCallback(
                    new NetworkRequest.Builder()
                            .addCapability(NetworkCapabilities.NET_CAPABILITY_INTERNET)
                            .build(), connectivityCallback);
            monitoringConnectivity = true;
        }

    }

All our work is almost finished we just need to call our checkConnectivity(), the method in onResume() of our Activity/Fragment

我们所有的工作都快完成了,我们只需要调用我们的 Activity/Fragment 的 onResume() 中的方法 checkConnectivity()

  @Override
    protected void onResume() {
        super.onResume();
        checkConnectivity();
    }

*unRegister the NetworkCallback in onPause() ,method of your Activity/Fragment *

*在 onPause() 中取消注册 NetworkCallback,您的活动/片段的方法 *

   @Override
    protected void onPause() {
        // if network is being moniterd then we will unregister the network callback
        if (monitoringConnectivity) {
            final ConnectivityManager connectivityManager
                    = (ConnectivityManager) getSystemService(Context.CONNECTIVITY_SERVICE);
            connectivityManager.unregisterNetworkCallback(connectivityCallback);
            monitoringConnectivity = false;
        }
        super.onPause();
    }

That's it, just add this code in which every class of your Activity/Fragment were you need to monitor the Network!.And don't forget to unregister it!!!

就是这样,只需添加此代码,其中您需要监视网络的活动/片段的每个类!。不要忘记取消注册!!!

回答by Ajay Venugopal

Create class that extends BroadcastReceiver , use ConnectivityManager.EXTRA_NO_CONNECTIVITY to get connection info.

创建扩展 BroadcastReceiver 的类,使用 ConnectivityManager.EXTRA_NO_CONNECTIVITY 获取连接信息。

import android.content.BroadcastReceiver;
import android.content.Context;
import android.content.Intent;
import android.net.ConnectivityManager;
import android.widget.Toast;

public class CheckConnectivity extends BroadcastReceiver{

@Override
public void onReceive(Context context, Intent arg1) {

    boolean isConnected = arg1.getBooleanExtra(ConnectivityManager.EXTRA_NO_CONNECTIVITY, false);
    if(isConnected){
        Toast.makeText(context, "Internet Connection Lost", Toast.LENGTH_LONG).show();
    }
    else{
        Toast.makeText(context, "Internet Connected", Toast.LENGTH_LONG).show();
    }
   }
 }

Add this permission in mainfest too

在 mainfest 中也添加此权限

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

回答by Oscar J. Irun

You can also try this service Class. Just set the time interval in seconds and the url to ping:

你也可以试试这个服务类。只需将时间间隔(以秒为单位)和 url 设置为 ping:

Android Check Internet Connection

Android 检查互联网连接

Just remember to add the service to the Manifest file, and add the permissions

记得把服务添加到Manifest文件中,并添加权限

回答by lucian.pantelimon

The Android system already does that for you. Instead of constantly polling the phone for the network state, register BroadcastReceivers for WiFi and network state changes and process the Intents sent by the system when the WiFi or network state changes.

Android 系统已经为您做到了。不是不断轮询手机网络状态,而是BroadcastReceiver为WiFi和网络状态变化注册s,并Intent在WiFi或网络状态变化时处理系统发送的s。

Have a look at this questionfor more information on this.

查看此问题以获取有关此问题的更多信息。

Once you register your BroadcastReceiver, the network state change listening will happen in the background (in the OS) and an Intentwill be sent to your receivers on the UI thread (most likely) when the network state changes. If you want to receive the Intents on a background thread, check this questionfor more info.

一旦您注册了BroadcastReceiver,网络状态更改侦听将在后台(在操作系统中)发生,并且Intent当网络状态更改时,将在 UI 线程上(最有可能)发送到您的接收器。如果您想Intent在后台线程上接收s,请查看此问题以获取更多信息。