AndroidAnnnotations注入框架使用之Inje

(一).前言:

前面我们已经对于AndroidAnnotations框架的注入组件的方式做了讲解,今天我们开始具体学习一下Injection标签使用。

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

本博客已完成Injection更新如下:

(二).@AfterExtras

自AndroidAnnotations3.1起

如果你需要在extras注入之后执行相关代码,你可以在该要执行的方法上面使用@AfterExtras注解

@EActivity
public class MyClass{
 
  @Extra
  String someExtra;
 
  @Extra
  int anotherExtra;
 
 
  @AfterExtras
  public void doSomethingAfterExtrasInjection(){
    // someExtra and anotherExtra are set tothe value contained in the incoming intent
    // if an intent does not contain one of theextra values the field remains unchanged
  }
 
}

(三).@AfterInject

如下的例子:当然我们的被@EBean注解类的构造函数被调用,它的属性还没有被注入,如果你需要在编译的时候,依赖注入的之后执行相关的代码。你可以在需要执行的方法使用@AfterInject注入。

@EBean
public class MyClass{
 
  @SystemService
  NotificationManager notificationManager;
 
  @Bean
  MyOtherClass dependency;
 
  public MyClass() {
    // notificationManager and dependency arenull
  }
 
  @AfterInject
  public void doSomethingAfterInjection() {
    // notificationManager and dependency areset
  }
 
}

(四).@AfterViews

使用@AfterViews注解过后的方法会在views进行绑定之后被调用。

[注]当onCreate()方法被调用的时候,然后@ViewById注入的属性还没有被执行。因此你可以在依赖注入的Views中使用@AfterViews。

实例如下:

@EActivity(R.layout.main)
public classMyActivity extends Activity {
 
    @ViewById
    TextView myTextView;
 
    @AfterViews
    void updateTextWithDate() {
        myTextView.setText("Date: " +new Date());
    }
[...]

同样你可以使用@AfterViews注解多个方法。但是要记住,在onCreate()方法不要使用任务View相关的属性。

@EActivity(R.layout.main)
public classMyActivity extends Activity {
 
    @ViewById
    TextView myTextView;
 
    @Override
    public void onCreate(BundlesavedInstanceState) {
        super.onCreate(savedInstanceState);
        // DON"T DO THIS !! It will throw aNullPointerException, myTextView is not set yet.
        // myTextView.setText("Date:" + new Date());
    }
[...]

(五).@App

自AndroidAnnotations 2.1开始

你可以使用@App来进行注入Application类

@EActivity
public classMyActivity extends Activity {
  @App
  MyApplication application;
}

该同样在任何类型注入组件中进行使用,例如:@EBBean

@EBean
public class MyBean{
  @App
  MyApplication application;
}

(六).@Bean

在另一个注解类或者Android组件中使用这个注解类,我们可以使用@Bean;

@EBean
public classMyOtherClass {
  @Bean
  MyClass myClass;
}

同时你可以实现继承依赖关系

@EActivity
public classMyActivity extends Activity {
  @Bean
  MyOtherClass myOtherClass;
}

【注】当你在属性声明的地方使用@Bean注入,你总会得到一个新的实例,除非那个类是一个单例。

值得我们注意的是,注解生成的子类是final类型的,也就是说我们不能在继承生成的类。但是我们可以扩展原始的类。扩展出来的类同样可以使用注解。如下:

@EActivity
public classMyChildActivity extends MyActivity {
}

(七).@Extra

自AndroidAnnotations1.0起

@Extra注解表示Activity中的属性应该注解成Intent中相应的Extra数据,由此用来打开Activity

使用实例如下:

@EActivity
public classMyActivity extends Activity {
 
  @Extra("myStringExtra")
  String myMessage;
 
  @Extra("myDateExtra")
  Date myDateExtraWithDefaultValue = newDate();
 
}

自AndroidAnnotations2.6起

如果@Extra注解中没有提供任何值,那么将会直接使用属性的名字。

@EActivity
public classMyActivity extends Activity {
 
  // The name of the extra will be"myMessage"
  @Extra
  String myMessage;
}

你可以通过Intent构建起来传递额外的数据值

MyActivity_.intent().myMessage("hello").start();

(八).@FragmentArg

使用@FragmentArg注解Fragment中的属性相当于Fragment Argument

生成的构建器的set方法总会使用argument相同的名字。默认情况下绑定值的key的名字就是该注入的属性的名字,但是你可以给以个@FragmentArg的参数值来改变它。

实例:

@EFragment
public classMyFragment extends Fragment {
 
  @FragmentArg("myStringArgument")
  String myMessage;
 
  @FragmentArg
  String anotherStringArgument;
 
  @FragmentArg("myDateExtra")
  Date myDateArgumentWithDefaultValue = newDate();
 
}

使用Fragment构建器来进行使用。

MyFragmentmyFragment = MyFragment_.builder()
  .myMessage("Hello")
  .anotherStringArgument("World")
  .build();

(九).@FragmentById和@FragmentByTag

我们可以在类中使用@EActivity,@EFragment,@Eview,@EViewGroup,@EBean,使用@FragmentById或者@FragmentByTag来进行注入fragments。

【注】推荐使用哪个@FragmentById而不是@FragmentByTag,因为后者没有编译时候的验证。

请注意@FragmentById和@FragmentByTag仅仅能注入fragments而不是创建它们。所以它们只能存在于Activity中

@EActivity(R.layout.fragments)
public classMyFragmentActivity extends FragmentActivity {
  @FragmentById
  MyFragment myFragment;
 
  @FragmentById(R.id.myFragment)
  MyFragment myFragment2;
 
  @FragmentByTag
  MyFragment myFragmentTag;
 
  @FragmentByTag("myFragmentTag")
  MyFragment myFragmentTag2;
}

(十).@FromHtml

10.1.注入HTML

自AndroidAnnotations2.2起

如果你要TextView中注入HTML文本(可能因为格式问题或者你天生喜欢使用HTML),有下面两种方式帮到你:

  • @FromHtml
  • @HtmlRes

现在我们假设有以下的字符串资源

<?xmlversion="1.0" encoding="utf-8"?>
<resources>
    <stringname="hello_html"><![CDATA[Hello<b>World</b>!]]></string>
</resources>

10.2.@HtmlRes

这个注解首先会表现成@StringRes(获取字符串资源),然后进行包装进行调用HTML.fromHtml():

@EActivity
public classMyActivity extends Activity {
 
  // Injects R.string.hello_html
  @HtmlRes(R.string.hello_html)
  Spanned myHelloString;
 
  // Also injects R.string.hello_html
  @HtmlRes
  CharSequence helloHtml;
 
}

10.3.@FromHtml

这个@FromHtml必须被使用在TextView,并且该TextView已经被@ViewById注解了,该注解的目的就是设置HTML文本在TextView上面

@EActivity
public classMyActivity extends Activity {
 
  @ViewById(R.id.my_text_view)
  @FromHtml(R.string.hello_html)
  TextView textView;
 
  // Injects R.string.hello_html into theR.id.hello_html view
  @ViewById
  @FromHtml
  TextView helloHtml;
 
}

(十一).@HttpsClient

自AndroidAnnotations2.6起

11.1.简要介绍

通过@HttpsClient注解实例简化了HTTPS请求配置秘钥,信任库和主机验证。并且所有的参数都是可选的。

11.2.双向认证

下面实例是一个完整的表单,如果你想实现验证,方式如下:

@HttpsClient(trustStore=R.raw.cacerts,
    trustStorePwd="changeit",
    keyStore=R.raw.client,
    keyStorePwd="secret",
    allowAllHostnames=false)
HttpClienthttpsClient;
  • trustStore:信任库
  • trustStorePwd:密码
  • keyStore:秘钥
  • keyStorePwd:秘钥密码
  • allowAllHostnames:允许的主机名

简单的SSL身份认证如下:

@HttpsClient(trustStore=R.raw.mycacerts,
    trustStorePwd="changeit")
HttpClienthttpsClient;

11.3.默认情况

如果你没有指定信任的文件,注解会使用Android默认的信任库在/system/etc/security/cacerts.bks

@HttpsClient
HttpClienthttpsClient;

11.4.使用实例

@EActivity
public classMyActivity extends Activity {
 
    @HttpsClient(trustStore=R.raw.cacerts,
        trustStorePwd="changeit",
        hostnameVerif=true)
    HttpClient httpsClient;
 
    @AfterInject
    @Background
    public void securedRequest() {
        try {
            HttpGet httpget = newHttpGet("https://www.verisign.com/");
            HttpResponse response =httpsClient.execute(httpget);
            doSomethingWithResponse(response);
        } catch (Exception e) {
            e.printStackTrace();
        }
    }
 
    @UiThread
    public voiddoSomethingWithResponse(HttpResponse resp) {
        Toast.makeText(this, "HTTP status" + resp.getStatusLine().getStatusCode(), Toast.LENGTH_LONG).show();
    }
}

(十二).@NoConfigurationInstance

自AndroidAnnotations2.5开始

12.1.简要介绍

当Configuration发生改变的时候,Activity通常会被销毁然后重新创建。这样会重新加载资源。这样就涉及一个从就对象到新Activity实例的引用问题(例如:加载图片,网络连接,Activity运行的线程…)

这就是Activity.onRetainNonConfigurationInstance()用来解决这个问题。

12.2.@NonConfigurationInstance

我们通过@NonConfigurationInstance来对Activity的属性变量进行注解,在配置信息发生改变的时候来保存实例。

@EActivity
public classMyActivity extends Activity {
 
  @NonConfigurationInstance
  Bitmap someBitmap;
 
  @NonConfigurationInstance
  @Bean
  MyBackgroundTask myBackgroundTask;
 
}

(十三).@RootContext

可以在@EBean依赖注入的类中使用@RootContext注入Android根组件,不过需要主要的时候只能注入上下文相关类型的。

@EBean
public class MyClass{
 
  @RootContext
  Context context;
 
  // Only injected if the root context is anactivity
  @RootContext
  Activity activity;
 
  // Only injected if the root context is aservice
  @RootContext
  Service service;
 
  // Only injected if the root context is aninstance of MyActivity
  @RootContext
  MyActivity myActivity;
 
}

(十四).@SystemService

自AndroidAnnotations1.0起

14.1.Android系统标准服务注入

使用标准的系统服务,我们需要记得系统服务的常量名字,然后进行强制转换获取。

notificationManager= (NotificationManager) context.getSystemService(Context.NOTIFICATION_SERVICE);

14.2.@SystemService

使用@SystemSerivce注解的Activity中的属性相当于使用Android系统服务,该等同于调用Context.getSystemService()方法。

@EActivity
public classMyActivity extends Activity {
 
  @SystemService
  NotificationManager notificationManager;
 
}

(十五).@ViewById

使用@ViewById注解Activity中的属性等相当于布局文件中的View组件。等同于调用findViewById()方法。该View的id可以设置在注解的参数中,例如@ViewById(R.id.myTextView)。如果没有设置,将会使用字段的的名字。并且字段不能为私有的。实例如下:

@EActivity
public classMyActivity extends Activity {
 
  // Injects R.id.myEditText
  @ViewById
  EditText myEditText;
 
  @ViewById(R.id.myTextView)
  TextView textView;
}

(十六).@ViewsById

自AndroidAnnotations3.1起

该注解和@ViewById相似,不过该是注入一组视图View。该私用java.util.List或者android.view.view子类型的属性。该注解的参数值为R.id.*相关集合。在通过给定的IDs注入之后的views会保存在List中。但是需要检查代码避免空数据加入注入。

到此位置关于AndroidAnnotations注解Injection标签使用方法已经全部讲解完成了。

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

https://github.com/jiangqqlmj/FastDev4Android 

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

文章导航