简体   繁体   English

使用 Java 在 Android 中检测设备是否连接到 Internet 的好方法

[英]Good way for detecting if a device is connected to the internet in Android using Java

I am trying to make a function that detects if an user is connected to the internet so that I can request a new interstitial ad in case this function returns true.我正在尝试制作一个 function 来检测用户是否已连接到互联网,以便在此 function 返回 true 时请求新的插页式广告。 This is the function I made, but now it is deprecated because it is using deprecated API.这是我制作的 function,但现在已弃用,因为它使用了弃用的 API。 Actually this function only detects if the user is connected to a network.实际上这个 function 只检测用户是否连接到网络。 So I don´t know which option would be better for the new function I want to make as this one is deprecated, to detect if the user is connected to a network as I made or to check if the user is actually connected to the internet if the use of this function will be to request an interstitial ad if it returns true as I have said.所以我不知道哪个选项更适合我想要制作的新 function,因为这个选项已被弃用,以检测用户是否像我所做的那样连接到网络或检查用户是否实际连接到互联网如果使用此 function 将请求插页式广告,如果它返回 true,如我所说。

This is the function I made, but now it needs to be changed because it is using deprecated API...这是我制作的 function,但现在需要更改,因为它使用的是已弃用的 API...

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



public class ConnectionDetector {

    private Context _context;

    public ConnectionDetector(Context context) {
        this._context = context;
    }

    public boolean isConnectingToInternet() {
        ConnectivityManager connectivity = (ConnectivityManager) _context.getSystemService(Context.CONNECTIVITY_SERVICE);
        if (connectivity != null) {
            //noinspection deprecation
            NetworkInfo[] info = connectivity.getAllNetworkInfo();
            for (NetworkInfo anInfo : info)
                if (anInfo.getState() == NetworkInfo.State.CONNECTED) {
                    return true;
                }

        }
        return false;
    }

}
    private void CallNewInertial() {
        ConnectionDetector cd = new ConnectionDetector(Activityone.this);
        if (cd.isConnectingToInternet()) {
            requestNewInterstitial();
        }
    }

I have searched for information but I have only found current awnsers but they were fot Kotlin, not Java...我搜索了信息,但只找到了当前的遮阳篷,但它们是 Kotlin,而不是 Java...

You could for instance ping an external address that is always reachable, such as IP 8.8.8.8 (Google).例如,您可以 ping 始终可访问的外部地址,例如 IP 8.8.8.8 (Google)。 See here how you do it. 在这里看看你是怎么做的。

But normally you can just skip it, as interstitial ads are loaded in the background and won't throw an exception if there is no connection, at least for Admob and most major ad networks.但通常你可以跳过它,因为插页式广告在后台加载,如果没有连接不会抛出异常,至少对于 Admob 和大多数主要广告网络。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM