Detecting internet connection status in your app is very easy and won’t take more than 5mins. In this article you will learn how to detect internet connection status manually and automatically. Using broadcast receiver, your app will be automatically notified when there is a change in network connection.
This provides easy way do any changes in the app like hiding few button (like WhatsApp hides send, upload icon when there is not internet), navigation user to another screen, or just show a Snackbar message.
Creating New Project
1. Create a new project in Android Studio from File ⇒ New Project. When it prompts you to select the default activity, select Blank Activity and proceed.
2. Create a class named ConnectivityReceiver.java and extend it from BroadcastReceiver. This is a receiver class which will be notified whenever there is change in network / internet connection.
package info.androidhive.checkinternet; 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) { ConnectivityManager cm = (ConnectivityManager) context .getSystemService(Context.CONNECTIVITY_SERVICE); NetworkInfo activeNetwork = cm.getActiveNetworkInfo(); boolean isConnected = activeNetwork != null && activeNetwork.isConnectedOrConnecting(); if (connectivityReceiverListener != null) { connectivityReceiverListener.onNetworkConnectionChanged(isConnected); } } public static boolean isConnected() { ConnectivityManager cm = (ConnectivityManager) MyApplication.getInstance().getApplicationContext() .getSystemService(Context.CONNECTIVITY_SERVICE); NetworkInfo activeNetwork = cm.getActiveNetworkInfo(); return activeNetwork != null && activeNetwork.isConnectedOrConnecting(); } public interface ConnectivityReceiverListener { void onNetworkConnectionChanged(boolean isConnected); } }
3. Create another class named MyApplication.java and extend it from Application. This class will be called whenever app is launched. Here setConnectivityListener() method is used to initiate the connectivity listener.
package info.androidhive.checkinternet; 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; } }
4. Open AndroidManifest.xml and do the below changes.
> Add MyApplication to <application> tag.
> Add ConnectivityReceiver as <receiver>.
> Declare INTERNET and ACCESS_NETWORK_STATE permissions.
<?xml version="1.0" encoding="utf-8"?> <manifest xmlns:android="http://schemas.android.com/apk/res/android" package="info.androidhive.checkinternet"> <uses-permission android:name="android.permission.INTERNET" /> <uses-permission android:name="android.permission.ACCESS_NETWORK_STATE" /> <application android:name=".MyApplication" android:allowBackup="true" android:icon="@mipmap/ic_launcher" android:label="@string/app_name" android:supportsRtl="true" android:theme="@style/AppTheme"> <activity android:name=".MainActivity" android:label="@string/app_name" android:theme="@style/AppTheme.NoActionBar"> <intent-filter> <action android:name="android.intent.action.MAIN" /> <category android:name="android.intent.category.LAUNCHER" /> </intent-filter> </activity> <receiver android:name=".ConnectivityReceiver" android:enabled="true"> <intent-filter> <action android:name="android.net.conn.CONNECTIVITY_CHANGE" /> </intent-filter> </receiver> </application> </manifest>
Broadcasting Internet Status to All Activities
Now we have all the setup ready. Let’s see how to notify an activity when the device is connected or disconnected from internet.
5. Open layout file main activity activity_main.xml add the below layout.
<?xml version="1.0" encoding="utf-8"?> <android.support.design.widget.CoordinatorLayout xmlns:android="http://schemas.android.com/apk/res/android" xmlns:app="http://schemas.android.com/apk/res-auto" xmlns:tools="http://schemas.android.com/tools" android:layout_width="match_parent" android:layout_height="match_parent" android:fitsSystemWindows="true" tools:context="info.androidhive.checkinternet.MainActivity"> <android.support.design.widget.AppBarLayout android:layout_width="match_parent" android:layout_height="wrap_content" android:theme="@style/AppTheme.AppBarOverlay"> <android.support.v7.widget.Toolbar android:id="@+id/toolbar" android:layout_width="match_parent" android:layout_height="?attr/actionBarSize" android:background="?attr/colorPrimary" app:popupTheme="@style/AppTheme.PopupOverlay" /> </android.support.design.widget.AppBarLayout> <LinearLayout android:layout_width="match_parent" android:layout_height="match_parent" android:orientation="vertical" android:padding="@dimen/activity_vertical_margin" app:layout_behavior="@string/appbar_scrolling_view_behavior"> <TextView android:layout_width="match_parent" android:layout_height="wrap_content" android:text="Turn on/off wifi to notify the app about connection status." /> <Button android:id="@+id/btn_check" android:layout_width="wrap_content" android:layout_height="wrap_content" android:layout_marginTop="20dp" android:text="Check Connection" /> </LinearLayout> <android.support.design.widget.FloatingActionButton android:id="@+id/fab" android:layout_width="wrap_content" android:layout_height="wrap_content" android:layout_gravity="bottom|end" android:layout_margin="@dimen/fab_margin" android:src="@drawable/ic_add_white_24dp" /> </android.support.design.widget.CoordinatorLayout>
6. Open your MainActivity.java and do the below changes to receive the internet status.
> Register the connection change listener in onResume() method by calling MyApplication.getInstance().setConnectivityListener(this).
> Implement the activity from ConnectivityReceiver.ConnectivityReceiverListener which will override onNetworkConnectionChanged() method.
> onNetworkConnectionChanged() method will be triggered whenever device is connected / disconnected from internet. You need to take appropriate action here.
Follow the above same three steps in all other activities in which in you want to notify the internet status.
package info.androidhive.checkinternet; import android.content.Intent; import android.graphics.Color; import android.os.Bundle; import android.support.design.widget.FloatingActionButton; import android.support.design.widget.Snackbar; import android.support.v7.app.AppCompatActivity; import android.support.v7.widget.Toolbar; import android.view.View; import android.widget.Button; import android.widget.TextView; public class MainActivity extends AppCompatActivity implements ConnectivityReceiver.ConnectivityReceiverListener { private Button btnCheck; @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_main); Toolbar toolbar = (Toolbar) findViewById(R.id.toolbar); setSupportActionBar(toolbar); btnCheck = (Button) findViewById(R.id.btn_check); // Manually checking internet connection checkConnection(); btnCheck.setOnClickListener(new View.OnClickListener() { @Override public void onClick(View v) { // Manually checking internet connection checkConnection(); } }); } // Method to manually check connection status private void checkConnection() { boolean isConnected = ConnectivityReceiver.isConnected(); showSnack(isConnected); } // Showing the status in Snackbar private void showSnack(boolean isConnected) { String message; int color; if (isConnected) { message = "Good! Connected to Internet"; color = Color.WHITE; } else { message = "Sorry! Not connected to internet"; color = Color.RED; } Snackbar snackbar = Snackbar .make(findViewById(R.id.fab), message, Snackbar.LENGTH_LONG); View sbView = snackbar.getView(); TextView textView = (TextView) sbView.findViewById(android.support.design.R.id.snackbar_text); textView.setTextColor(color); snackbar.show(); } @Override protected void onResume() { super.onResume(); // register connection status listener MyApplication.getInstance().setConnectivityListener(this); } /** * Callback will be triggered when there is change in * network connection */ @Override public void onNetworkConnectionChanged(boolean isConnected) { showSnack(isConnected); } }
Run the project and try turning off / on wifi or mobile data. You can notice a Snackbar is shown with network connection status.
Không có nhận xét nào:
Đăng nhận xét