Android之使用Android-query框架進行開發

https://code.google.com/p/android-query/


第一節: 

複製代碼
  // 必須實現AQuery這個類

AQuery aq = new AQuery(view);
// 按順序分析:取得xml對應控件id,設置圖片,設置可以顯示,點擊事件(方法someMethod必須是public修飾)    

aq.id(R.id.icon).image(R.drawable.icon).visible().clicked(this, "someMethod");  
// 設置文字內容
        aq.id(R.id.name).text(content.getPname());
        aq.id(R.id.time).text(FormatUtility.relativeTime(System.currentTimeMillis(), content.getCreate())).visible();

aq.id(R.id.desc).text(content.getDesc()).visible();  

複製代碼

          

 AQuery也支持Fragment:

複製代碼
    @Override
    public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
        
        View view = inflater.inflate(getContainerView(), container, false);             
                
        aq = new AQuery(getActivity(), view);
        return view;
  }              
複製代碼

     

第二節: 使用AQuery異步加載圖片

2.1 從網上讀取圖片

aq.id(R.id.image1).image(“圖片URL”); 

 

2.2 緩存控制:  圖片過大的話,避免記憶緩存

boolean memCache = false;

     boolean fileCache = true;

     aq.id(R.id.image1).image("http://www.vikispot.com/z/images/vikispot/android-w.png", memCache, fileCache);
2.3 當下載太多圖片的時候需要降低圖片採樣率,第四個參數爲了保證圖片質量,一般範圍時200-399
   aq.id(R.id.image1).image(imageUrl, true, true, 200, 0);
2.4 如果下載圖片失敗,處理的方法:1. 設置一個預定的圖片  2. 使imageview不可見或者是gone
     aq.id(R.id.image1).image(imageUrl, true, true, 0, R.drawable.default_image);
     aq.id(R.id.image1).image(imageUrl, true, true, 0, AQuery.INVISIBLE);
     aq.id(R.id.image1).image(imageUrl, true, true, 0, AQuery.GONE);

2.5 圖片預加載
    // 從之前的url取得小圖片
     String thumbnail = "http://farm6.static.flickr.com/5035/5802797131_a729dac808_s.jpg";   
     Bitmap preset = aq.getCachedImage(thumbnail);
    // 加載大圖片前先顯示小圖片
     String imageUrl = "http://farm6.static.flickr.com/5035/5802797131_a729dac808_b.jpg";            
    aq.id(R.id.image).image(imageUrl, false, false, 0, 0, preset, AQuery.FADE_IN);
2.6 在加載圖片的時候顯示進度條,progress裏面傳入id
    String imageUrl = "http://farm6.static.flickr.com/5035/5802797131_a729dac808_b.jpg";            
     aq.id(R.id.image).progress(R.id.progress).image(imageUrl, false, false);
2.7 圖片圓角顯示,不支持大圖片
     ImageOptions options = new ImageOptions();
     options.round = 15;
     aq.id(R.id.image).image(url, options);
2.8 圖片長寬比例    
    // 保留原圖片比例
    aq.id(R.id.image).image(imageUrl, true, true, 0, 0, null, AQuery.FADE_IN, AQuery.RATIO_PRESERVE);
    // 自定義圖片比例
    //1:1, a square 
    aq.id(R.id.image2).image(imageUrl, true, true, 0, 0, null, 0, 1.0f / 1.0f);             
    aq.id(R.id.image3).image(imageUrl, true, true, 0, 0, null, 0, 1.5f / 1.0f);     
    //16:9, a video thumbnail
    aq.id(R.id.image4).image(imageUrl, true, true, 0, 0, null, 0, 9.0f / 16.0f);    
    aq.id(R.id.image5).image(imageUrl, true, true, 0, 0, null, 0, 3.0f / 4.0f);
2.9 圖片描點,如果圖片過高,描點可用來描述圖片的哪一部分用於顯示
    Anchor values:
1.0 : Display top of the image
0 : Display the center of the image
-1.0 : Display bottom of the image
AQuery.ANCHOR_DYNAMIC : Display image with a top bias for photos.
=======================================================
	ImageOptions options = new ImageOptions();
	options.ratio = 1;
	options.anchor = 1.0;
	aq.id(R.id.image1).image(imageUrl, options);
2.10 自定義圖片加載後的處理
    aq.id(R.id.image1).image(imageUrl, true, true, 0, 0, new BitmapAjaxCallback(){});
2.11 異步從文件加載圖片,建議使用降低採樣率避免oom
    File file = new File(path);        
   //load image from file, down sample to target width of 300 pixels  
   aq.id(R.id.avatar).image(file, 300);
   //load image from file with callback
   aq.id(R.id.avatar).image(file, false, 300, new BitmapAjaxCallback(){
    @Override
    public void callback(String url, ImageView iv, Bitmap bm, AjaxStatus status){
        iv.setImageBitmap(bm);
	}
});
2.12 如果之前image("url")已經成功,之後的都可以直接使用而不需要重新訪問網絡,也就是說之後可以離線訪問此圖像資源
2.13 文件中獲取緩衝圖片
     File file = aq.getCachedFile(url);
2.14 除了imageview,webview也可以用來放圖片
     aq.id(R.id.web).progress(R.id.progress).webImage(url);
2.15 延遲圖片加載,幫助你是否加載正在快速滾動的listview,詳情參考文檔使用
2.16 圖片不使用緩存
     aq.id(R.id.image).image(url, false, false);
2.17 緩存配置,緩存一般是保存在內部文件系統,但也可以保存在SDCard裏面
      File ext = Environment.getExternalStorageDirectory();
      File cacheDir = new File(ext, "myapp"); 
      AQUtility.setCacheDir(cacheDir);
2.18 共享圖片,爲了與其他程序共享圖片,你需要把文件放在SDCard,makeSharedFile方法創建緩存地址的一個副本
      File file = aq.makeSharedFile(url, "android.png");
         if(file != null){
                Intent intent = new Intent(Intent.ACTION_SEND);
                intent.setType("image/jpeg");
                intent.putExtra(Intent.EXTRA_STREAM, Uri.fromFile(file));
                startActivityForResult(Intent.createChooser(intent, "Share via:"), SEND_REQUEST);
        }
2.19 配置,最好把配置寫在application的onCreate方法,詳細參考文檔
2.20 程序退出時候需要把緩存清除
      if(isTaskRoot()){
	  AQUtility.cleanCacheAsync(this);
	}
或者: if(isTaskRoot()){
	//clean the file cache with advance option
        long triggerSize = 3000000; //大於3M時候開始清除
        long targetSize = 2000000;      //直到少於2M
        AQUtility.cleanCacheAsync(this, triggerSize, targetSize);
        }
2.21 低內存處理
      public class MainApplication extends Application{
          @Override
         public void onLowMemory(){  
        //clear all memory cached images when system is in low memory
        //note that you can configure the max image cache count, see CONFIGURATION
         BitmapAjaxCallback.clearCache();
	}
}

異步網絡:

1. 添加權限:<uses-permission android:name="android.permission.INTERNET" />  

2. 支持的類型

JSONObject
JSONArray
String (HTML, XML)
XmlDom (XML parsing)
XmlPullParser (Large XML files)
byte array
User defined custom type (Transformer)

Bitmap 

3. 以Json數據爲例,注意,紅色部分是隨你請求的數據類型一起改變

複製代碼
String url = "http://www.google.com/uds/GnewsSearch?q=Obama&v=1.0";                  aq.ajax(url, JSONObject.classnew AjaxCallback<JSONObject>() {                 @Override                 public void callback(String url, JSONObject json, AjaxStatus status) {                                                  if(json != null){                                 //successful ajax call, show status code and json content                                 Toast.makeText(aq.getContext(), status.getCode() + ":" + json.toString(), Toast.LENGTH_LONG).show();                                                  }else{                                 //ajax error, show error code                                 Toast.makeText(aq.getContext(), "Error:" + status.getCode(), Toast.LENGTH_LONG).show();                         }                 }

});  

複製代碼

        

上面的形式也可以寫成下面一樣,他們是無條件對等 

複製代碼
public void asyncJson(){                  //perform a Google search in just a few lines of code                  String url = "http://www.google.com/uds/GnewsSearch?q=Obama&v=1.0";                      aq.ajax(url, JSONObject.classthis, "jsonCallback");          } public void jsonCallback(String url, JSONObject json, AjaxStatus status){                  if(json != null){                                //successful ajax call                   }else{                           //ajax error         } }         
複製代碼

再舉一個使用AQuery的XmlDom解析xml的例子,如果XML過大,使用XMLPullParser

複製代碼
public void xml_ajax(){                  String url = "https://picasaweb.google.com/data/feed/base/featured?max-results=8";                       aq.ajax(url, XmlDom.classthis, "picasaCb");            } public void picasaCb(String url, XmlDom xml, AjaxStatus status){ // 返回一系列爲entry的結點,並把其add進list         List<XmlDom> entries = xml.tags("entry");                        List<String> titles = new ArrayList<String>();                  String imageUrl = null;                  for(XmlDom entry: entries){                 titles.add(entry.text("title")); //循環把第一個結點爲title的文本放進title                 imageUrl = entry.tag("content", "type", "image/jpeg").attr("src");//把第一個結點爲content,屬性爲type,屬性值爲image/jpeg的src屬性值賦予給imageUri         }                          aq.id(R.id.image).image(imageUrl); }         
複製代碼

4. 如果你想指定保存文件的位置,使用download方法

String url = "https://picasaweb.google.com/data/feed/base/featured?max-results=16";             

File ext = Environment.getExternalStorageDirectory();
File target = new File(ext, "aquery/myfolder/photos.xml");              

aq.progress(R.id.progress).download(url, target, new AjaxCallback<File>(){
        
        public void callback(String url, File file, AjaxStatus status) {
                
                if(file != null){
                        showResult("File:" + file.length() + ":" + file, status);
                }else{
                        showResult("Failed", status);
                }
        }
   }); 

5. 自定義類型(文檔例子是gson數據使用對象解析),詳細見文檔 

 

6. 使用Http Post (Multiple)

private void aync_multipart(){

        
        String url = "https://graph.facebook.com/me/photos";
        
        Map<String, Object> params = new HashMap<String, Object>();
        params.put("message", "Message");
        
        //Simply put a byte[] to the params, AQuery will detect it and treat it as a multi-part post
        byte[] data = getImageData();
        params.put("source", data);
        
        //Alternatively, put a File or InputStream instead of byte[]
        //File file = getImageFile();           
        //params.put("source", file);
        
        AQuery aq = new AQuery(getApplicationContext());
        aq.auth(handle).ajax(url, params, JSONObject.class, this, "photoCb");
        
}
7. 使用ajax是很容易達到緩存的
String url = "http://www.google.com";

// 返回最近15分鐘內的緩存副本,如果expire爲-1,內容將會立即更新且緩存
long expire = 15 * 60 * 1000;

aq.ajax(url, String.class, expire, new AjaxCallback<String>() {

    @Override
    public void callback(String url, String html, AjaxStatus status) {        
        showResult(html);
    }
        
});
8. 使緩存無效
public void callback(String url, JSONObject json, AjaxStatus status) {
    
        if(json != null){
                if("1".equals(json.optString("status"))){
                        //do something
                }else{
                        // 不緩存
                        status.invalidate();
                }
        }
}
9. 同步調用:如果ajax調用是在新開的線程,sync方法能夠阻塞線程,直到ajax調用完畢,如果sync方法用在主線程將會引起Exception
String url = "http://www.google.com/uds/GnewsSearch?q=Obama&v=1.0";
        
AjaxCallback<JSONObject> cb = new AjaxCallback<JSONObject>();           
cb.url(url).type(JSONObject.class);             
        
aq.sync(cb);
        
JSONObject jo = cb.getResult();
AjaxStatus status = cb.getStatus();

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章