Android annotations REST

时间:2024-09-28 18:04:20

使用前:

 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的Rest注解替换手工建立Spring Android RestTemplate对象,不仅可以减少很多代码,同时使工程结构更简洁、严谨,利于复用。

自己构造RestTemplate的原生写法:

 HttpHeaders requestHeaders = new HttpHeaders();
List<MediaType> acceptableMediaTypes = new ArrayList<MediaType>();
acceptableMediaTypes.add(MediaType.APPLICATION_JSON);
requestHeaders.setAccept(acceptableMediaTypes); HttpEntity<?> requestEntity = new HttpEntity<Object>(requestHeaders); RestTemplate restTemplate = new RestTemplate();
restTemplate.getMessageConverters().add(new MappingJackson2HttpMessageConverter()); ResponseEntity<User[]> responseEntity = restTemplate.exchange(url, HttpMethod.GET, requestEntity, User[].class);

利用androidannotations的Rest注解替换后的代码:

 //初始化
@RestService
RestApiService restApiService;
ResponseEntity<User[]> responseEntity = restApiService.getByStatus();
 @Rest(rootUrl = "http://10.0.2.2:8080/together/api", converters = { MappingJackson2HttpMessageConverter.class })
public interface RestApiService { @Get("/user/getByStatus.do?status=1")
ResponseEntity<User[]> getUsersByStatus(); }

wiki api :

https://github.com/excilys/androidannotations/wiki/Rest-API