AndroidAnnotations说明—AndroidAnnotations它是如何工作的?

时间:2023-03-09 18:01:09
AndroidAnnotations说明—AndroidAnnotations它是如何工作的?

AndroidAnnotations它的工作原理很easy,它使用标准java注塑加工工具,自己主动加她一个额外的步骤生成源代码编译。



        源代码是什么?每个增强的类。比方每个用@EActivity注入的Activity,会自己主动生成一个以该类类名+下划线为类名的该Activity子类。



        比方以下这个类:

package com.some.company;

@EActivity
public class MyActivity extends Activity {
// ...
}

将会生成以下这个子类,他们在同一个包以下但处在不同的目录:

package com.some.company;

public final class MyActivity_ extends MyActivity {
// ...
}

这个子类通过复写一些方法(比方onCreate())来为你的activity添加一些行为。



        上面介绍的这些就是你在AndroidManifest.xml生命Acitivty时须要为你的类名后面添加一个下划线的原因:

<activity android:name=".MyListActivity_" />



启动一个使用注入的Activity:


        在Android中,我们一般会通过例如以下的方式来启动一个activity:

startActivity(this, MyListActivity.class);

然而。假设使用AndroidAnnotations的话,真正被启动的activity是MyListActivity_而不是MyListActivity:

startActivity(this, MyListActivity_.class);

 Intent Builder(AndroidAnnotations 2.4及以上):

        我们提供了一个静态的帮助类来启动编译生成的activity:

// Starting the activity
MyListActivity_.intent(context).start(); // Building an intent from the activity
Intent intent = MyListActivity_.intent(context).get(); // You can provide flags
MyListActivity_.intent(context).flags(FLAG_ACTIVITY_CLEAR_TOP).start(); // You can even provide extras defined with @Extra in the activity
MyListActivity_.intent(context).myDateExtra(someDate).start();

在AndroidAnnotations 2.7及以上的版本号中你能够使用还有一个启动Activity的方法startActivityForResult()了 :

MyListActivity_.intent(context).startForResult();

启动一个使用注解的服务:

        在Android中。我们通常通过例如以下的方式来启动一个服务:

startService(this, MyService.class);

然而,假设使用AndroidAnnotations的话,真正被启动的Service是MyService_而不是MyService:

startService(this, MyService_.class);

Intent Builder(AndroidAnnotations 2.7及以上版本号):

        我们提供了一个静态的帮助类来启动生产的Service:

// Starting the service
MyService_.intent(context).start(); // Building an intent from the activity
Intent intent = MyService_.intent(context).build(); // You can provide flags
MyService_.intent(context).flags(Intent.FLAG_GRANT_READ_URI_PERMISSION).start();