Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
3.4k views
in Technique[技术] by (71.8m points)

java - I would like the internet mandatory in my android' app

I'm looking to impose INTERNET in my android apps that I develop on Android Studio ! it is possible today to play to my app without internet connection and this is a problem for me (about AdMob for sure)! So I would like the internet to be mandatory ! Anyone know the solution ?

thanks a lot... (and sorry for my english i'm french)


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

You are able to check the current state of your internet access using the Connectivity Service. Using that service, you can have a callback that will alert you when your internet access situation changes, here's a little example (in Kotlin):

val connectivityManager =
        getApplication<Application>().getSystemService(Context.CONNECTIVITY_SERVICE) as ConnectivityManager

    val networkCallback = object : ConnectivityManager.NetworkCallback() {
        override fun onAvailable(network: Network) {
            super.onAvailable(network)
            // Do something
        }

        override fun onLost(network: Network) {
            super.onLost(network)
            // Do something else
        }
    }

    connectivityManager.registerNetworkCallback(
        NetworkRequest.Builder().build(),
        networkCallback
    )

At the same time, you can also check for wifi using the Wifi Service and data using the Telephony Service. Here's an example where I check both to determine internet situation, though you are free to check for either individually if you see fit:

val wifiManager =
        getApplication<Application>().applicationContext.getSystemService(Context.WIFI_SERVICE) as WifiManager
    val simManager =
        getApplication<Application>().applicationContext.getSystemService(Context.TELEPHONY_SERVICE) as TelephonyManager
    if (wifiManager.connectionInfo.supplicantState != SupplicantState.COMPLETED && simManager.dataState != TelephonyManager.DATA_CONNECTED) {
        // Do something
    }

Keep in mind you will need to enable these permissions in the Android Manifest:

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

Using these services you can selectively disable the app or certain functionalities if the user has no internet.


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

1.4m articles

1.4m replys

5 comments

57.0k users

...