본문 바로가기

안드로이드

안드로이드 스튜디오 인터넷 연결 모니터하는 법.

728x90

MainActivity 

private lateinit var internetManager : ConnectivityManager
//네트워크 콜백 객체를 만듬 
private val networkCallBack = object : ConnectivityManager.NetworkCallback() {
    override fun onAvailable(network: Network) {
    //연결 되었을 때 
        initLayout()
    }
    override fun onLost(network: Network) {
    //연결이 끊겼을 때 
    }
}

 override fun onViewCreated(view: View, savedInstanceState: Bundle?) {
        super.onViewCreated(view, savedInstanceState)
 
 		//초기화하여 init 해준다. 
        internetManagerInit()
    }
    
         fun internetManagerInit(){

        internetManager =  (requireContext().getSystemService(Context.CONNECTIVITY_SERVICE) as ConnectivityManager)
        val builder = NetworkRequest.Builder()
        internetManager.registerNetworkCallback(builder.build(),networkCallBack)
    }
    
    	//onDestroy 에서는 다시 unRegister하여서 콜백을 풀어준다. 
        override fun onDestroy() {
        super.onDestroy()
        internetManager =(requireContext().getSystemService(Context.CONNECTIVITY_SERVICE) as ConnectivityManager)
        internetManager.unregisterNetworkCallback(networkCallBack)
    }