SORU
25 Kasım 2011, Cuma


DİNLENME istemci, Örnek Android?

Eğer bu konu cevap kabul etmiş olsa bile, diğer fikirler önermek için çekinmeyin, ya da kullanın


Bu makaleler tanıştım:

Ve istemci uygulamaları hakkında 2010 video G/Ç bu Google beni neden

Şimdi bu yana, Uygulama denetleyicisi sınıfımda statik bileşeni olarak DİNLENME bileşen oluşturma oldum.

Şimdi, bence, desen de değiştirmek lazım. Somebody Google IOSched Uygulama Android üzerinde KALAN müşteriler yazmak için nasıl büyük bir örnek olduğunu ifade etti. Somebody else yol çok overcomplicated bu olduğunu söyledi.

Kimse en iyi uygulama gösterin lütfen? Kısa ve basit bir şekilde.
İOSched uygulama örnek-örnek kullanım için çok karmaşık.

CEVAP
2 Ocak 2012, PAZARTESİ


DÜZENLEME:

Orijinal cevabı bir yıldan fazla düzenleme ve bu anda bir buçuk yaşında. Kavramları özgün bir cevap olarak sunulan kıpırdama olsa da diğer cevaplar işaret ettiği gibi, şimdi sizin için bu görevi kolaylaştıran kütüphaneler var. Daha da önemlisi, bu kütüphanelerin bazıları için aygıt yapılandırma değişiklikleri ele.

Orijinal cevap referans için aşağıda korunur. Ama lütfen herkes de bazı eğer kullanım durumları onlar uygun olup olmadığını görmek için Android için istemci kitaplıkları incelemek için zaman ayırın. Aşağıdaki değerlendirdi olduğum kütüphanelere listesidir. Hiçbir şekilde kapsamlı bir liste olması amaçlanmıştır.


Orijinal Cevabı:

Olması için benim yaklaşım sunan Android istemcileri DİNLENME. En iyisi de bu olur :) iddia etmiyorum Da, bu benim ihtiyacına yanıt olarak geldi ne olduğunu unutmayın. Eğer kullanım durumunda talep varsa daha fazla katman daha fazla karmaşıklık eklemek gerekebilir. Örneğin, benim app birkaç DİNLENME yanıtları kaybı olmayacaktır çünkü yerel depolama var; ben değil.

Benim yaklaşım altında AsyncTasks kapakları sadece kullanır. Benim durumumda, ben "Ara" bu Görevler benim Activity örnek; ama tam hesap için davalar gibi ekran döndürme olabilirsiniz seçim çağrısı onlardan bir Service ya da böyle.

Ben bilinçli olarak KALAN müvekkilim kendisini bir API olarak seçti. Bu benim geri KALANI istemci kullanan uygulama bile gerçek DİNLENME URL ve veri biçimi farkında olması gerekmez anlamına gelir.

İstemci 2 kat olurdu:

  1. Üst katman: bu katman amacı REST API işlevselliğini ayna hangi yöntemler sağlamaktır. Örneğin, bir Java yöntemi REST API (hatta iki Alır ve Mesajlar için) her URL için ilgili olabilir.
    Bu DİNLENME istemci API giriş noktasıdır. Bu uygulama normalde kullanmak istiyorsunuz tabakadır. Bir tek, ama ille de olabilir.
    Gerisini yanıt aramayı bir POJO içine bu katman tarafından ayrıştırılır ve uygulamaya döndürdü.

  2. Bu alt seviyesidir HTTP istemci yöntemleri aslında gidip DİNLENMEK arama yapmak için kullanır AsyncTask tabaka.

Ayrıca, AsyncTasks sonucu app iletişim kurmak için bir Geri dönüş mekanizması kullanmayı tercih ettim.

Metin yeter. Şimdi biraz kod bakın. Varsayımsal bir REST API - http://myhypotheticalapi.com/user/profile URL sağlar

Üst katmanı bu gibi görünebilir:

   /**
 * Entry point into the API.
 */
public class HypotheticalApi{   
    public static HypotheticalApi getInstance(){
        //Choose an appropriate creation strategy.
    }

    /**
     * Request a User Profile from the REST server.
     * @param userName The user name for which the profile is to be requested.
     * @param callback Callback to execute when the profile is available.
     */
    public void getUserProfile(String userName, final GetResponseCallback callback){
        String restUrl = Utils.constructRestUrlForProfile(userName);
        new GetTask(restUrl, new RestTaskCallback (){
            @Override
            public void onTaskComplete(String response){
                Profile profile = Utils.parseResponseAsProfile(response);
                callback.onDataReceived(profile);
            }
        }).execute();
    }

    /**
     * Submit a user profile to the server.
     * @param profile The profile to submit
     * @param callback The callback to execute when submission status is available.
     */
    public void postUserProfile(Profile profile, final PostCallback callback){
        String restUrl = Utils.constructRestUrlForProfile(profile);
        String requestBody = Utils.serializeProfileAsString(profile);
        new PostTask(restUrl, requestBody, new RestTaskCallback(){
            public void onTaskComplete(String response){
                callback.onPostSuccess();
            }
        }).execute();
    }
}


/**
 * Class definition for a callback to be invoked when the response data for the
 * GET call is available.
 */
public abstract class GetResponseCallback{

    /**
     * Called when the response data for the REST call is ready. <br/>
     * This method is guaranteed to execute on the UI thread.
     * 
     * @param profile The {@code Profile} that was received from the server.
     */
    abstract void onDataReceived(Profile profile);

    /*
     * Additional methods like onPreGet() or onFailure() can be added with default implementations.
     * This is why this has been made and abstract class rather than Interface.
     */
}

/**
 * 
 * Class definition for a callback to be invoked when the response for the data 
 * submission is available.
 * 
 */
public abstract class PostCallback{
    /**
     * Called when a POST success response is received. <br/>
     * This method is guaranteed to execute on the UI thread.
     */
    public abstract void onPostSuccess();

}

App JSON veya XML (veya herhangi bir diğer biçimi) geri KALAN API tarafından döndürülen doğrudan kullanmaz unutmayın. Bunun yerine, app sadece fasulye Profile görür.

Sonra, alt katman (AsyncTask katman) bu gibi görünebilir:

/**
 * An AsyncTask implementation for performing GETs on the Hypothetical REST APIs.
 */
public class GetTask extends AsyncTask<String, String, String>{

    private String mRestUrl;
    private RestTaskCallback mCallback;

    /**
     * Creates a new instance of GetTask with the specified URL and callback.
     * 
     * @param restUrl The URL for the REST API.
     * @param callback The callback to be invoked when the HTTP request
     *            completes.
     * 
     */
    public GetTask(String restUrl, RestTaskCallback callback){
        this.mRestUrl = restUrl;
        this.mCallback = callback;
    }

    @Override
    protected String doInBackground(String... params) {
        String response = null;
        //Use HTTP Client APIs to make the call.
        //Return the HTTP Response body here.
        return response;
    }

    @Override
    protected void onPostExecute(String result) {
        mCallback.onTaskComplete(result);
        super.onPostExecute(result);
    }
}

    /**
     * An AsyncTask implementation for performing POSTs on the Hypothetical REST APIs.
     */
    public class PostTask extends AsyncTask<String, String, String>{
        private String mRestUrl;
        private RestTaskCallback mCallback;
        private String mRequestBody;

        /**
         * Creates a new instance of PostTask with the specified URL, callback, and
         * request body.
         * 
         * @param restUrl The URL for the REST API.
         * @param callback The callback to be invoked when the HTTP request
         *            completes.
         * @param requestBody The body of the POST request.
         * 
         */
        public PostTask(String restUrl, String requestBody, RestTaskCallback callback){
            this.mRestUrl = restUrl;
            this.mRequestBody = requestBody;
            this.mCallback = callback;
        }

        @Override
        protected String doInBackground(String... arg0) {
            //Use HTTP client API's to do the POST
            //Return response.
        }

        @Override
        protected void onPostExecute(String result) {
            mCallback.onTaskComplete(result);
            super.onPostExecute(result);
        }
    }

    /**
     * Class definition for a callback to be invoked when the HTTP request
     * representing the REST API Call completes.
     */
    public abstract class RestTaskCallback{
        /**
         * Called when the HTTP request completes.
         * 
         * @param result The result of the HTTP request.
         */
        public abstract void onTaskComplete(String result);
    }

Bir uygulama API (Activity Service) kullanabilirsiniz:

HypotheticalApi myApi = HypotheticalApi.getInstance();
        myApi.getUserProfile("techie.curious", new GetResponseCallback() {

            @Override
            void onDataReceived(Profile profile) {
                //Use the profile to display it on screen, etc.
            }

        });

        Profile newProfile = new Profile();
        myApi.postUserProfile(newProfile, new PostCallback() {

            @Override
            public void onPostSuccess() {
                //Display Success
            }
        });

Yorum tasarımını açıklamak için yeterlidir umarım; ama daha fazla bilgi vermekten mutlu olurum.

Bunu Paylaş:
  • Google+
  • E-Posta
Etiketler:

YORUMLAR

SPONSOR VİDEO

Rastgele Yazarlar

  • BgirlNilaya

    BgirlNilaya

    29 EKİM 2008
  • fast2hell

    fast2hell

    16 AĞUSTOS 2006
  • MusicDeluxeTV

    MusicDeluxeT

    14 Mayıs 2010