EventBus comunication between activity and service

有些话、适合烂在心里 提交于 2021-02-19 08:30:06

问题


I'm working on an Android application with EventBus library. I have an activity and a service. I want to to fire an event from activity and receive it on service.

The activity is:

public class MainActivity extends AppCompatActivity {

    public static final String TAG="ACTIVITY";

    @Subscribe(threadMode = ThreadMode.MAIN)
    public void onMessageEvent(StartEvent event) {
        Log.d(TAG, "Received message");
        Snackbar.make(fab, "Stop task", Snackbar.LENGTH_LONG).show();
        txtMessage.setText(event.message);
    };

    FloatingActionButton fab;


    TextView txtMessage;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);
        Toolbar toolbar = (Toolbar) findViewById(R.id.toolbar);
        setSupportActionBar(toolbar);

        txtMessage=findViewById(R.id.txtMessage);
        fab = (FloatingActionButton) findViewById(R.id.fab);
        fab.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                Snackbar.make(view, "Start background process", Snackbar.LENGTH_LONG)
                        .setAction("Action", null).show();
                txtMessage.setText("Begin");
                Log.d(TAG,Thread.currentThread().getName()+ " ");
                EventBus.getDefault().post(new StartEvent());
            }
        });
    }

    @Override
    protected void onPause() {
        EventBus.getDefault().unregister(this);
        super.onPause();
    }

    @Override
    protected void onResume() {
        // registriamo un receiver per ricevere una notifica alla fine del servizio in background
        EventBus.getDefault().register(this);
        super.onResume();
    }


}

The service is:

public class MyService extends Service {
    public static final String TAG="SERVICE";

    public MyService() {
    }

    @Nullable
    @Override
    public IBinder onBind(Intent intent) {
        return null;
    }

    @Override
    public int onStartCommand(Intent intent, int flags, int startId) {
        return START_STICKY_COMPATIBILITY;
    }

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

    }

    @Override
    public void onDestroy() {
        EventBus.getDefault().unregister(this);
        super.onDestroy();
    }

    @Subscribe
    public void onEvent(StartEvent event){
        Log.d(TAG, "BEGIN process in background su thread "+Thread.currentThread().getName());

        try {
            Thread.sleep(10000);
        } catch (InterruptedException e) {
            e.printStackTrace();
        }
        Log.d(TAG, "END processo in background su thread "+Thread.currentThread().getName());

        MessageEvent message=new MessageEvent();
        message.message="Operazione in background terminata!";
        EventBus.getDefault().post(message);
    }

}

The manifest is:

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

    <application
        android:allowBackup="true"
        android:icon="@mipmap/ic_launcher"
        android:label="@string/app_name"
        android:roundIcon="@mipmap/ic_launcher_round"
        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>

        <service
            android:name=".MyService"
            android:enabled="true"
            android:exported="true"></service>
    </application>

</manifest>

When i press button on activity to start background task, EventBus show me the following message on logcat:

ACTIVITY: main 
EventBus: No subscribers registered for event class xx.StartEvent
EventBus: No subscribers registered for event class org.greenrobot.eventbus.NoSubscriberEvent

What is wrong?


回答1:


The service should be running before it can receive events.

If it is not running it is not registered, and if it is not registered you see the no subscribers message.




回答2:


It's because same bus instance can't run on different processes.

android:exported="true"

Your MainService is exported, which means that it's different process.



来源:https://stackoverflow.com/questions/47295912/eventbus-comunication-between-activity-and-service

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!