TelephonyManager: Callback function for SIM Operator Name change

19 views Asked by At

I'm developing an APP for mobile network testing. The Home page of the APP shows the mobile network the SIM is registered to. I need to keep this info updated, how can I do?

This is the current working code:

package com.giorgio.roamingqosapp.ui.home

import android.app.Activity
import android.os.Bundle
import android.telephony.TelephonyManager
import android.view.LayoutInflater
import android.view.View
import android.view.ViewGroup
import android.widget.ImageView
import android.widget.TextView
import androidx.appcompat.content.res.AppCompatResources
import androidx.core.content.ContextCompat.getSystemService
import androidx.fragment.app.Fragment
import androidx.lifecycle.ViewModelProvider
import com.giorgio.roamingqosapp.R
import com.giorgio.roamingqosapp.databinding.FragmentHomeBinding

class HomeFragment : Fragment() {

    private var _binding: FragmentHomeBinding? = null

    // This property is only valid between onCreateView and
    // onDestroyView.
    private val binding get() = _binding!!

    override fun onCreateView(
        inflater: LayoutInflater,
        container: ViewGroup?,
        savedInstanceState: Bundle?
    ): View {
        val homeViewModel =
            ViewModelProvider(this).get(HomeViewModel::class.java)
        var text = ""

        _binding = FragmentHomeBinding.inflate(inflater, container, false)
        val root: View = binding.root

        val textView: TextView = binding.textHome
        homeViewModel.text.observe(viewLifecycleOwner) {
            textView.text = it
        }

        val tm = requireActivity().getSystemService(Activity.TELEPHONY_SERVICE) as TelephonyManager
        val SIMOperatorName = tm.simOperatorName
        val isRoaming = tm.isNetworkRoaming

        if (SIMOperatorName != null) {
            text = getString(R.string.registered_operator, SIMOperatorName)
            binding.registeredOperator.text = text
        }
        text = when (isRoaming) {
            true -> getString(R.string.roaming, "Roaming")
            false -> getString(R.string.roaming, "Home")
        }
        binding.roaming.text = text

        val imageView: ImageView = binding.registeredImageView
        imageView.setImageDrawable(AppCompatResources.getDrawable(requireContext(),R.drawable.led_verde))
        return root
    }

    override fun onDestroyView() {
        super.onDestroyView()
        _binding = null
    }
}

My goal is to keep binding.registeredOperator.text updated if the name of the operator changes

0

There are 0 answers