“Android mendengarkan perubahan jaringan” Kode Jawaban

Android mendengarkan perubahan jaringan

ConnectivityManager.NetworkCallback networkCallback = new ConnectivityManager.NetworkCallback() {
    @Override
    public void onAvailable(Network network) {
        // network available
    }

    @Override
    public void onLost(Network network) {
        // network unavailable
    }
};

ConnectivityManager connectivityManager =
        (ConnectivityManager) context.getSystemService(Context.CONNECTIVITY_SERVICE);

if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.N) {
    connectivityManager.registerDefaultNetworkCallback(networkCallback);
} else {
    NetworkRequest request = new NetworkRequest.Builder()
            .addCapability(NetworkCapabilities.NET_CAPABILITY_INTERNET).build();
    connectivityManager.registerNetworkCallback(request, networkCallback);
}
Serial Koder

Android mendengarkan perubahan jaringan

val connectivityManager = context.getSystemService(Context.CONNECTIVITY_SERVICE) as ConnectivityManager
connectivityManager?.let {
    it.registerDefaultNetworkCallback(object : ConnectivityManager.NetworkCallback() {
        override fun onAvailable(network: Network) {
            //take action when network connection is gained
        }
        override fun onLost(network: Network?) {
            //take action when network connection is lost
        }
    })
}
Serial Koder

Jawaban yang mirip dengan “Android mendengarkan perubahan jaringan”

Pertanyaan yang mirip dengan “Android mendengarkan perubahan jaringan”

Lebih banyak jawaban terkait untuk “Android mendengarkan perubahan jaringan” di Java

Jelajahi jawaban kode populer menurut bahasa

Jelajahi bahasa kode lainnya