How to implement Event Bus in Android

EventBus - Android optimized event bus that simplifies communication between Activities, Fragments.

Create New Project

1. First create a new project in Android Studio (File => New Project)

AndroidManifest.xml

									   
<?xml version="1.0" encoding="utf-8"?>
<manifest xmlns:android="http://schemas.android.com/apk/res/android"
    package="com.narendra.eventbus">

    <uses-permission android:name="android.permission.INTERNET" />
    <uses-permission android:name="android.permission.ACCESS_NETWORK_STATE" />
    <uses-permission android:name="android.permission.CHANGE_WIFI_STATE" />
    <uses-permission android:name="android.permission.ACCESS_WIFI_STATE" />

    <application
        android:allowBackup="true"
        android:icon="@mipmap/ic_launcher"
        android:label="@string/app_name"
        android:supportsRtl="true"
        android:theme="@style/AppTheme">
        <activity android:name=".MainActivity">
            <intent-filter>
                <action android:name="android.intent.action.MAIN" />
                <category android:name="android.intent.category.LAUNCHER" />
            </intent-filter>
        </activity>

        <receiver
            android:name=".NetworkChangeReceiver"
            android:label="NetworkChangeReceiver">
            <intent-filter>
                <action android:name="android.net.conn.CONNECTIVITY_CHANGE" />
                <action android:name="android.net.wifi.WIFI_STATE_CHANGED" />
            </intent-filter>
        </receiver>

    </application>

</manifest>

activity_main.xml

									   
<?xml version="1.0" encoding="utf-8"?>
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:tools="http://schemas.android.com/tools"
    android:id="@+id/activity_main"
    android:layout_width="match_parent"
    android:layout_height="match_parent">

    <include layout="@layout/netlayout" />

    <RelativeLayout
        android:id="@+id/mainlayout"
        android:layout_width="match_parent"
        android:layout_height="match_parent">

        <TextView
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"
            android:layout_centerInParent="true"
            android:text="Welcome"
            android:textAppearance="?android:attr/textAppearanceLarge" />

        <Button
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"
            android:id="@+id/check"
            android:layout_alignParentBottom="true"
            android:layout_centerHorizontal="true"
            android:text="Check again internet connection" />

    </RelativeLayout>
</RelativeLayout>

netlayout.xml


<?xml version="1.0" encoding="utf-8"?>
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
    android:id="@+id/neterror"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    android:background="#fff"
    android:orientation="vertical">

    <ImageView
        android:id="@+id/netimg"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:layout_gravity="center"
        android:layout_marginTop="30dp"
        android:src="@drawable/nointernet" />

    <TextView
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:layout_alignParentEnd="true"
        android:layout_below="@+id/netimg"
        android:layout_gravity="center"
        android:layout_marginEnd="121dp"
        android:text="Waiting for Net"
        android:textAppearance="?android:attr/textAppearanceMedium"
        android:textColor="#f43260" />

    <TextView
        android:id="@+id/retry"
        android:layout_width="match_parent"
        android:layout_height="30dp"
        android:layout_alignParentBottom="true"
        android:background="#f53464"
        android:gravity="center"
        android:text="If Network is connect automatically redirect" />

    <ProgressBar
        android:id="@+id/netpro"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:layout_above="@+id/retry"
        android:layout_centerHorizontal="true"
        android:layout_marginBottom="60dp" />

</RelativeLayout>
	

Network.java

									   
package com.narendra.eventbus;

import android.content.Context;
import android.net.ConnectivityManager;
import android.net.NetworkInfo;

public class Network {

    public static String activityname;
    private static boolean isConnected = false;

    public static boolean isConnectingToInternet(Context _context) {
        ConnectivityManager connectivity = (ConnectivityManager) _context.getSystemService(Context.CONNECTIVITY_SERVICE);
        if (connectivity != null) {
            NetworkInfo[] info = connectivity.getAllNetworkInfo();
            if (info != null)
                for (int i = 0; i < info.length; i++)
                    if (info[i].getState() == NetworkInfo.State.CONNECTED) {
                        return true;
                    }
        }
        return false;
    }
}

NetworkChangeReceiver.java


package com.narendra.eventbus;

import android.content.BroadcastReceiver;
import android.content.Context;
import android.content.Intent;
import android.net.ConnectivityManager;
import android.net.NetworkInfo;
import android.util.Log;
import android.widget.Toast;

import org.greenrobot.eventbus.EventBus;

public class NetworkChangeReceiver extends BroadcastReceiver {
    static EventBus bus = EventBus.getDefault();
    @Override
    public void onReceive(final Context context, final Intent intent) {

        String status = NetworkUtil.getConnectivityStatusString(context);
        Toast.makeText(context, status, Toast.LENGTH_SHORT).show();
        if(status != null) {
            if (status.equals("Not connected to Internet")){
            }
            else {
                Toast.makeText(context, "connected", Toast.LENGTH_SHORT).show();
                try {
                    bus.post(Network.activityname);
                    Log.w("-------","connect ");
                } catch (Exception e) {
                    e.printStackTrace();
                }
            }
        }
    }
}

class NetworkUtil {

    public static int TYPE_WIFI = 1;
    public static int TYPE_MOBILE = 2;
    public static int TYPE_NOT_CONNECTED = 0;
    public static int getConnectivityStatus(Context context) {
        ConnectivityManager cm = (ConnectivityManager) context
                .getSystemService(Context.CONNECTIVITY_SERVICE);

        NetworkInfo activeNetwork = cm.getActiveNetworkInfo();
        if (null != activeNetwork) {
            if(activeNetwork.getType() == ConnectivityManager.TYPE_WIFI)
                return TYPE_WIFI;

            if(activeNetwork.getType() == ConnectivityManager.TYPE_MOBILE)
                return TYPE_MOBILE;
        }
        return TYPE_NOT_CONNECTED;
    }

    public static String getConnectivityStatusString(Context context) {
        int conn = NetworkUtil.getConnectivityStatus(context);
        String status = null;
        if (conn == NetworkUtil.TYPE_WIFI) {
            status = "Wifi enabled";
        } else if (conn == NetworkUtil.TYPE_MOBILE) {
            status = "Mobile data enabled";
        } else if (conn == NetworkUtil.TYPE_NOT_CONNECTED) {
            status = "Not connected to Internet";
        }
        return status;
    }
}
	

MainActivity.java



package com.narendra.eventbus;

import android.content.Context;
import android.content.IntentFilter;
import android.net.ConnectivityManager;
import android.os.Build;
import android.os.Bundle;
import android.support.v7.app.AppCompatActivity;
import android.util.Log;
import android.view.View;
import android.widget.Button;
import android.widget.RelativeLayout;
import android.widget.Toast;

import org.greenrobot.eventbus.EventBus;
import org.greenrobot.eventbus.Subscribe;

public class MainActivity extends AppCompatActivity {

    EventBus bus = EventBus.getDefault();
    NetworkChangeReceiver myReceiver = new NetworkChangeReceiver();
    Context context;
    RelativeLayout mainlayout, netlayout;
    Button check;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);
        context = this;

        mainlayout = (RelativeLayout) findViewById(R.id.mainlayout);
        netlayout = (RelativeLayout) findViewById(R.id.neterror);
        check = (Button) findViewById(R.id.check);

        Network.activityname = "main";
        if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.N) {
            registerReceiver(myReceiver,
			new IntentFilter(ConnectivityManager.CONNECTIVITY_ACTION));
        }
        if (!bus.isRegistered(this)) {
            Log.w("-------", " register bus 1111 ");
            bus.register(this);
        }
        if (Network.isConnectingToInternet(context)) {
            mainlayout.setVisibility(View.VISIBLE);
            netlayout.setVisibility(View.GONE);
            perform();
        } else {
            mainlayout.setVisibility(View.GONE);
            netlayout.setVisibility(View.VISIBLE);
        }
    }

    private void perform() {
        Toast.makeText(context, "Connection true", Toast.LENGTH_SHORT).show();
        mainlayout.setVisibility(View.VISIBLE);
        netlayout.setVisibility(View.GONE);

        check.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                if (Network.isConnectingToInternet(context)) {
                    Toast.makeText(context, "Connection true", Toast.LENGTH_SHORT).show();
                    mainlayout.setVisibility(View.VISIBLE);
                    netlayout.setVisibility(View.GONE);
                    perform();
                } else {
                    Toast.makeText(context, "Not Connect", Toast.LENGTH_SHORT).show();
                    mainlayout.setVisibility(View.GONE);
                    netlayout.setVisibility(View.VISIBLE);
                }
            }
        });
    }

    @Subscribe
    public void onEvent(String name) {
        if (name.equalsIgnoreCase("main")) {

            Log.w("------", "on event ");
            perform();
        }
    }

    @Override
    protected void onDestroy() {
        super.onDestroy();

        if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.N) {
            unregisterReceiver(myReceiver);
        }
    }
}
									   
	

Output :

Tags

  • Android

  • Android Studio

  • Android development

  • Java