0

I am making a sample app, only to see, how to monitor the network connectivity on Android.

For that I follow this document: https://developer.android.com/training/monitoring-device-state/connectivity-status-type

Since I am not getting the results I expected, I decided to create this post hoping to get some relevant feedback from experienced users.

My source code, hereafter, is limited to one file: MainActivity.kt.

package me.soft.network

import android.net.ConnectivityManager
import android.net.Network
import android.net.NetworkCapabilities
import android.net.NetworkRequest
import androidx.appcompat.app.AppCompatActivity
import android.os.Bundle

class MainActivity : AppCompatActivity() {
    lateinit var networkRequest: NetworkRequest
    private val networkCallback = object : ConnectivityManager.NetworkCallback() {
        // network is available for use
        override fun onAvailable(network: Network) {
            super.onAvailable(network)
            println("onAvailable --- CALLED")
        }

        // Network capabilities have changed for the network
        override fun onCapabilitiesChanged(
            network: Network,
            networkCapabilities: NetworkCapabilities
        ) {
            super.onCapabilitiesChanged(network, networkCapabilities)
            val unmetered = networkCapabilities.hasCapability(NetworkCapabilities.  NET_CAPABILITY_NOT_METERED)
            println("onCapabilitiesChanged --- CALLED")
        }

        // lost network connection
        override fun onLost(network: Network) {
            super.onLost(network)
            println("onLost --- CALLED")
        }
    }


    override fun onCreate(savedInstanceState: Bundle?) {
        super.onCreate(savedInstanceState)
        setContentView(R.layout.activity_main)

        networkRequest = NetworkRequest.Builder()
            .addCapability(NetworkCapabilities.NET_CAPABILITY_INTERNET)
            .addTransportType(NetworkCapabilities.TRANSPORT_WIFI)
            .addTransportType(NetworkCapabilities.TRANSPORT_CELLULAR)
            .build()

        val connectivityManager = getSystemService(ConnectivityManager::class.java) as  ConnectivityManager
        connectivityManager.requestNetwork(networkRequest, networkCallback)
    }
}

As one can notice, it is mainly comming straight from the document I mentioned above. After launching the app I expect to see it running and react to whatever happens to the state of the device connectivity by means of calls to the funtions: onAvailable, onCapabilitiesChanged, onLost of the networkCallback ConnectivityManager.NetworkCallback object. But things do not quite happen this way, instead the app behaves as expected when started with the device connected:

I see in the console "onAvailable --- CALLED" and "onCapabilitiesChanged --- CALLED" and then if I go to disable the device connection I see in the console "onLost --- CALLED". This seems OK. But without the device connected, things don't work, meaning: I don't see any "xxx --- CALLED" type of message even if I enable the connection later.

One more piece of information, here is the AndroidManifest.xml file:

<?xml version="1.0" encoding="utf-8"?>
<manifest xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:tools="http://schemas.android.com/tools"
    package="me.soft.network">

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

    <application
        android:allowBackup="true"
        android:dataExtractionRules="@xml/data_extraction_rules"
        android:fullBackupContent="@xml/backup_rules"
        android:icon="@mipmap/ic_launcher"
        android:label="@string/app_name"
        android:roundIcon="@mipmap/ic_launcher_round"
        android:supportsRtl="true"
        android:theme="@style/Theme.NetWork"
        tools:targetApi="31">
        <activity
            android:name=".MainActivity"
            android:exported="true">
            <intent-filter>
                <action android:name="android.intent.action.MAIN" />

                <category android:name="android.intent.category.LAUNCHER" />
            </intent-filter>
        </activity>
    </application>

</manifest>

What am I doing wrong ?

Michel
  • 10,303
  • 17
  • 82
  • 179
  • You're going to need to check `adb logcat` and see what error your app is throwing. Most likely, it is a permission issue in which case, @beant-singh answer may help. – Always Learning Jul 06 '22 at 18:58
  • I have installed adb (which I did not know before). I must say it does not look very usable (probably because I don't know how to use it). It produces zillions of lines of messages. Nothing in the few I can see seems relevant. – Michel Jul 07 '22 at 03:44

1 Answers1

1

First of all, go to your manifest file and add below Permission

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

also go To MainActivity tag and check

android:exported="true" 

is true or not, if not set it true.

Beant Singh
  • 169
  • 4
  • I did that and that makes the app keep running (at least for a while) instead of stopping as before. The android:exported was already "true". So this is some clear improvement, but only half way: I see in the console "onAvailable --- CALLED" and "onCapabilitiesChanged --- CALLED" when the app starts and then if I go to disable the device connection I see in the console "onLost --- CALLED". Things are OK up to this point. But if reenable the connection I do not see anything (which is unexpected). – Michel Jul 07 '22 at 03:30
  • And also the app suddenly stops after some time. If I start the app with no connectivity, and change the connectivity later while the app is running, it doesn't work (I do not see anything in the console) . As you can see there are still some issues. – Michel Jul 07 '22 at 03:30
  • I edited the question to include the AndroidManifest.xml file. One can see some added permissions. – Michel Jul 07 '22 at 06:17
  • But without the device connected, things don't work. is it using internet or wire? – Beant Singh Jul 07 '22 at 07:29
  • It is using internet (WIFI). But I mean, if the device is not connected it should tell me that there is no connectivity and it should also tell me when the connection becomes available again (which it does tell me at all). – Michel Jul 07 '22 at 10:49