Programing

Virgil Dobjanschi REST 구현 패턴을 구현하는 샘플 Android REST 클라이언트 프로젝트가 필요합니다.

lottogame 2020. 10. 6. 07:44
반응형

Virgil Dobjanschi REST 구현 패턴을 구현하는 샘플 Android REST 클라이언트 프로젝트가 필요합니다.


안드로이드 폰에서 REST 클라이언트를 만들고 싶습니다.

REST 서버는 (GET)과 같은 여러 리소스를 노출합니다.

http://foo.bar/customer      List of all customer
http://foo.bar/customer/4711    The customer with id 4711
http://foo.bar/customer/vip     List of all VIP customer

http://foo.bar/company           List of all companys
http://foo.bar/company/4711     The company with the ID 4711
http://foo.bar/company/vip      List of all VIP companys

나는 REST 서버와 대화하고 필요한 정보를 얻는 방법을 알고 있습니다. 다음과 같은 API로 REST 클라이언트 클래스를 구현합니다.

public List<Customer> getCustomers();
public Customer getCustomer(final String id);
public List<Customer> getVipCustomer();

public List<Company> getCompanies();
public Customer getCompany(final String id);
public List<Customer> getVipCompanies();

Virgil Dobjanschi의 " Developing Android REST client applications " 프레젠테이션을 참조 하여 활동의 작업자 스레드에서 REST 요청을 처리하는 것이 좋지 않다는 것을 알게되었습니다. 대신 Service API를 사용해야합니다 .

(로컬) 서비스에 바인딩되는 Singleton ServiceHelper가 있다는 생각이 마음에 들지만 서비스 개념을 올바르게 이해하지 못한 것 같습니다.

지금은 REST 호출 결과 (서비스에서 비동기로 수행됨)를 호출자 활동에 다시보고하는 방법을 이해하지 못합니다. 또한 모든 REST 요청 (다른 반환 유형 포함)을 처리하는 ONE Service가 필요한지 아니면 각 REST 요청에 대한 전용 서비스가 필요한지 궁금합니다.

아마도 다른 이해 문제가 많을 것이므로 가장 좋은 것은 내 요구를 충족 하는 샘플 응용 프로그램 이 될 것입니다. 내 사용 사례는 드물지 않으며 예제 응용 프로그램이 있기를 바랍니다.

알려주세요!

올바른 구현 방향을 알려주는 다른 제안도 도움이됩니다 (Android API-Demo가 내 사용 사례와 일치하지 않음).

미리 감사드립니다.

클라우스

편집 : SO에서 발견 된 유사한 주제 (이 게시물을 게시 한 후)가 필요한 방향으로 안내합니다 (복잡한 "Dobjanschi 패턴"최소화) :


오버뷰

편집하다:

관심있는 사람이라면 누구나 RESTful Android를 살펴 보는 것도 고려해 볼 수 있습니다.

Dobjanschi 모델을 구현하려는 경험에서 배운 것은 모든 것이 돌로 작성된 것은 아니며 앱에서 앱으로 변경 될 수있는 작업에 대한 개요 만 제공한다는 것입니다. 그러나 공식은 다음과 같습니다.

이 아이디어를 따르십시오 + 자신의 것을 추가하십시오 = 행복한 Android 애플리케이션

일부 앱의 모델은 요구 사항과 다를 수 있으며 일부는 SyncAdapter에 대한 계정이 필요하지 않을 수 있고 다른 일부는 C2DM을 사용할 수 있습니다. 최근에 작업 한이 모델은 누군가를 도울 수 있습니다.


계정 및 AccountManager가있는 응용 프로그램 만들기

SyncAdapter를 사용하여 데이터를 동기화 할 수 있습니다. 이것은 자신의 SyncAdapter 만들기 에서 논의되었습니다.

ContentProvider 만들기 (필요한 경우)

이 추상화를 사용하면 데이터베이스에 액세스 할 수있을뿐만 아니라 REST Arch와의 일대일 매핑 방법이 있으므로 ServiceHelper로 이동하여 REST 호출을 실행할 수 있습니다.

콘텐츠 제공자 | REST 방법

쿼리 ----------------> GET

삽입 ----------------> PUT

업데이트 ----------------> POST

삭제 ----------------> DELETE

ServiceHelper 계층화

이 사람은 기본적으로 (a) ContentProvider에서 전달한 매개 변수로 Http (반드시 프로토콜은 아니지만 가장 일반적인) REST 메소드를 실행하는 서비스를 시작합니다. 콘텐츠 공급자의 UriMatcher에서 가져온 일치 정수를 전달하여 액세스 할 REST 리소스를 알 수 있습니다.

class ServiceHelper{

    public static void execute(Context context,int match,String parameters){
//find the service resource (/path/to/remote/service with the match
//start service with parameters 
    }

}

서비스

실행되고 (대부분 IntentService를 사용합니다) 도우미에서 전달 된 매개 변수를 사용하여 RESTMethod로 이동합니다. 서비스는 백그라운드에서 실행하는 것이 좋습니다.

또한 BroadCastReceiver를 구현하여 서비스가 작업이 완료되면이 브로드 캐스트를 등록한 내 활동에 알리고 다시 쿼리하십시오. 저는이 마지막 단계가 Virgill Conference에있는 것이 아니라고 생각하지만 좋은 방법이라고 확신합니다.

RESTMethod 클래스

Takes the parameters, the WS resource(http://myservice.com/service/path) adds the parameters,prepared everything, execute the call, and save the response.

If the authtoken is needed you can requested from the AccountManager If the calling of the service failed because authentication, you can invalidate the authtoken and reauth to get a new token.

Finally the RESTMethod gives me either a XML or JSON no matter i create a processor based on the matcher and pass the response.

The processor

It's in charged of parsing the response and insert it locally.

A Sample Application? Of course!

Also if you are interesting on a test application you look at Eli-G, it might not be the best example but it follow the Service REST approach, it is built with ServiceHelper, Processor, ContentProvider, Loader, and Broadcast.


Programming Android has a complete chapter (13. Exploring Content Providers) dedicated to 'Option B: Use the ContentProvider API' from Virgil's Google I/O talk.

We are not the only ones who see the benefits of this approach. At the Google I/O conference in May 2010, Virgil Dobjanschi of Google presented a talk that outlined the following three patterns for using content providers to integrate RESTful web services into Android applications...

In this chapter, we’ll explore the second pattern in detail with our second Finch video example; this strategy will yield a number of important benefits for your applications. Due to the elegance with which this approach integrates network operations into Android MVC, we’ve given it the moniker “Network MVC.”

A future edition of Programming Android may address the other two approaches, as well as document more details of this Google presentation. After you finish reading this chapter, we suggest that you view Google’s talk.

Highly recommended.

Programming Android by Zigurd Mednieks, Laird Dornin, G. Blake Meike, and Masumi Nakamura. Copyright 2011 O’Reilly Media, Inc., 978-1-449-38969-7.


"Developing Android REST client applications" by Virgil Dobjanschi led to much discussion, since no source code was presented during the session or was provided afterwards.

  • A reference implementation is available under http://datadroid.foxykeep.com (the Google IO session is mentioned under /presentation). It is a library which you can use in your own application.
  • Android Priority Job Queue was inspired by Dobjanschi's talk and sounds very promising to me.

Please comment if you know more implementations.


We have developped a library that adresses this issue : RoboSpice.

The library uses the "service approach" described by Virgil Dobjanschi and Neil Goodmann, but we offer a complete all-in-one solution that :

  • executes asynchronously (in a background AndroidService) network requests that will return POJOs (ex: REST requests)
  • caches results (in Json, or Xml, or flat text files, or binary files)
  • notifies your activities (or any other context) of the result of the network request if they are still alive
  • doesn't notify your activities of the result if they are not alive anymore
  • notifies your activities on their UI Thread
  • uses a simple but robust exception handling model
  • supports multiple ContentServices to aggregate different web services results
  • supports multi-threading of request executions
  • is strongly typed !
  • is open source ;)
  • and tested

We are actually looking for feedback from the community.


Retrofit could be very helpful here, it builds an Adapter for you from a very simple configuration like:

Retrofit turns your REST API into a Java interface.

public interface GitHubService {
  @GET("/users/{user}/repos")
  List<Repo> listRepos(@Path("user") String user);
}

The RestAdapter class generates an implementation of the GitHubService interface.

RestAdapter restAdapter = new RestAdapter.Builder()
    .setEndpoint("https://api.github.com")
    .build();

GitHubService service = restAdapter.create(GitHubService.class); Each call on the generated GitHubService makes an HTTP request to the remote webserver.

List<Repo> repos = service.listRepos("octocat");

for more information visit the official site: http://square.github.io/retrofit/

Note: the adapter RestAdapter you get from Retrofit is not derived from BaseAdapter you should make a wrapper for it somehow like this SO question Why is my ListView empty after calling setListAdapter inside ListFragment?


This is a little late but here is an article which explains the first pattern from the talk:

http://www.codeproject.com/Articles/429997/Sample-Implementation-of-Virgil-Dobjanschis-Rest-p

The thing I like about the first pattern is that the interface to the rest methods is a plain class, and the Content Provider is left to simply provide access to the database.


You should check out the source code for Google's official I/O 2010 app, for starters, particularly the SyncService and the various classes in the io subpackage.


Good news guys. An implementation of the service helper is available here: https://github.com/MathiasSeguy-Android2EE/MythicServiceHelper It's an open source project (Apache 2). I am at the beginning of the project. I've done a project where I defined the pattern to do, but i haven't yet extract the code to make a clean librairy. It will be done soon.

참고URL : https://stackoverflow.com/questions/4948152/need-sample-android-rest-client-project-which-implements-virgil-dobjanschi-rest

반응형