Search code examples
androidbroadcastreceiverandroid-snackbar

Show SnackBar in current Activity


I have many activities, and I have broadCastReceiver that I registered in manifest for check Connectivity. I would like show Snackbar in current activity when I lost internet connection I registered my receiver in manifest:

<receiver android:name="com.itmind.spac.spacapp.services.ConnectivityChangeReceiver">
        <intent-filter>
            <action android:name="android.net.conn.CONNECTIVITY_CHANGE"/>
        </intent-filter>
    </receiver>

And in BroadCast class:

public class ConnectivityChangeReceiver extends BroadcastReceiver {
   @Override
   public void onReceive(final Context context, final Intent intent) {
      ConnectivityManager cm =(ConnectivityManager) context.getSystemService(Context.CONNECTIVITY_SERVICE);
      if (cm.getActiveNetworkInfo()!=null){
         Toast.makeText(context, "Connected to Internet", Toast.LENGTH_LONG).show();
       }
       else{
       /** I WOULD CREATE A SNACKBAR FOR ALL ACTIVITIES, OR FOR MY CURRENT ACTIVITY */
        Toast.makeText(context, "No Connected to Internet", Toast.LENGTH_LONG).show();

       }

   }
}

Solution

  • If you are going to respond to a broadcast only when one of your activities is active, you should register and unregister the broadcast receiver in your activities, and the register / unregister calls should appear in matching life cycle events of the activity like onCreate() / onDestroy() or onStart() / onStop().

    An easy way to do it for an application with multiple activities is by letting each activity extend a base class that manages the receiver, for example this outline:

    public class MyActivity extends AppCompatActivity {
      void onCreate(...) {
        // register the receiver here...
      }
    
      void onDestroy() {
        // unregister the receiver here...
      }
    }
    

    You should also make your connectivity receiver an inner class of this activity, and remove the receiver declaration from the manifest file, because you are registering it dynamically now.