package com.example.eventbustest;
import android.app.Activity;
import android.content.Intent;
import android.os.Bundle;
import android.view.Menu;
import android.view.MenuItem;
public class MainActivity extends Activity {
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
// setContentView(R.layout.activity_main);
// text = (TextView) findViewById(R.id.text);
// EventBus.getDefault().register(this);
task();
Intent intent = new Intent(this, MyAppService.class);
startService(intent);
}
@Override
public void onDestroy() {
super.onDestroy();
Intent intent = new Intent(this, MyAppService.class);
stopService(intent);
}
private void task() {
new Thread(new Runnable() {
@Override
public void run() {
try {
Thread.sleep(3000);
} catch (InterruptedException e) {
e.printStackTrace();
}
for (int i = 0; i < 100; i++) {
MyEvent event = new MyEvent();
event.id = i;
event.content = "hello,world !" + i;
EventBus.getDefault().post(event);
try {
Thread.sleep(2000);
} catch (InterruptedException e) {
e.printStackTrace();
}
}
}
}).start();
}
}
package com.example.eventbustest;
import android.app.Service;
import android.content.Intent;
import android.os.IBinder;
import android.util.Log;
public class MyAppService extends Service{
// 仅仅create一次
@Override
public void onCreate() {
EventBus.getDefault().register(this);
}
// @Override
// public int onStartCommand(Intent intent, int flags, int startId) {
// return super.onStartCommand(intent, flags, startId);
// }
@Override
public void onDestroy() {
EventBus.getDefault().unregister(this);
}
@Override
public IBinder onBind(Intent intent) {
return null;
}
// 这里,EventBus回调接受消息,然后更新Main UI的TextView
public void onEventMainThread(MyEvent event) {
Log.d(this.getClass().getName(),
"onEventMainThread:" + event.toString());
}
// EventBus回调接受消息
public void onEventBackgroundThread(MyEvent event) {
Log.d(this.getClass().getName(),
"onEventBackgroundThread:" + event.toString());
}
// EventBus回调接受消息
public void onEventAsync(MyEvent event) {
Log.d(this.getClass().getName(), "onEventAsync:" + event.toString());
}
}
package com.example.eventbustest;
public class MyEvent {
public int id;
public String content;
@Override
public String toString(){
return content;
}
}
<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"
tools:context="com.example.eventbustest.MainActivity" >
<TextView
android:id="@+id/text"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="@string/hello_world" />
<Button
android:id="@+id/button"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_alignParentBottom="true"
android:layout_marginBottom="162dp"
android:layout_toRightOf="@+id/text"
android:text="启动Service" />
</RelativeLayout>