Страницы

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

понедельник, 15 октября 2018 г.

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

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


Ответ

Актуальная проверка на сегодняшний день:
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.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
override fun onActive() { super.onActive()
updateConnection()
when { Build.VERSION.SDK_INT >= Build.VERSION_CODES.N -> { connectivityManager.registerDefaultNetworkCallback(networkCallback) } 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")) //android.net.ConnectivityManager.CONNECTIVITY_ACTION } } } }
override fun onInactive() { super.onInactive() if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.LOLLIPOP) { connectivityManager.unregisterNetworkCallback(networkCallback) } 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(), networkCallback) }
private val networkCallback = @RequiresApi(Build.VERSION_CODES.LOLLIPOP) object : ConnectivityManager.NetworkCallback() { override fun onAvailable(network: Network?) { postValue(true) }
override fun onLost(network: Network?) { postValue(false) } }
private val networkReceiver = object : BroadcastReceiver() { override fun onReceive(context: Context, intent: Intent) { updateConnection() } }
private fun updateConnection() { val activeNetwork: NetworkInfo? = connectivityManager.activeNetworkInfo postValue(activeNetwork?.isConnected) } }
Вызов:
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); }

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

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