Приклад: зв’язок між активністю та сервісом за допомогою повідомлень


584

Я не зміг знайти жодного прикладу того, як надсилати повідомлення між діяльністю та службою, і я витратив занадто багато годин, щоб зрозуміти це. Ось приклад проекту для посилань для інших.

Цей приклад дозволяє запускати або зупиняти послугу безпосередньо, а також окремо прив'язувати / скасовувати зв’язок із службою. Коли служба працює, вона збільшує число на 10 Гц. Якщо активність пов'язана з значком Service, воно відображатиме поточне значення. Дані передаються як цілий чи рядок, так що ви можете бачити, як це зробити двома різними способами. У діяльності також є кнопки для надсилання повідомлень до сервісу (змінює приріст значення).

Знімок екрана:

Скріншот прикладу обміну повідомленнями служби Android

AndroidManifest.xml:

<?xml version="1.0" encoding="utf-8"?>
<manifest xmlns:android="http://schemas.android.com/apk/res/android"
      package="com.exampleservice"
      android:versionCode="1"
      android:versionName="1.0">
    <application android:icon="@drawable/icon" android:label="@string/app_name">
        <activity android:name=".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>
    <service android:name=".MyService"></service>
    </application>
    <uses-sdk android:minSdkVersion="8" />
</manifest>

res \ values ​​\ strings.xml:

<?xml version="1.0" encoding="utf-8"?>
<resources>
    <string name="app_name">ExampleService</string>
    <string name="service_started">Example Service started</string>
    <string name="service_label">Example Service Label</string>
</resources>

res \ layout \ main.xml:

<RelativeLayout
    android:id="@+id/RelativeLayout01"
    android:layout_width="fill_parent"
    android:layout_height="wrap_content" >

    <Button
        android:id="@+id/btnStart"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:text="Start Service" >
    </Button>

    <Button
        android:id="@+id/btnStop"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:layout_alignParentRight="true"
        android:text="Stop Service" >
    </Button>
</RelativeLayout>

<RelativeLayout
    android:id="@+id/RelativeLayout02"
    android:layout_width="fill_parent"
    android:layout_height="wrap_content" >

    <Button
        android:id="@+id/btnBind"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:text="Bind to Service" >
    </Button>

    <Button
        android:id="@+id/btnUnbind"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:layout_alignParentRight="true"
        android:text="Unbind from Service" >
    </Button>
</RelativeLayout>

<TextView
    android:id="@+id/textStatus"
    android:layout_width="fill_parent"
    android:layout_height="wrap_content"
    android:text="Status Goes Here"
    android:textSize="24sp" />

<TextView
    android:id="@+id/textIntValue"
    android:layout_width="fill_parent"
    android:layout_height="wrap_content"
    android:text="Integer Value Goes Here"
    android:textSize="24sp" />

<TextView
    android:id="@+id/textStrValue"
    android:layout_width="fill_parent"
    android:layout_height="wrap_content"
    android:text="String Value Goes Here"
    android:textSize="24sp" />

<RelativeLayout
    android:id="@+id/RelativeLayout03"
    android:layout_width="fill_parent"
    android:layout_height="wrap_content" >

    <Button
        android:id="@+id/btnUpby1"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:text="Increment by 1" >
    </Button>

    <Button
        android:id="@+id/btnUpby10"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:layout_alignParentRight="true"
        android:text="Increment by 10" >
    </Button>
</RelativeLayout>

src \ com.exampleservice \ MainActivity.java:

package com.exampleservice;

import android.app.Activity;
import android.content.ComponentName;
import android.content.Context;
import android.content.Intent;
import android.content.ServiceConnection;
import android.os.Bundle;
import android.os.Handler;
import android.os.IBinder;
import android.os.Message;
import android.os.Messenger;
import android.os.RemoteException;
import android.util.Log;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.Button;
import android.widget.TextView;

public class MainActivity extends Activity {
    Button btnStart, btnStop, btnBind, btnUnbind, btnUpby1, btnUpby10;
    TextView textStatus, textIntValue, textStrValue;
    Messenger mService = null;
    boolean mIsBound;
    final Messenger mMessenger = new Messenger(new IncomingHandler());

    class IncomingHandler extends Handler {
        @Override
        public void handleMessage(Message msg) {
            switch (msg.what) {
            case MyService.MSG_SET_INT_VALUE:
                textIntValue.setText("Int Message: " + msg.arg1);
                break;
            case MyService.MSG_SET_STRING_VALUE:
                String str1 = msg.getData().getString("str1");
                textStrValue.setText("Str Message: " + str1);
                break;
            default:
                super.handleMessage(msg);
            }
        }
    }
    private ServiceConnection mConnection = new ServiceConnection() {
        public void onServiceConnected(ComponentName className, IBinder service) {
            mService = new Messenger(service);
            textStatus.setText("Attached.");
            try {
                Message msg = Message.obtain(null, MyService.MSG_REGISTER_CLIENT);
                msg.replyTo = mMessenger;
                mService.send(msg);
            }
            catch (RemoteException e) {
                // In this case the service has crashed before we could even do anything with it
            }
        }

        public void onServiceDisconnected(ComponentName className) {
            // This is called when the connection with the service has been unexpectedly disconnected - process crashed.
            mService = null;
            textStatus.setText("Disconnected.");
        }
    };

    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.main);
        btnStart = (Button)findViewById(R.id.btnStart);
        btnStop = (Button)findViewById(R.id.btnStop);
        btnBind = (Button)findViewById(R.id.btnBind);
        btnUnbind = (Button)findViewById(R.id.btnUnbind);
        textStatus = (TextView)findViewById(R.id.textStatus);
        textIntValue = (TextView)findViewById(R.id.textIntValue);
        textStrValue = (TextView)findViewById(R.id.textStrValue);
        btnUpby1 = (Button)findViewById(R.id.btnUpby1);
        btnUpby10 = (Button)findViewById(R.id.btnUpby10);

        btnStart.setOnClickListener(btnStartListener);
        btnStop.setOnClickListener(btnStopListener);
        btnBind.setOnClickListener(btnBindListener);
        btnUnbind.setOnClickListener(btnUnbindListener);
        btnUpby1.setOnClickListener(btnUpby1Listener);
        btnUpby10.setOnClickListener(btnUpby10Listener);

        restoreMe(savedInstanceState);

        CheckIfServiceIsRunning();
    }

    @Override
    protected void onSaveInstanceState(Bundle outState) {
        super.onSaveInstanceState(outState);
        outState.putString("textStatus", textStatus.getText().toString());
        outState.putString("textIntValue", textIntValue.getText().toString());
        outState.putString("textStrValue", textStrValue.getText().toString());
    }
    private void restoreMe(Bundle state) {
        if (state!=null) {
            textStatus.setText(state.getString("textStatus"));
            textIntValue.setText(state.getString("textIntValue"));
            textStrValue.setText(state.getString("textStrValue"));
        }
    }
    private void CheckIfServiceIsRunning() {
        //If the service is running when the activity starts, we want to automatically bind to it.
        if (MyService.isRunning()) {
            doBindService();
        }
    }

    private OnClickListener btnStartListener = new OnClickListener() {
        public void onClick(View v){
            startService(new Intent(MainActivity.this, MyService.class));
        }
    };
    private OnClickListener btnStopListener = new OnClickListener() {
        public void onClick(View v){
            doUnbindService();
            stopService(new Intent(MainActivity.this, MyService.class));
        }
    };
    private OnClickListener btnBindListener = new OnClickListener() {
        public void onClick(View v){
            doBindService();
        }
    };
    private OnClickListener btnUnbindListener = new OnClickListener() {
        public void onClick(View v){
            doUnbindService();
        }
    };
    private OnClickListener btnUpby1Listener = new OnClickListener() {
        public void onClick(View v){
            sendMessageToService(1);
        }
    };
    private OnClickListener btnUpby10Listener = new OnClickListener() {
        public void onClick(View v){
            sendMessageToService(10);
        }
    };
    private void sendMessageToService(int intvaluetosend) {
        if (mIsBound) {
            if (mService != null) {
                try {
                    Message msg = Message.obtain(null, MyService.MSG_SET_INT_VALUE, intvaluetosend, 0);
                    msg.replyTo = mMessenger;
                    mService.send(msg);
                }
                catch (RemoteException e) {
                }
            }
        }
    }


    void doBindService() {
        bindService(new Intent(this, MyService.class), mConnection, Context.BIND_AUTO_CREATE);
        mIsBound = true;
        textStatus.setText("Binding.");
    }
    void doUnbindService() {
        if (mIsBound) {
            // If we have received the service, and hence registered with it, then now is the time to unregister.
            if (mService != null) {
                try {
                    Message msg = Message.obtain(null, MyService.MSG_UNREGISTER_CLIENT);
                    msg.replyTo = mMessenger;
                    mService.send(msg);
                }
                catch (RemoteException e) {
                    // There is nothing special we need to do if the service has crashed.
                }
            }
            // Detach our existing connection.
            unbindService(mConnection);
            mIsBound = false;
            textStatus.setText("Unbinding.");
        }
    }

    @Override
    protected void onDestroy() {
        super.onDestroy();
        try {
            doUnbindService();
        }
        catch (Throwable t) {
            Log.e("MainActivity", "Failed to unbind from the service", t);
        }
    }
}

src \ com.exampleservice \ MyService.java:

package com.exampleservice;

import java.util.ArrayList;
import java.util.Timer;
import java.util.TimerTask;

import android.app.Notification;
import android.app.NotificationManager;
import android.app.PendingIntent;
import android.app.Service;
import android.content.Intent;
import android.os.Bundle;
import android.os.Handler;
import android.os.IBinder;
import android.os.Message;
import android.os.Messenger;
import android.os.RemoteException;
import android.util.Log;

public class MyService extends Service {
    private NotificationManager nm;
    private Timer timer = new Timer();
    private int counter = 0, incrementby = 1;
    private static boolean isRunning = false;

    ArrayList<Messenger> mClients = new ArrayList<Messenger>(); // Keeps track of all current registered clients.
    int mValue = 0; // Holds last value set by a client.
    static final int MSG_REGISTER_CLIENT = 1;
    static final int MSG_UNREGISTER_CLIENT = 2;
    static final int MSG_SET_INT_VALUE = 3;
    static final int MSG_SET_STRING_VALUE = 4;
    final Messenger mMessenger = new Messenger(new IncomingHandler()); // Target we publish for clients to send messages to IncomingHandler.


    @Override
    public IBinder onBind(Intent intent) {
        return mMessenger.getBinder();
    }
    class IncomingHandler extends Handler { // Handler of incoming messages from clients.
        @Override
        public void handleMessage(Message msg) {
            switch (msg.what) {
            case MSG_REGISTER_CLIENT:
                mClients.add(msg.replyTo);
                break;
            case MSG_UNREGISTER_CLIENT:
                mClients.remove(msg.replyTo);
                break;
            case MSG_SET_INT_VALUE:
                incrementby = msg.arg1;
                break;
            default:
                super.handleMessage(msg);
            }
        }
    }
    private void sendMessageToUI(int intvaluetosend) {
        for (int i=mClients.size()-1; i>=0; i--) {
            try {
                // Send data as an Integer
                mClients.get(i).send(Message.obtain(null, MSG_SET_INT_VALUE, intvaluetosend, 0));

                //Send data as a String
                Bundle b = new Bundle();
                b.putString("str1", "ab" + intvaluetosend + "cd");
                Message msg = Message.obtain(null, MSG_SET_STRING_VALUE);
                msg.setData(b);
                mClients.get(i).send(msg);

            }
            catch (RemoteException e) {
                // The client is dead. Remove it from the list; we are going through the list from back to front so this is safe to do inside the loop.
                mClients.remove(i);
            }
        }
    }

    @Override
    public void onCreate() {
        super.onCreate();
        Log.i("MyService", "Service Started.");
        showNotification();
        timer.scheduleAtFixedRate(new TimerTask(){ public void run() {onTimerTick();}}, 0, 100L);
        isRunning = true;
    }
    private void showNotification() {
        nm = (NotificationManager)getSystemService(NOTIFICATION_SERVICE);
        // In this sample, we'll use the same text for the ticker and the expanded notification
        CharSequence text = getText(R.string.service_started);
        // Set the icon, scrolling text and timestamp
        Notification notification = new Notification(R.drawable.icon, text, System.currentTimeMillis());
        // The PendingIntent to launch our activity if the user selects this notification
        PendingIntent contentIntent = PendingIntent.getActivity(this, 0, new Intent(this, MainActivity.class), 0);
        // Set the info for the views that show in the notification panel.
        notification.setLatestEventInfo(this, getText(R.string.service_label), text, contentIntent);
        // Send the notification.
        // We use a layout id because it is a unique number.  We use it later to cancel.
        nm.notify(R.string.service_started, notification);
    }
    @Override
    public int onStartCommand(Intent intent, int flags, int startId) {
        Log.i("MyService", "Received start id " + startId + ": " + intent);
        return START_STICKY; // run until explicitly stopped.
    }

    public static boolean isRunning()
    {
        return isRunning;
    }


    private void onTimerTick() {
        Log.i("TimerTick", "Timer doing work." + counter);
        try {
            counter += incrementby;
            sendMessageToUI(counter);

        }
        catch (Throwable t) { //you should always ultimately catch all exceptions in timer tasks.
            Log.e("TimerTick", "Timer Tick Failed.", t);
        }
    }

    @Override
    public void onDestroy() {
        super.onDestroy();
        if (timer != null) {timer.cancel();}
        counter=0;
        nm.cancel(R.string.service_started); // Cancel the persistent notification.
        Log.i("MyService", "Service Stopped.");
        isRunning = false;
    }
}

53
Чудовий приклад! Ще одна приємна особливість: Якщо ви помістите android:process=:myservicenameатрибут serviceтегу вашої служби в manifest.xml, як-от:, <service android:name="sname" android:process=":myservicename" />то він запустить вашу службу як інший процес - таким чином, в інший потік. Це означає, що будь-який важкий розрахунок, виконаний / тривалий запит сервісом, не повинен підвішувати вашу нитку інтерфейсу користувача.
— sydd

28
Я знаю, що ви доклали зусиль для цього, але було б більше сенсу розмістити його на github або подібному веб-сайті для спільного використання вихідного коду та опублікувати посилання тут. Людям легше це встати і працювати таким чином.
— Ехтеш Чудхурі

25
Хороший приклад. Я ставлю цей код на онлайн-репо (з незначними модифікаціями) для тих, хто хотів би клонувати: bitbucket.org/alexfu/androidserviceexample/src
— Алекс Фу

7
Повідомлення дійсно необхідне лише в тому випадку, якщо вашу послугу можуть викликати інші програми. В іншому випадку ви можете дотримуватися Binder, який повертає вам посилання на Службу і просто називає публічні методи її.
— type-a1pha

13
Вам слід було поставити запитання, а потім створити відповідь самостійно, а не відповідати на питання. Хоча
— чудовий

Відповіді:


46

Подивіться приклад LocalService .

Ви Serviceповертаєте екземпляр себе споживачам, які дзвонять onBind. Тоді ви можете безпосередньо взаємодіяти з сервісом, наприклад, зареєструвати власний інтерфейс слухача з сервісом, щоб ви могли отримати зворотній зв'язок.


2
Єдина проблема з цим полягає в тому, що він не використовував би Messenger, тому він не відповів би на це псевдо питання. Я використовував LocalService, але був радий знайти приклад Messenger / Handler. Я не вірю, що LocalService можна ввести в інший процес.
— Бен

@ Christoper-Orr: Я дуже вдячний, що ви опублікували це посилання Android BroadcastReceiverпідручника. Я використовував a LocalBroadcastManagerдля постійного обміну даними між двома Activityекземплярами.
— Дірк

Проблема LocalBroadcastManagerполягає в тому, що це не блокує і вам доведеться чекати результатів. Іноді хочеться негайних результатів.
— TheRealChx101

Чи можете ви мені допомогти з цим питанням stackoverflow.com/questions/51508046/…
— Rajesh K

20

Для надсилання даних до сервісу ви можете використовувати:

Intent intent = new Intent(getApplicationContext(), YourService.class);
intent.putExtra("SomeData","ItValue");
startService(intent);

А після служби в onStartCommand () отримуйте дані з наміру.

Для надсилання даних або події з послуги в додаток (для однієї або декількох заходів):

private void sendBroadcastMessage(String intentFilterName, int arg1, String extraKey) {
    Intent intent = new Intent(intentFilterName);
    if (arg1 != -1 && extraKey != null) {
        intent.putExtra(extraKey, arg1);
    }
    sendBroadcast(intent);
}

Цей метод дзвонить з вашої служби. Ви можете просто надіслати дані для своєї діяльності.

private void someTaskInYourService(){

    //For example you downloading from server 1000 files
    for(int i = 0; i < 1000; i++) {
        Thread.sleep(5000) // 5 seconds. Catch in try-catch block
        sendBroadCastMessage(Events.UPDATE_DOWNLOADING_PROGRESSBAR, i,0,"up_download_progress");
    }

Для отримання події з даними створіть і зареєструйте метод registerBroadcastReceivers () у своїй діяльності:

private void registerBroadcastReceivers(){
    broadcastReceiver = new BroadcastReceiver() {
        @Override
        public void onReceive(Context context, Intent intent) {
            int arg1 = intent.getIntExtra("up_download_progress",0);
            progressBar.setProgress(arg1);
        }
    };
    IntentFilter progressfilter = new IntentFilter(Events.UPDATE_DOWNLOADING_PROGRESS);
    registerReceiver(broadcastReceiver,progressfilter);

Щоб надіслати більше даних, ви можете змінити метод sendBroadcastMessage();. Пам'ятайте: ви повинні зареєструвати трансляції методами onResume () та скасувати реєстрацію в методах onStop ()!

ОНОВЛЕННЯ

Будь ласка, не використовуйте мій тип зв'язку між Діяльністю та Сервісом. Це неправильний шлях. Для кращого досвіду, будь ласка, використовуйте спеціальні губки, такі як ми:

1) EventBus від greenrobot

2) Отто від Square Inc

PS Я використовую EventBus від greenrobot у своїх проектах,


2
де мені потрібно зареєструвати приймач в onResume та в onStop, чи потрібно мені робити в діяльності?
— користувач3233280

Так. Для отримання події від служби потрібно зареєструвати трансляцію в режимі onResume. Пам’ятайте, що ви повинні скасувати реєстрацію трансляції в onStop. Тепер я не рекомендую використовувати свій метод. Будь ласка, використовуйте спеціальні лібри для спілкування з іншими видами / діями / послугами, такими як EventBus github.com/greenrobot/EventBus або Otto github.com/square/otto
— a.black13

1
Ви можете, будь ласка, допомогти мені, як я можу використовувати це, що я застряг у своєму проекті в службовому спілкуванні
— user3233280

8
Чи рекомендував Google проти цього, чи ти просто кажеш, що це "неправильно", оскільки ти вважаєш, що інші рішення кращі?
— Кевін Крумвієде

плюс один для надання посилань на EventBusта Otto.
— Мохаммед Алі

14

Примітка. Вам не потрібно перевіряти, чи працює ваша служба CheckIfServiceIsRunning(), тому що bindService()запустить її, якщо вона не працює.

Також: якщо ви повертаєте телефон, ви не хочете, щоб він bindService()знову, тому що onCreate()буде викликаний знову. Обов’язково визначтеся, onConfigurationChanged()щоб цього не допустити.


У моєму випадку мені служба не потрібна постійно. Якщо служба вже працює, коли діяльність починається, я хочу прив’язати її. Якщо служба не запускається, коли діяльність починається, я хочу залишити службу зупиненою.
— Lance Lefebure

1
Я не впевнений, що це правда, bindService не запускає послугу, чи можете ви вказати на документацію?
— Калін

1
developer.android.com/reference/android/app/Service.html У першому абзаці зазначеноServices can be started with Context.startService() and Context.bindService()
— Хтось десь

8
Message msg = Message.obtain(null, 2, 0, 0);
                    Bundle bundle = new Bundle();
                    bundle.putString("url", url);
                    bundle.putString("names", names);
                    bundle.putString("captions",captions); 
                    msg.setData(bundle);

Тож ви відправляєте його в службу. Після цього отримайте.


8

Все добре. Добрий приклад activity/serviceспілкування за допомогою Messenger .

Один коментар: метод MyService.isRunning()не потрібен .. bindService()можна зробити будь-яку кількість разів. шкоди в цьому немає.

Якщо MyService працює в іншому процесі, статична функція MyService.isRunning()завжди повертатиметься хибною. Тому немає необхідності в цій функції.


2

Це те, як я реалізував Activity-> Service Communication: у своїй діяльності я мав

private static class MyResultReciever extends ResultReceiver {
     /**
     * Create a new ResultReceive to receive results.  Your
     * {@link #onReceiveResult} method will be called from the thread running
     * <var>handler</var> if given, or from an arbitrary thread if null.
     *
     * @param handler
     */
     public MyResultReciever(Handler handler) {
         super(handler);
     }

     @Override
     protected void onReceiveResult(int resultCode, Bundle resultData) {
         if (resultCode == 100) {
             //dostuff
         }
     }

А потім я скористався цим, щоб розпочати свою Службу

protected void onCreate(Bundle savedInstanceState) {
MyResultReciever resultReciever = new MyResultReciever(handler);
        service = new Intent(this, MyService.class);
        service.putExtra("receiver", resultReciever);
        startService(service);
}

У моїй службі я був

public int onStartCommand(Intent intent, int flags, int startId) {
    if (intent != null)
        resultReceiver = intent.getParcelableExtra("receiver");
    return Service.START_STICKY;
}

Сподіваюся, що це допомагає


0

Мені здається, ти міг би зберегти деяку пам’ять, заявивши про свою діяльність за допомогою "Implements Handler.Callback"


0

Чудовий підручник, фантастична презентація. Акуратний, простий, короткий і дуже пояснювальний. Хоча, notification.setLatestEventInfo(this, getText(R.string.service_label), text, contentIntent);методу вже немає. Як тут було сказано, інтерес повинен бути:

private static final int NOTIFICATION_ID = 45349;

private void showNotification() {
    NotificationCompat.Builder builder =
            new NotificationCompat.Builder(this)
                    .setSmallIcon(R.mipmap.ic_launcher)
                    .setContentTitle("My Notification Title")
                    .setContentText("Something interesting happened");

    Intent targetIntent = new Intent(this, MainActivity.class);
    PendingIntent contentIntent = PendingIntent.getActivity(this, 0, targetIntent, PendingIntent.FLAG_UPDATE_CURRENT);
    builder.setContentIntent(contentIntent);
    _nManager = (NotificationManager) getSystemService(Context.NOTIFICATION_SERVICE);
    _nManager.notify(NOTIFICATION_ID, builder.build());
}

@Override
public void onDestroy() {
    super.onDestroy();
    if (_timer != null) {_timer.cancel();}
    _counter=0;
    _nManager.cancel(NOTIFICATION_ID); // Cancel the persistent notification.
    Log.i("PlaybackService", "Service Stopped.");
    _isRunning = false;
}

Перевірив себе, все працює як шарм (назви діяльності та послуг можуть відрізнятися від оригіналу).


0

Я бачив усі відповіді. Я хочу розповісти найбільш надійний спосіб зараз за день . Це змусить вас спілкуватися між Activity - Service - Dialog - Fragments(Все).

EventBus

Ця лайка, яку я використовую у своїх проектах, має чудові функції, пов’язані з повідомленнями.

EventBus в 3 етапи

  1. Визначте події:

    public static class MessageEvent { /* Additional fields if needed */ }

  2. Підготуйте передплатників:

Декларуйте та коментуйте свій метод підписки, необов'язково вкажіть режим потоку :

@Subscribe(threadMode = ThreadMode.MAIN) 
public void onMessageEvent(MessageEvent event) {/* Do something */};

Зареєструйте та скасуйте реєстрацію свого підписника. Наприклад, на Android, дії та фрагменти зазвичай повинні реєструватися відповідно до їх життєвого циклу:

@Override
public void onStart() {
    super.onStart();
    EventBus.getDefault().register(this);
}

@Override
public void onStop() {
    super.onStop();
    EventBus.getDefault().unregister(this);
}
  1. Опублікувати події:

    EventBus.getDefault().post(new MessageEvent());

Просто додайте цю залежність у ступінь рівня програми

compile 'org.greenrobot:eventbus:3.1.1'
Використовуючи наш веб-сайт, ви визнаєте, що прочитали та зрозуміли наші Політику щодо файлів cookie та Політику конфіденційності.
Licensed under cc by-sa 3.0 with attribution required.