AndroidAnnotations(Code Diet)android快速开发框架
jopen
9年前
最近用了一款很不错的android快速开发框架,1000行的代码瞬间变成几百行,不用你会后悔的
特点:
(1) 依赖注入:包括view,extras,系统服务,资源等等
(2) 简单的线程模型,通过annotation表示方法运行在ui线程还是后台线程
(3) 事件绑定:通过annotation表示view的响应事件,不用在写内部类
(4) REST客户端:定义客户端接口,自动生成REST请求的实现
(5) 没有你想象的复杂:AndroidAnnotations只是在在编译时生成相应子类
(6) 不影响应用性能:仅50kb,在编译时完成,不会对运行时有性能影响。
PS:与roboguice的比较:roboguice通过运行时读取annotations进行反射,所以可能影响应用性能,而AndroidAnnotations在编译时生成子类,所以对性能没有影响
现在我们开始试用这个吧
- 首先我们要准备一下基本环境
1.因为目前主流市场IDE环境转入android studio,所以我就直说它的搭建环境吧,打开build.gradle(project)文件导入我们需要的编译环境,下载编译环境工具包
// Top-level build file where you can add configuration options common to all sub-projects/modules. buildscript { repositories { mavenCentral() } dependencies { classpath 'com.android.tools.build:gradle:1.1.+' classpath 'com.neenbedankt.gradle.plugins:android-apt:1.4' //导入编译AndroidAnnotations框架需要使用的工具包 } } tasks.withType(JavaCompile) { options.encoding = "UTF-8" } allprojects { repositories { jcenter() //下载jcenter服务器上的插件工具包 } }
2.打开build.gradle(Module)文件导入我们需要的编译环境,导入下载的工具包apt,下载框架需要的包,然后在运行之前编译的配置,并且输出日志
apply plugin: 'android' apply plugin: 'android-apt' //导入下载的工具 dependencies { compile fileTree(include: '*.jar', dir: 'libs') compile project(':SwitchCompatLibrary') compile 'com.orhanobut:logger:1.1+' compile 'org.androidannotations:androidannotations:3.3.1' //导入框架包 apt 'org.androidannotations:androidannotations:3.3.1' //用之前下载的工具根据框架包编译项目 } apt{ //输出日志文件 arguments{ trace true androidManifestFile variant.outputs[0].processResources.manifestFile } } android { compileSdkVersion 15 buildToolsVersion "21.1.2" lintOptions{ checkReleaseBuilds false } sourceSets { main { manifest.srcFile 'AndroidManifest.xml' java.srcDirs = ['src'] resources.srcDirs = ['src'] aidl.srcDirs = ['src'] renderscript.srcDirs = ['src'] res.srcDirs = ['res'] assets.srcDirs = ['assets'] jniLibs.srcDirs=['libs'] } instrumentTest.setRoot('tests') debug.setRoot('build-types/debug') release.setRoot('build-types/release') } }
大部分情况网络情况不好下,这个包是下载不下来的,我们可以下载在本地放在libs文件下
compile 'org.androidannotations:androidannotations:3.3.1' //导入框架包 apt 'org.androidannotations:androidannotations:3.3.1' //用之前下载的工具根据框架包编译项目 使用方法
compile files('libs/androidannotations.jar')
- 接下来我们使用了
闲话不多了,直接给代码了,下面这段代码是我们平时一般写android的原生代码
public class BookmarksToClipboardActivity extends Activity { BookmarkAdapter adapter; ListView bookmarkList; EditText search; BookmarkApplication application; Animation fadeIn; ClipboardManager clipboardManager; @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); requestWindowFeature(Window.FEATURE_NO_TITLE); getWindow().setFlags(FLAG_FULLSCREEN, FLAG_FULLSCREEN); setContentView(R.layout.bookmarks); bookmarkList = (ListView) findViewById(R.id.bookmarkList); search = (EditText) findViewById(R.id.search); application = (BookmarkApplication) getApplication(); fadeIn = AnimationUtils.loadAnimation(this, anim.fade_in); clipboardManager = (ClipboardManager) getSystemService(CLIPBOARD_SERVICE); View updateBookmarksButton1 = findViewById(R.id.updateBookmarksButton1); updateBookmarksButton1.setOnClickListener(new OnClickListener() { @Override public void onClick(View v) { updateBookmarksClicked(); } }); View updateBookmarksButton2 = findViewById(R.id.updateBookmarksButton2); updateBookmarksButton2.setOnClickListener(new OnClickListener() { @Override public void onClick(View v) { updateBookmarksClicked(); } }); bookmarkList.setOnItemClickListener(new OnItemClickListener() { @Override public void onItemClick(AdapterView<?> p, View v, int pos, long id) { Bookmark selectedBookmark = (Bookmark) p.getAdapter().getItem(pos); bookmarkListItemClicked(selectedBookmark); } }); initBookmarkList(); } void initBookmarkList() { adapter = new BookmarkAdapter(this); bookmarkList.setAdapter(adapter); } void updateBookmarksClicked() { UpdateBookmarksTask task = new UpdateBookmarksTask(); task.execute(search.getText().toString(), application.getUserId()); } private static final String BOOKMARK_URL = // "http://www.bookmarks.com/bookmarks/{userId}?search={search}"; class UpdateBookmarksTask extends AsyncTask<String, Void, Bookmarks> { @Override protected Bookmarks doInBackground(String... params) { String searchString = params[0]; String userId = params[1]; RestTemplate client = new RestTemplate(); HashMap<String, Object> args = new HashMap<String, Object>(); args.put("search", searchString); args.put("userId", userId); HttpHeaders httpHeaders = new HttpHeaders(); HttpEntity<Bookmarks> request = new HttpEntity<Bookmarks>(httpHeaders); ResponseEntity<Bookmarks> response = client.exchange( // BOOKMARK_URL, HttpMethod.GET, request, Bookmarks.class, args); Bookmarks bookmarks = response.getBody(); return bookmarks; } @Override protected void onPostExecute(Bookmarks result) { adapter.updateBookmarks(result); bookmarkList.startAnimation(fadeIn); } } void bookmarkListItemClicked(Bookmark selectedBookmark) { clipboardManager.setText(selectedBookmark.getUrl()); } }
这段是我们用了框架后写过的代码
@NoTitle @Fullscreen @EActivity(R.layout.bookmarks) public class BookmarksToClipboardActivity extends Activity { BookmarkAdapter adapter; @ViewById ListView bookmarkList; @ViewById EditText search; @App BookmarkApplication application; @RestService BookmarkClient restClient; @AnimationRes Animation fadeIn; @SystemService ClipboardManager clipboardManager; @AfterViews void initBookmarkList() { adapter = new BookmarkAdapter(this); bookmarkList.setAdapter(adapter); } @Click({R.id.updateBookmarksButton1, R.id.updateBookmarksButton2}) void updateBookmarksClicked() { searchAsync(search.getText().toString(), application.getUserId()); } @Background void searchAsync(String searchString, String userId) { Bookmarks bookmarks = restClient.getBookmarks(searchString, userId); updateBookmarks(bookmarks); } @UiThread void updateBookmarks(Bookmarks bookmarks) { adapter.updateBookmarks(bookmarks); bookmarkList.startAnimation(fadeIn); } @ItemClick void bookmarkListItemClicked(Bookmark selectedBookmark) { clipboardManager.setText(selectedBookmark.getUrl()); } }
@Rest("http://www.bookmarks.com") public interface BookmarkClient { @Get("/bookmarks/{userId}?search={search}") Bookmarks getBookmarks(String search, String userId); }
对比之后我们发现我们代码少了很多,很多人可能会顾虑代码少了,里面是不是做了很多消耗性能多余的操作,这里大家不用担心,根据AndroidAnnotations写的代码,在编译时生成子类,子类的代码和原生一模一样,所以对性能没有影响
- 常用地址
- api地址和demo地址https://github.com/excilys/androidannotations/wiki/Cookbook
- 下载地址https://github.com/excilys/androidannotations
- 总结
- 基本语法就不和大家说呢,对程序员来说有了api文档和demo就行了
- 这个框架语法很简单用一下就会了,就是环境有点蛋疼,这里只说了一个IDE环境搭配,其它的大家可以看文档
- 东西虽然很好,但是希望android初学者学好基础后再来使用框架,框架是不断推出新的,如果你基础都不知道,以后变迁项目,或者项目报错你会对很多错误很茫然的,对你以后的发展也不好。