EventBus

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();
  }

 }

}

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值