Страницы

Поиск по вопросам

вторник, 10 декабря 2019 г.

Проверить подключение к интернету

#android


Как при запуске Activity проверять подключение к интернету и если подключение отсутствует,
то выводить сообщение? 
    


Ответы

Ответ 1



import android.annotation.TargetApi import android.arch.lifecycle.LiveData import android.content.BroadcastReceiver import android.content.Context import android.content.Context.CONNECTIVITY_SERVICE import android.content.Intent import android.content.IntentFilter import android.net.ConnectivityManager import android.net.Network import android.net.NetworkInfo import android.net.NetworkRequest import android.os.Build import android.support.annotation.RequiresApi class ConnectionLiveData(val context: Context) : LiveData() { private var connectivityManager: ConnectivityManager = context.getSystemService(CONNECTIVITY_SERVICE) as ConnectivityManager private lateinit var connectivityManagerCallback: ConnectivityManager.NetworkCallback override fun onActive() { super.onActive() updateConnection() when { Build.VERSION.SDK_INT >= Build.VERSION_CODES.N -> { connectivityManager.registerDefaultNetworkCallback(getConnectivityManagerCallback()) } Build.VERSION.SDK_INT >= Build.VERSION_CODES.LOLLIPOP -> { lollipopNetworkAvailableRequest() } else -> { if (Build.VERSION.SDK_INT < Build.VERSION_CODES.LOLLIPOP) { context.registerReceiver( networkReceiver, IntentFilter("android.net.conn.CONNECTIVITY_CHANGE") ) } } } } override fun onInactive() { super.onInactive() if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.LOLLIPOP) { connectivityManager.unregisterNetworkCallback(connectivityManagerCallback) } else { context.unregisterReceiver(networkReceiver) } } @TargetApi(Build.VERSION_CODES.LOLLIPOP) private fun lollipopNetworkAvailableRequest() { val builder = NetworkRequest.Builder() .addTransportType(android.net.NetworkCapabilities.TRANSPORT_CELLULAR) .addTransportType(android.net.NetworkCapabilities.TRANSPORT_WIFI) connectivityManager.registerNetworkCallback(builder.build(), getConnectivityManagerCallback()) } private fun getConnectivityManagerCallback(): ConnectivityManager.NetworkCallback { if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.LOLLIPOP) { connectivityManagerCallback = object : ConnectivityManager.NetworkCallback() { override fun onAvailable(network: Network?) { postValue(true) } override fun onLost(network: Network?) { postValue(false) } } return connectivityManagerCallback } else { throw IllegalAccessError("Should not happened") } } private val networkReceiver = object : BroadcastReceiver() { override fun onReceive(context: Context, intent: Intent) { updateConnection() } } private fun updateConnection() { val activeNetwork: NetworkInfo? = connectivityManager.activeNetworkInfo postValue(activeNetwork?.isConnected == true) } } Вызов: public override fun onCreate(savedInstanceState: Bundle?) { super.onCreate(savedInstanceState) setContentView(R.layout.activity_main) val connectionLiveData = ConnectionLiveData(this) connectionLiveData.observe(this, Observer { isConnected -> isConnected?.let { //что-то } }) } Deprecated import android.content.BroadcastReceiver; import android.content.Context; import android.content.Intent; import android.net.ConnectivityManager; import android.net.NetworkInfo; public class ConnectivityReceiver extends BroadcastReceiver { public static ConnectivityReceiverListener connectivityReceiverListener; public ConnectivityReceiver() { super(); } @Override public void onReceive(Context context, Intent arg1) { NetworkInfo activeNetwork = ((ConnectivityManager) context.getSystemService(Context.CONNECTIVITY_SERVICE)).getActiveNetworkInfo(); boolean isConnected = activeNetwork != null && activeNetwork.isConnectedOrConnecting(); if (connectivityReceiverListener != null) connectivityReceiverListener.onNetworkConnectionChanged(isConnected); } public static boolean isConnected() { NetworkInfo activeNetwork = ((ConnectivityManager) MyApplication.getInstance().getApplicationContext().getSystemService(Context.CONNECTIVITY_SERVICE)).getActiveNetworkInfo(); return activeNetwork != null && activeNetwork.isConnectedOrConnecting(); } public interface ConnectivityReceiverListener { void onNetworkConnectionChanged(boolean isConnected); } } 2. import android.app.Application; public class MyApplication extends Application { private static MyApplication mInstance; @Override public void onCreate() { super.onCreate(); mInstance = this; } public static synchronized MyApplication getInstance() { return mInstance; } public void setConnectivityListener(ConnectivityReceiver.ConnectivityReceiverListener listener) { ConnectivityReceiver.connectivityReceiverListener = listener; } } 3. ... 4. private void checkConnection() { boolean isConnected = ConnectivityReceiver.isConnected(); showSnack(isConnected); } private void showSnack(boolean isConnected) { String message; if (isConnected) message = "Good! Connected to Internet"; else message = "Sorry! Not connected to internet"; Snackbar snackbar = Snackbar.make(findViewById(R.id.fab), message, Snackbar.LENGTH_LONG).show(); } @Override protected void onResume() { super.onResume(); MyApplication.getInstance().setConnectivityListener(this); } @Override public void onNetworkConnectionChanged(boolean isConnected) { showSnack(isConnected); }

Комментариев нет:

Отправить комментарий