Android非同步介面實現

來源:互聯網
上載者:User

標籤:

在使用非同步請求網路資料時,每次請求一個介面就定義一個非同步類,為避免其中一些多餘的步驟,採用將非同步類抽象出來

以下使用一個登陸介面來對比使用介面的前後,登陸使用post請求

    簡化前非同步實現:

class LoginAsyTask extends AsyncTask<Void, Integer, String>{
        @Override
        protected void onPreExecute() {
            super.onPreExecute();
        }
        
        @Override
        protected String doInBackground(Void... arg0) {

    //post請求的參數
            Map<String, String> params = new HashMap<String, String>();
            params.put("username", mEditUserName.getText().toString());
            params.put("password", mEditUserPwd.getText().toString());
            
            try {

      //發送請求,接受伺服器返回的字串
                return PostUtil.sendPostRequest(loginUrl,params);
            } catch (ClientProtocolException e) {
                e.printStackTrace();
            } catch (IOException e) {
                e.printStackTrace();
            }
            return null;
        }
        
        @Override
        protected void onPostExecute(String result) {
            if(result != null){
                JSONTokener jsonParser = new JSONTokener(result);  
                // 此時還未讀取任何json文本,直接讀取就是一個JSONObject對象。  
                JSONObject loginJSON;
                try {
                    loginJSON = (JSONObject) jsonParser.nextValue();
                    // 接下來的就是JSON對象的操作了 
                    loginJSON.getString("message");  
                    loginJSON.getInt("code");  
                    if(loginJSON.getInt("code") == 0){
                        Intent intent = new Intent(LoginActivity.this,MainActivity.class);
                        startActivity(intent);
                        Toast.makeText(LoginActivity.this, "登入成功", 0).show();
                    }else{
                        Toast.makeText(LoginActivity.this, "登入失敗", 0).show();
                    }
                } catch (JSONException e) {
                    // TODO Auto-generated catch block
                    e.printStackTrace();
                }
                LogUtil.e("login", result.toString());
            }
            super.onPostExecute(result);
        }
        
    }

 

 

  將非同步使用介面簡化後

首先定義一個介面,其中包括一個抽象的onPostExecute(Object object)方法

AsyncCallBack.Class

public interface AsyncCallBack {

    public void onPostExecute(Object object);
}

然後定義一個非同步抽象類別

public abstract class AbstractPostAsyncTask<Void, Progress, Result> extends AsyncTask<Void, Progress, Result>{

    private HttpUtil mHttpUtil;
    private Gson gson;
    private Class<Result> result;

    protected AsyncCallBack mAsyncCallBack;
    
    public AbstractPostAsyncTask(Class<Result> t, AsyncCallBack asyncCallBack) {
        this.mAsyncCallBack = asyncCallBack;
        this.result = t;
        this.gson = new Gson();
        this.mHttpUtil = new HttpUtil();
    }
    

    @Override
    protected Result doInBackground(Void... arg0) {
        String str = null;
        try {
            str = PostUtil.sendPostRequest(getRequestUrl(), getRequestParams());
            return parse(str, result);
        } catch (ClientProtocolException e) {
            e.printStackTrace();
        } catch (IOException e) {
            e.printStackTrace();
        }
        return null;
    }
    
    @Override
    protected void onPostExecute(Result result) {
        super.onPostExecute(result);
        this.mAsyncCallBack.onPostExecute(result);
    }
    
    
    private Result parse(String str, Class<Result> t) {
        Result result = null;
        ObjectMapper mapper = MapperUtil.getMapper();
        //解析Json資料為“申請”對象
        try {
            result = mapper.readValue(str,t);
        } catch (JsonParseException e) {
            e.printStackTrace();
        } catch (JsonMappingException e) {
            e.printStackTrace();
        } catch (IOException e) {
            e.printStackTrace();
        }
        return result;
    }
    
    protected abstract Map<String, String> getRequestParams();
    
    protected abstract String getRequestUrl();
}

最後在需要的地方實現這個抽象類別的抽象方法和AsyncCallBack介面中的onPostExecute(Object object)方法

    public class AllSitesAsyTask extends AbstractGetAsyncTask<Void, Void, SiteJSON> {
        
        @Override
        protected void onPreExecute() {
            super.onPreExecute();
        }

        public AllSitesAsyTask(Class<LOGINJSON> t, AsyncCallBack asyncCallBack) {
            super(t, asyncCallBack);
        }

        @Override
        public String getRequestUrl() {
            return Constants.LOGIN_URL;
        }
    }

實現非同步執行

  AllSitesAsyTask allSitesAsyTask = new AllSitesAsyTask(SiteJSON.class, new AsyncCallBack() {
    @Override
    public void onPostExecute(Object object) {
      setAllStationToList(object);
      progressDialog.dismiss();
    }             
  });
  allSitesAsyTask.execute();

 

使用到的PostUtil工具類,用來請求post資料

public class PostUtil {
    
    /**
     *
     * @param params 參數數組
     * @return
     */
    public static String sendPostRequest(String url, Map<String, String> params) throws ClientProtocolException, IOException {
        DefaultHttpClient  httpclient = new DefaultHttpClient();
        HttpPost httpPost = new HttpPost(url);
        
        List<NameValuePair> pairs = new ArrayList<NameValuePair>();                    //存放請求參數
        if(params != null && !params.isEmpty()){
            for(Map.Entry<String, String> entry : params.entrySet()) {
                pairs.add(new BasicNameValuePair(entry.getKey(), entry.getValue()));
            }
        }
        UrlEncodedFormEntity entity = new UrlEncodedFormEntity(pairs, HTTP.UTF_8);
        httpPost.setEntity(entity);
        HttpResponse response = httpclient.execute(httpPost);  
        if (response.getStatusLine().getStatusCode() == HttpURLConnection.HTTP_OK){  
            return EntityUtils.toString(response.getEntity());  
        }
        return null;
    }
    
}

Android非同步介面實現

聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在5個工作日內處理。

如果您發現本社區中有涉嫌抄襲的內容,歡迎發送郵件至: info-contact@alibabacloud.com 進行舉報並提供相關證據,工作人員會在 5 個工作天內聯絡您,一經查實,本站將立刻刪除涉嫌侵權內容。

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.