EventBus下载地址:https://github.com/greenrobot/EventBus
MyEvent:
package com.zzw.testeventbus; public class MyEvent {
public int id;
public String content; public MyEvent() {
super(); } @Override
public String toString() {
return "MyEvent [id=" + id + ", content=" + content + "]";
} }
MyEvent
MainActivity:
package com.zzw.testeventbus; import android.app.Activity;
import android.content.Intent;
import android.graphics.Color;
import android.os.Bundle;
import android.util.Log;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.TextView;
import de.greenrobot.event.EventBus; public class MainActivity extends Activity {
TextView tv;
public static final String TAG = "MainActivity"; @Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
tv = (TextView) findViewById(R.id.tv); EventBus.getDefault().register(this); findViewById(R.id.bt).setOnClickListener(new OnClickListener() {
@Override
public void onClick(View v) {
Intent intent = new Intent(MainActivity.this, EventService.class);
startService(intent);
}
});
}
// Main线程,这个与Android UI线程密切相关,可以在里面设置UI值,不要阻塞它!
public void onEventMainThread(MyEvent event) {
Log.d(TAG + "--" + "onEventMainThread", event.toString());
tv.setText(event.content);
int id = event.id % 3;
if (id == 0) {
tv.setTextColor(Color.RED);
} else if (id == 1) {
tv.setTextColor(Color.GREEN);
} else if (id == 2) {
tv.setTextColor(Color.BLUE);
}
} // 后台线程中接收处理
public void onEventBackgroundThread(MyEvent event) {
Log.e(TAG + "--" + "onEventBackgroundThread", event.toString());
} // 异步线程中接收处理
public void onEventAsync(MyEvent event) {
Log.i(TAG + "--" + "onEventAsync", event.toString());
} @Override
protected void onDestroy() {
EventBus.getDefault().unregister(this);
}
}
EventService:
package com.zzw.testeventbus; import android.app.Service;
import android.content.Intent;
import android.os.IBinder;
import android.os.SystemClock;
import de.greenrobot.event.EventBus; public class EventService extends Service { @Override
public void onCreate() { super.onCreate();
} private void task() {
new Thread(new Runnable() { @Override
public void run() {
for (int i = 1; i <= 100; i++) {
MyEvent event = new MyEvent();
event.id = i;
event.content = "傻逼" + i;
EventBus.getDefault().post(event);
SystemClock.sleep(1000);
}
}
}).start();
} @Override
public int onStartCommand(Intent intent, int flags, int startId) {
task();
return super.onStartCommand(intent, flags, startId);
} @Override
public void onDestroy() {
super.onDestroy();
} @Override
public IBinder onBind(Intent intent) {
return null;
} }