AndroidAnnotations(Code Diet)android快速开发框架
最近用了一款很不错的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的原生代码
1 public class BookmarksToClipboardActivity extends Activity { 2 3 BookmarkAdapter adapter; 4 5 ListView bookmarkList; 6 7 EditText search; 8 9 BookmarkApplication application; 10 11 Animation fadeIn; 12 13 ClipboardManager clipboardManager; 14 15 @Override 16 protected void onCreate(Bundle savedInstanceState) { 17 super.onCreate(savedInstanceState); 18 19 requestWindowFeature(Window.FEATURE_NO_TITLE); 20 getWindow().setFlags(FLAG_FULLSCREEN, FLAG_FULLSCREEN); 21 22 setContentView(R.layout.bookmarks); 23 24 bookmarkList = (ListView) findViewById(R.id.bookmarkList); 25 search = (EditText) findViewById(R.id.search); 26 application = (BookmarkApplication) getApplication(); 27 fadeIn = AnimationUtils.loadAnimation(this, anim.fade_in); 28 clipboardManager = (ClipboardManager) getSystemService(CLIPBOARD_SERVICE); 29 30 View updateBookmarksButton1 = findViewById(R.id.updateBookmarksButton1); 31 updateBookmarksButton1.setOnClickListener(new OnClickListener() { 32 33 @Override 34 public void onClick(View v) { 35 updateBookmarksClicked(); 36 } 37 }); 38 39 View updateBookmarksButton2 = findViewById(R.id.updateBookmarksButton2); 40 updateBookmarksButton2.setOnClickListener(new OnClickListener() { 41 42 @Override 43 public void onClick(View v) { 44 updateBookmarksClicked(); 45 } 46 }); 47 48 bookmarkList.setOnItemClickListener(new OnItemClickListener() { 49 50 @Override 51 public void onItemClick(AdapterView<?> p, View v, int pos, long id) { 52 Bookmark selectedBookmark = (Bookmark) p.getAdapter().getItem(pos); 53 bookmarkListItemClicked(selectedBookmark); 54 } 55 }); 56 57 initBookmarkList(); 58 } 59 60 void initBookmarkList() { 61 adapter = new BookmarkAdapter(this); 62 bookmarkList.setAdapter(adapter); 63 } 64 65 void updateBookmarksClicked() { 66 UpdateBookmarksTask task = new UpdateBookmarksTask(); 67 68 task.execute(search.getText().toString(), application.getUserId()); 69 } 70 71 private static final String BOOKMARK_URL = // 72 "http://www.bookmarks.com/bookmarks/{userId}?search={search}"; 73 74 75 class UpdateBookmarksTask extends AsyncTask<String, Void, Bookmarks> { 76 77 @Override 78 protected Bookmarks doInBackground(String... params) { 79 String searchString = params[0]; 80 String userId = params[1]; 81 82 RestTemplate client = new RestTemplate(); 83 HashMap<String, Object> args = new HashMap<String, Object>(); 84 args.put("search", searchString); 85 args.put("userId", userId); 86 HttpHeaders httpHeaders = new HttpHeaders(); 87 HttpEntity<Bookmarks> request = new HttpEntity<Bookmarks>(httpHeaders); 88 ResponseEntity<Bookmarks> response = client.exchange( // 89 BOOKMARK_URL, HttpMethod.GET, request, Bookmarks.class, args); 90 Bookmarks bookmarks = response.getBody(); 91 92 return bookmarks; 93 } 94 95 @Override 96 protected void onPostExecute(Bookmarks result) { 97 adapter.updateBookmarks(result); 98 bookmarkList.startAnimation(fadeIn); 99 } 100 101 } 102 103 void bookmarkListItemClicked(Bookmark selectedBookmark) { 104 clipboardManager.setText(selectedBookmark.getUrl()); 105 } 106 107 }
这段是我们用了框架后写过的代码
1 @NoTitle 2 @Fullscreen 3 @EActivity(R.layout.bookmarks) 4 public class BookmarksToClipboardActivity extends Activity { 5 6 BookmarkAdapter adapter; 7 8 @ViewById 9 ListView bookmarkList; 10 11 @ViewById 12 EditText search; 13 14 @App 15 BookmarkApplication application; 16 17 @RestService 18 BookmarkClient restClient; 19 20 @AnimationRes 21 Animation fadeIn; 22 23 @SystemService 24 ClipboardManager clipboardManager; 25 26 @AfterViews 27 void initBookmarkList() { 28 adapter = new BookmarkAdapter(this); 29 bookmarkList.setAdapter(adapter); 30 } 31 32 @Click({R.id.updateBookmarksButton1, R.id.updateBookmarksButton2}) 33 void updateBookmarksClicked() { 34 searchAsync(search.getText().toString(), application.getUserId()); 35 } 36 37 @Background 38 void searchAsync(String searchString, String userId) { 39 Bookmarks bookmarks = restClient.getBookmarks(searchString, userId); 40 updateBookmarks(bookmarks); 41 } 42 43 @UiThread 44 void updateBookmarks(Bookmarks bookmarks) { 45 adapter.updateBookmarks(bookmarks); 46 bookmarkList.startAnimation(fadeIn); 47 } 48 49 @ItemClick 50 void bookmarkListItemClicked(Bookmark selectedBookmark) { 51 clipboardManager.setText(selectedBookmark.getUrl()); 52 } 53 54 }
1 @Rest("http://www.bookmarks.com") 2 public interface BookmarkClient { 3 4 @Get("/bookmarks/{userId}?search={search}") 5 Bookmarks getBookmarks(String search, String userId); 6 7 }
对比之后我们发现我们代码少了很多,很多人可能会顾虑代码少了,里面是不是做了很多消耗性能多余的操作,这里大家不用担心,根据AndroidAnnotations写的代码,在编译时生成子类,子类的代码和原生一模一样,所以对性能没有影响
- 常用地址
- api地址和demo地址https://github.com/excilys/androidannotations/wiki/Cookbook
- 下载地址https://github.com/excilys/androidannotations
- 总结
- 基本语法就不和大家说呢,对程序员来说有了api文档和demo就行了
- 这个框架语法很简单用一下就会了,就是环境有点蛋疼,这里只说了一个IDE环境搭配,其它的大家可以看文档
- 东西虽然很好,但是希望android初学者学好基础后再来使用框架,框架是不断推出新的,如果你基础都不知道,以后变迁项目,或者项目报错你会对很多错误很茫然的,对你以后的发展也不好。