articles

Home / DeveloperSection / Articles / Using the Otto Event Bus library on Android

Using the Otto Event Bus library on Android

Manoj Pandey10832 16-Mar-2015

Otto is an event bus designed to decouple different parts of your application while

still allowing them to communicate efficiently.

Forked from Guava, Otto adds unique functionality to an already refined event bus as well as specializing it to the Android platform.

Otto is a great way to communicate between your activity and fragments or to communicate between an activity and a service.

Here is an example of Otto Event Bus library

1.      Create an android project

2.      The usage of this library in Java or Android is very simple, download the JAR and its one requirement from Download Otto and add it to your classpath.

3.      Add library in libs folder

4.      My activity_main.xml file

<FrameLayout xmlns:android="http://schemas.android.com/apk/res/android"

    xmlns:tools="http://schemas.android.com/tools"

    android:id="@+id/container"

    android:layout_width="match_parent"

    android:layout_height="match_parent"

    tools:context="com.vogella.android.otto.MainActivity"

    tools:ignore="MergeRootFrame" />

5.       Add new xml layout name as fragment_main.xml and add following views

<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"

    xmlns:tools="http://schemas.android.com/tools"

    android:layout_width="match_parent"

    android:layout_height="match_parent"

    android:paddingBottom="@dimen/activity_vertical_margin"

    android:paddingLeft="@dimen/activity_horizontal_margin"

    android:paddingRight="@dimen/activity_horizontal_margin"

    android:paddingTop="@dimen/activity_vertical_margin"

>

 

    <Button

        android:id="@+id/fragmentbutton"

        android:layout_width="wrap_content"

        android:layout_height="wrap_content"

        android:layout_marginTop="20dp"

        android:text="Send event from fragment" />

 

</RelativeLayout>

 6 .      Paste following code in MainActivity.class

 

 package com.example.androidottoenevt; 

import android.os.Bundle;

import android.app.Activity;

import android.view.Menu; 

import android.app.Fragment;

import android.view.LayoutInflater;

import android.view.MenuItem;

import android.view.View;

import android.view.ViewGroup;

import android.widget.Toast; 

import com.squareup.otto.Bus;

import com.squareup.otto.Produce;

import com.squareup.otto.Subscribe;

import com.squareup.otto.ThreadEnforcer; 

public class MainActivity extends Activity {

                public static Bus bus; 

                @Override

                protected void onCreate(Bundle savedInstanceState) {

                                super.onCreate(savedInstanceState);

                                setContentView(R.layout.activity_main);

                                if (savedInstanceState == null) {

                                                getFragmentManager().beginTransaction()

                                                                                .add(R.id.container, new PlaceholderFragment()).commit();

                                }

                                bus = new Bus(ThreadEnforcer.MAIN);

                                bus.register(this);

                }

                @Subscribe

                public void getMessage(String s) {

                                Toast.makeText(this, s, Toast.LENGTH_LONG).show();

                } 

                @Override

                public boolean onCreateOptionsMenu(Menu menu) {

                                getMenuInflater().inflate(R.menu.main, menu);

                                return true;

                } 

                @Override

                public boolean onOptionsItemSelected(MenuItem item) {

                                int id = item.getItemId();

                                if (id == R.id.action_settings) {

                                                TestData t = new TestData();

                                                t.message = "Hello from the activity";

                                                bus.post(t);

                                                return true;

                                }

                                return super.onOptionsItemSelected(item);

                } 

                public class TestData {

                                public String message;

                }

               /**

                 * A placeholder fragment containing a simple view.

                 */ 

                public static class PlaceholderFragment extends Fragment { 

                                public PlaceholderFragment() {

                                } 

                                @Override

                                public View onCreateView(LayoutInflater inflater, ViewGroup container,

                                                                Bundle savedInstanceState) {

                                                View rootView = inflater.inflate(R.layout.fragment_main, container,

                                                                                false);

                                                View button = rootView.findViewById(R.id.fragmentbutton);

                                                button.setOnClickListener(new View.OnClickListener() { 

                                                                @Override

                                                                public void onClick(View v) {

                                                                                bus.post("Hello from the Fragment");

                                                                }

                                                });

                                                bus.register(this);

                                                return rootView;

                                } 

                                @Subscribe

                                public void getMessage(MainActivity.TestData data) {

                                                Toast.makeText(getActivity(), data.message, Toast.LENGTH_LONG)  .show();

                                }

                } 

                @Produce

                public String produceEvent() {

                                return "Starting up";

                } 

}

7.       My Manifest.xml file

<?xml version="1.0" encoding="utf-8"?>

<manifest xmlns:android="http://schemas.android.com/apk/res/android"

    package="com.example.androidottoenevt"

    android:versionCode="1"

    android:versionName="1.0" >

 

    <uses-sdk

        android:minSdkVersion="10"

        android:targetSdkVersion="18" />

 

    <application

        android:allowBackup="true"

        android:icon="@drawable/ic_launcher"

        android:label="@string/app_name"

        android:theme="@style/AppTheme" >

        <activity

            android:name="com.example.androidottoenevt.MainActivity"

            android:label="@string/app_name" >

            <intent-filter>

                <action android:name="android.intent.action.MAIN" />

 

          <category android:name="android.intent.category.LAUNCHER" />

            </intent-filter>

        </activity>

    </application>

 

</manifest>

 

Now run your application

 

Using the Otto Event Bus library on Android

 

 


Leave Comment

Comments

Liked By