EventBus:
案例:用服务后台下载图片然后显示,案例中的FirstEvent是一个自定义的javaBean
public class MainActivity extends Activity {
private ImageView iv;
// EventBus:事件的发布和订阅总线.
// 发布:传递消息;
// 订阅:接受消息.
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
// EventBus的使用步骤
// ①.注册EventBus
EventBus.getDefault().register(this);
iv = (ImageView) findViewById(R.id.iv);
}
// 开启服务进行下载
public void down(View v) {
Intent service = new Intent(this, DownTaskService.class);
startService(service);
}
// ②.用来接受传递过来的消息
// 那么不论事件是在哪个线程中发布出来的,onEventMainThread都会在UI线程中执行
public void onEventMainThread(FristEvent event) {
// 接受消息
Bitmap bp = event.getBp();
iv.setImageBitmap(bp);
}
// 该方法到底属于什么线程:看发消息的地方属于什么线程.
public void onEvent() {
}
// 如果使用onEventBackgrond作为订阅函数,那么如果事件是在UI线程中发布出来的,
// 那么onEventBackground就会在子线程中运行
public void onEventBackgroundThread() {
}
// 使用这个函数作为订阅函数,那么无论事件在哪个线程发布,都会创建新的子线程在执行onEventAsync.
public void onEventAsync() {
}
// ③.取消注册
@Override
protected void onDestroy() {
super.onDestroy();
EventBus.getDefault().unregister(this);
}
}
在自定义的IntentService中:
public class DownTaskService extends IntentService {
private String path = "http://pimg1.126.net/movie/product/movie/144350279411210314_520_692_webp.jpg";
public DownTaskService() {
super("");
}
@Override
protected void onHandleIntent(Intent intent) {
try {
URL url = new URL(path);
HttpURLConnection conn = (HttpURLConnection) url.openConnection();
if (conn.getResponseCode() == 200) {
InputStream is = conn.getInputStream();
Bitmap bitmap = BitmapFactory.decodeStream(is);
if (bitmap != null) {
// 将Bitmap传递给Activity进行展示
// 利用EventBus传递消息
EventBus.getDefault().post(new FristEvent(bitmap));
}
}
} catch (IOException e) {
e.printStackTrace();
}
}
}