牛骨文教育服务平台(让学习变的简单)

(一).前言:

前面我们已经对于AndroidAnnotations框架的事件绑定做了讲解,今天我们开始具体学习一下线程处理(Threading)方法。

FastDev4Android框架项目地址:https://github.com/jiangqqlmj/FastDev4Android 

已更新如下:

自AndroidAnnotation1.0起,让我们从今天开始摆脱AsyncTask吧

(二).@Background

使用@Background注解的方法可以运行在子线程中而非UI线程。使用实例如下:

void myMethod() {
    someBackgroundWork("hello", 42);
}
 
@Background
voidsomeBackgroundWork(String aParam, long anotherParam) {
    [...]
}

该方法可以在单独的线程上面运行,但不意味着开启一个新线程。因为这边注解的内部使用一个共享的线程池,这样可以避免创建更多的线程。这意味着两个都使用@Background注解的方法可以并行的运行。

(三).@Id

自AndroidAnnotations3.0

如果你想要取消一个后台任务,你可以使用id字段,每一个任务都可以通过BackgroundExecutor.cancelAll("id")

void myMethod() {
   someCancellableBackground("hello", 42);
    [...]
    boolean mayInterruptIfRunning = true;
   BackgroundExecutor.cancelAll("cancellable_task",mayInterruptIfRunning);
}
 
@Background(id="cancellable_task")
voidsomeCancellableBackground(String aParam, long anotherParam) {
    [...]
}

(四).@Serial

自AndroidAnnotations3.0起,默认情况下,使用@Background注解的方法是并行运行的。如果你想要这些任务方法按照顺序执行,你可以使用@Serial注解字段,所有后台的任务将会按照顺序执行。使用实例如下:

void myMethod() {
    for (int i = 0; i < 10; i++)
        someSequentialBackgroundMethod(i);
}
 
@Background(serial ="test")
voidsomeSequentialBackgroundMethod(int i) {
    SystemClock.sleep(newRandom().nextInt(2000)+1000);
    Log.d("AA", "value : "+ i);
}

(五).@Delay

自AndroidAnnotations3.0起,如果想要让后台方法延迟运行,你可以使用@Delay参数

@Background(delay=2000)
voiddoInBackgroundAfterTwoSeconds() {
}

(六).@UiThread

使用@UiThread注解的方法可以在UIThread进行运行,使用实例如下:

void myMethod() {
    doInUiThread("hello", 42);
}
 
@UiThread
voiddoInUiThread(String aParam, long anotherParam) {
    [...]
}

就不在使用AsyncTask

(七).@SupposeBackground

自AndroidAnnotations3.1起,使用实例:

@EBean
public class MyBean{
 
  @SupposeBackground
  voidsomeMethodThatShouldNotBeCalledFromUiThread() {
  //if this method will be called from theUI-thread an exception will be thrown
  }
 
  @SupposeBackground(serial ={"serial1", "serial2"})
  voidsomeMethodThatShouldBeCalledFromSerial1OrSerial2() {
  //if this method will be called from anotherthread then a background thread with a
  //serial "serial1" or"serial2", an exception will be thrown
  }
}

(八).@SupposeUiThread

确保方法在UiThread中运行,使用实例:

@EBean
public class MyBean{
 
  @SupposeUiThread
  voidsomeMethodThatShouldBeCalledOnlyFromUiThread() {
  //if this method will be called from abackground thread an exception will be thrown
  }
 
}

到此位置关于AndroidAnnotations注解线程处理(Threading)使用方法已经全部讲解完成了。

FastDev4Android项目已经添加配置了AndroidAnnotations框架,后期的框架项目中也会主要使用这个DI框架,.欢迎大家去Github站点进行clone或者下载浏览.

https://github.com/jiangqqlmj/FastDev4Android 

同时欢迎大家star和fork整个开源快速开发框架项目~如果有什么意见和反馈,欢迎留言,必定第一时间回复。也欢迎有同样兴趣的童鞋加入到该项目中来,一起维护该项目。