开源项目之Android框架(Query)

使用Android-query框架能够快速开发Android,比传统开发android所要编写的代码要少得很多,容易阅读等优势。        

下面开认识一下该项目,项目如图:

  

根据项目名称就知道它的意思了,框架、实例、测试功能!

AndroidQuery 一个轻量级的库,用于实现 Android 上的异步任务和操作 UI 元素。

项目含有26 个文件源文件,分析如下:

auth含有:

public class WebDialog extends Dialog  对话框显示网页信息 

public class BasicHandle extends AccountHandle  本地帐号用户认证(Base64Coder编解码)

public class FacebookHandle extends AccountHandle    Facebook帐号用户认证(Base64Coder编解码)

public class TwitterHandle extends AccountHandle    Twitter帐号用户认证(Base64Coder编解码)

public class GoogleHandle extends AccountHandle implements DialogInterface.OnClickListener, OnCancelListener  Google帐号用户认证(Base64Coder编解码)


public class LocationAjaxCallback extends
AbstractAjaxCallback<Location, LocationAjaxCallback>   //本地位置信息回调 封装了本地手机gps、network确认手机位置信息 然后返回最新位置信息

public abstract class AbstractAQuery<T extends AbstractAQuery<T>> implements Constants  模块类,含有AQuery所有方法。

主要方法如:

public T find(int id) //查找根容器

public T parent(int id) //返回id容器的父容器

public T recycle(View root)  //回收

public T id(int id) //返回id容器

public T auth(AccountHandle handle)  //Ajax请求进行身份验证

public T transformer(Transformer transformer)  //Ajax请求所需的对象类型转换

……图片处理、下载、以及相关控件的方法操作!

public class AQuery extends AbstractAQuery<AQuery> //主要类,实现上面的模版类

public abstract class AbstractAjaxCallback<T, K> implements Runnable   //封装Ajax请求、回调

public class AjaxStatus  //记录ajax请求的状态信息 如头信息、cookies 等

public class BitmapAjaxCallback extends AbstractAjaxCallback<Bitmap, BitmapAjaxCallback>   //封装ajax请求图片

public class AQUtility  //封装了特效方法

public class BitmapCache extends LinkedHashMap<String, Bitmap>  //图片缓冲  使用哈希管理

public class Common implements Comparator<File>, Runnable, OnClickListener, OnLongClickListener, OnItemClickListener, OnScrollListener, OnItemSelectedListener, TextWatcher  //仅供内部使用。一个共享的监听器类,以减少类的数量。

public class PredefinedBAOS extends ByteArrayOutputStream  //管理缓冲流   返回流

public class Progress implements Runnable  //进度条管理

public class RatioDrawable extends BitmapDrawable  //图片

public class WebImage extends WebViewClient  //web图片

public class XmlDom  //XML解析


AndroidQuery 介绍完毕,那来看下是如何测试的。

public abstract class AbstractTest<T extends Activity> extends ActivityInstrumentationTestCase2<T>  //初始化Activity、释放缓冲

关键方法如:

	protected void setUp() throws Exception { //
        super.setUp();
        aq = new AQuery(getActivity());
        AQUtility.debug("new act", getActivity() + ":" + getActivity().isFinishing());
    }
	protected void clearCache(){  //清除缓冲
		
		BitmapAjaxCallback.clearCache();
		
		File cacheDir = AQUtility.getCacheDir(getActivity());
		AQUtility.cleanCache(cacheDir, 0, 0);
		
		waitSec(2000);
	}

public class AQueryAsyncTest extends AbstractTest<AQueryTestActivity>  //测试同步ajax请求

主要方法:

	//Test: <K> T ajax(String url, Map<String, Object> params, Class<K> type, AjaxCallback<K> callback)
	public void testAjaxPost(){  //测试ajax Post请求
		
        String url = "http://search.twitter.com/search.json";
		
        Map<String, String> params = new HashMap<String, String>();
		params.put("q", "androidquery");
		
        aq.ajax(url, params, JSONObject.class, new AjaxCallback<JSONObject>() {

            @Override
            public void callback(String url, JSONObject jo, AjaxStatus status) {
                   
            	done(url, jo, status);
               
            }
        });
        
        waitAsync();
		
        JSONObject jo = (JSONObject) result;
        assertNotNull(jo);       
        assertNotNull(jo.opt("results"));
        
	}
	// Test: public <K> T ajax(String url, Class<K> type, long expire,
	// AjaxCallback<K> callback)
	public void testAjaxCache() {  //ajax缓冲

		String url = "http://www.google.com/uds/GnewsSearch?q=Obama&v=1.0";

		AjaxCallback<JSONObject> cb = new AjaxCallback<JSONObject>() {

			@Override
			public void callback(String url, JSONObject jo, AjaxStatus status) {

				done(url, jo, status);

			}

		};

		aq.ajax(url, JSONObject.class, 15 * 60 * 1000, cb);

		waitAsync(2000);

		JSONObject jo = (JSONObject) result;

		assertNotNull(jo);
		assertNotNull(jo.opt("responseData"));

		File cached = aq.getCachedFile(url);
		assertTrue(cached.exists());
		assertTrue(cached.length() > 100);

	}
	public void testAjaxLongBitmapURL() { //加载大图片

		String dummy = "Lorem ipsum dolor sit amet, consectetur adipisicing elit, sed do eiusmod tempor incididunt ut labore et dolore magna aliqua. Ut enim ad minim veniam, quis nostrud exercitation ullamco laboris nisi ut aliquip ex ea commodo consequat. Duis aute irure dolor in reprehenderit in voluptate velit esse cillum dolore eu fugiat nulla pariatur. Excepteur sint occaecat cupidatat non proident, sunt in culpa qui officia deserunt mollit anim id est laborum.";

		String title = "Very long title " + dummy + dummy + dummy + dummy
				+ dummy;

		AQUtility.debug("title len", title.length());

		String url = "https://chart.googleapis.com/chart?chid=1234&cht=lc&chtt="
				+ title + "&chs=300x200&chxt=x&chd=t:40,20,50,20,100";

		AjaxCallback<Bitmap> cb = new AjaxCallback<Bitmap>() {

			@Override
			public void callback(String url, Bitmap bm, AjaxStatus status) {

				done(url, bm, status);

			}

		};

		aq.ajax(url, Bitmap.class, 15 * 60 * 1000, cb);

		waitAsync(2000);

		assertNotNull(result);

		File cached = aq.getCachedFile(url);
		assertTrue(cached.exists());
		assertTrue(cached.length() > 100);

	}
public void testAjaxPostMultiFile() throws IOException {  //Post 多文件下载

		String url = "http://www.androidquery.com/p/multipart";

		Map<String, Object> params = new HashMap<String, Object>();

		File tempFile1 = File.createTempFile("pre1", "bin");
		File tempFile2 = File.createTempFile("pre2", "bin");

		byte[] data1 = new byte[1234];
		byte[] data2 = new byte[2345];

		AQUtility.write(tempFile1, data1);
		AQUtility.write(tempFile2, data2);

		// byte[] data2 = new byte[2345];

		// params.put("data", data);
		// params.put("data2", data2);

		params.put("data", tempFile1);
		params.put("data2", tempFile2);

		aq.ajax(url, params, JSONObject.class, new AjaxCallback<JSONObject>() {

			@Override
			public void callback(String url, JSONObject jo, AjaxStatus status) {

				AQUtility.debug(status.getCode(), status.getError());

				AQueryAsyncTest.this.result = jo;
			}
		});

		waitAsync();

		JSONObject jo = (JSONObject) result;

		AQUtility.debug(jo);

		assertNotNull(jo);

		assertEquals(1234, jo.optInt("data"));
		assertEquals(2345, jo.optInt("data2"));
	}
……等等。

public class AQueryAuthTest extends AbstractTest<AQueryTestActivity>  //测试身份认证

主要方法:

	public void testBasicAuthHandle() {  //认证测试
		
		BasicHandle handle = new BasicHandle("tinyeeliu@gmail.com", "password");
		
		String url = "http://xpenser.com/api/v1.0/reports/";
		
		aq.auth(handle).ajax(url, JSONArray.class, this, "basicCb");
		
        waitAsync();
        
        JSONArray jo = (JSONArray) result;
        
        AQUtility.debug(jo);
        
        assertNotNull(jo);       
        
    }

public class AQueryImageTest extends AbstractTest<AQueryTestActivity>  //图片操作测试

主要方法:

	public void testImageBasicUrl() {  //图片

		clearCache();

		AQUtility.post(new Runnable() {

			@Override
			public void run() {
				aq.id(R.id.image).image(ICON_URL);
			}
		});

		waitAsync(2000);

		assertLoaded(aq.getImageView(), true);

		Bitmap bm = aq.getCachedImage(ICON_URL);

		assertNotNull(bm);

		File file = aq.getCachedFile(ICON_URL);
		assertNotNull(file);

	}
public void testImageNoCache() { //无缓存下载图片

		clearCache();

		AQUtility.post(new Runnable() {

			@Override
			public void run() {
				aq.id(R.id.image).image(ICON_URL, false, false);
			}
		});

		waitAsync(2000);

		assertLoaded(aq.getImageView(), true);

		Bitmap bm = aq.getCachedImage(ICON_URL);
		assertNull(bm);

		File file = aq.getCachedFile(ICON_URL);
		assertNull(file);

	}
	public void testImageFileWithCallback() {  //

		clearCache();

		prefetchFile();

		AQUtility.post(new Runnable() {

			@Override
			public void run() {
				File file = aq.getCachedFile(LAND_URL);
				aq.id(R.id.image2).image(file, true, 200,
						new BitmapAjaxCallback() {
							@Override
							protected void callback(String url, ImageView iv,
									Bitmap bm, AjaxStatus status) {
								iv.setImageBitmap(bm);
								assertNotNull(bm);
							}
						});
			}
		});

		assertLoaded(aq.getImageView(), true);

	}
public class AQueryLocationTest extends AbstractTest<AQueryTestActivity> //位置信息测试

	public void testLocationIter3Acc10000() {

		LocationAjaxCallback cb = new LocationAjaxCallback() {

			private int n;

			@Override
			public void callback(String url, Location loc, AjaxStatus status) {

				n++;

				AQUtility.debug(n);
				AQUtility.debug(loc);

				assertNotNull(loc);

				if (n == 3) {
					assertEquals("gps", loc.getProvider());
				}

			}
		};
		cb.timeout(30 * 1000).accuracy(10000).iteration(3).tolerance(-1);
		cb.async(getActivity());

		waitAsync(5000);

	}

	public void testLocationIter2Acc10000() { //位置测试
		LocationAjaxCallback cb = new LocationAjaxCallback() {

			private int n;

			@Override
			public void callback(String url, Location loc, AjaxStatus status) {

				n++;

				AQUtility.debug(n);
				AQUtility.debug(loc);

				assertNotNull(loc);

				if (n == 2) {
					assertEquals("gps", loc.getProvider());
				}

			}
		};
		cb.timeout(30 * 1000).accuracy(10000).iteration(2).tolerance(-1);
		cb.async(getActivity());

		waitAsync(5000);

	}

	public void testLocationIter1Acc10000() {

		LocationAjaxCallback cb = new LocationAjaxCallback() {

			private int n;

			@Override
			public void callback(String url, Location loc, AjaxStatus status) {

				n++;

				AQUtility.debug(n);
				AQUtility.debug(loc);

				assertNotNull(loc);

				if (n == 1) {
					assertEquals("gps", loc.getProvider());
				}

			}
		};
		cb.timeout(5 * 1000).accuracy(10000).iteration(1).tolerance(-1);
		cb.async(getActivity());

		waitAsync(5000);

	}

	public void testLocationIter2AccFail() {

		LocationAjaxCallback cb = new LocationAjaxCallback() {

			private int n;

			@Override
			public void callback(String url, Location loc, AjaxStatus status) {

				n++;

				AQUtility.debug(n);
				AQUtility.debug(loc);

				if (n == 2) {
					assertNull(loc);
					assertEquals(AjaxStatus.TRANSFORM_ERROR, status.getCode());
				} else if (n < 2) {
					assertNotNull(loc);
				} else {
					assertTrue(false);
				}

			}
		};

		cb.timeout(5 * 1000).accuracy(-1).iteration(2).tolerance(-1);
		cb.async(getActivity());

		waitAsync(6000);

	}
public class AQueryMiscTest extends AbstractTest<AQueryTestActivity>   //缓冲文件

	public void testTempFile() {
		
		
		clearCache();
		
		AQUtility.post(new Runnable() {
			
			@Override
			public void run() {
				aq.id(R.id.image).image(ICON_URL);
			}
		});
		
		waitAsync(2000);
		
		assertNotNull(aq.getImageView().getDrawable());
		
		File file = aq.getCachedFile(ICON_URL);
		assertNotNull(file);
		
		AQUtility.time("move");
		
		File temp = aq.makeSharedFile(ICON_URL, "hello.png");
		
		AQUtility.timeEnd("move", 0);
		
		assertTrue(temp.exists());	
		assertTrue(temp.length() > 1000);
		assertTrue(temp.getName().equals("hello.png"));
		
		clearCache();
		
		assertFalse(temp.exists());
		
		
		File ghost = aq.getCachedFile("http://www.abc.com");
		assertNull(ghost);
		
    }
public class AQueryXmlTest extends AbstractTest<AQueryTestActivity> //测试解析xml

	public void testText2(){
		
		assertEquals("https://picasaweb.google.com/data/feed/base/featured", xml.text("id"));
		assertEquals("EricJamesPhoto_10.jpg", xml.child("entry").text("title"));
	}
	
	public void testAttr(){
		
		assertEquals("application/atom+xml", xml.child("link").attr("type"));
	}
	
	public void testToString() throws SAXException{
		
		InputStream is = this.getActivity().getResources().openRawResource(R.raw.colors);
		xml = new XmlDom(is);
		
		assertTrue(xml.toString().length() > 300);
		
	}
public class IOUtility  //测试打开网络文件

	public static byte[] openHttpResult(String urlPath, boolean retry) throws IOException{
		
		AQUtility.debug("net", urlPath);
		
		URL url = new URL(urlPath);
        HttpURLConnection connection = (HttpURLConnection) url.openConnection();
              
        
        connection.setUseCaches(false);
        connection.setInstanceFollowRedirects(true);     
        connection.setConnectTimeout(NET_TIMEOUT);
        
        
        int code = connection.getResponseCode();
       
        if(code == 307 && retry){
        	String redirect = connection.getHeaderField("Location");
        	return openHttpResult(redirect, false);
        }
        
        if(code == -1 && retry){
        	return openHttpResult(urlPath, false);
        }
        
        AQUtility.debug("response", code);
        
        
        if(code == -1 || code < 200 || code >= 300){
        	
        	throw new IOException();
        }
        
        
        byte[] result = AQUtility.toBytes(connection.getInputStream());
        return result;
	}
	
	public static String openString(String urlPath) throws IOException{
		
		byte[] bytes = openBytes(urlPath);		
		return new String(bytes, "UTF-8");
		
	}


看一下它的一个demo:

一:

aq = new AQuery(this);

		AjaxCallback.setReuseHttpClient(false);
		// aq.id(R.id.text).text("point 1");

		try {
			/*
			 * String url =
			 * "http://farm6.static.flickr.com/5035/5802797131_a729dac808_b.jpg"
			 * ;
			 * 
			 * aq.id(new ImageView(this)).image(url, false, true, 200, 0, new
			 * BitmapAjaxCallback(){
			 * 
			 * protected void callback(String url, ImageView iv, Bitmap bm,
			 * AjaxStatus status) { AQUtility.debug(bm.getWidth()); }
			 * 
			 * });
			 */

			AQUtility.setDebug(true);
			final ProgressDialog dialog = new ProgressDialog(this);
			dialog.setIndeterminate(true);
			dialog.setCancelable(true);
			dialog.setInverseBackgroundForced(false);
			dialog.setCanceledOnTouchOutside(true);
			dialog.setTitle("Sending...");

			Button button = (Button) findViewById(R.id.button);
			button.setOnClickListener(new OnClickListener() {
				public void onClick(View v) {
					String url = "http://sssprog.ru";
					final int num = number;
					number++;

					Log.d("sss", "loading started " + num);

					aq.progress(dialog).ajax(url, String.class, new

					AjaxCallback<String>() {

						@Override
						public void callback(String url, String html,
								AjaxStatus status) {
							Log.i("sss",
									"ajax loaded " + num + "   "
											+ status.getCode() + "  " + url);
							Log.i("sss", "Res: " + html);
						}
					});
				}
			});
		} catch (Exception e) {
			e.printStackTrace();
		}

二:

		//11-16 22:38:26.449: W/AQuery(18289): preset:http://graph.facebook.com/1281625122/picture
		AQUtility.cleanCache(AQUtility.getCacheDir(this, AQuery.CACHE_DEFAULT), 0, 0);
		BitmapAjaxCallback.clearCache();

		String pic = "http://graph.facebook.com/1281625122/picture";
		
		aq.id(R.id.image1).image(pic);
		aq.id(R.id.image2).image(pic);

三:

if(!init){
			AQUtility.setDebug(true);
			AQUtility.setCacheDir(null);
			BitmapAjaxCallback.setPixelLimit(600 * 600);
			BitmapAjaxCallback.setCacheLimit(100);
			BitmapAjaxCallback.setMaxPixelLimit(5000000);
			init = true;
			ErrorReporter.installReporter(getApplicationContext());
		}
		
		super.onCreate(savedInstanceState);
		
		type = getIntent().getStringExtra("type");
		
		
		aq = new AQuery(this);		
		setContentView(R.layout.empty_list);
		aq.id(android.R.id.list).adapter(getAA()).itemClicked(this, "itemClicked");
		
		if(type == null && debug){
			forward();
		}

		
		if(isTaskRoot()){			
			MarketService ms = new MarketService(this);
			ms.level(MarketService.MINOR).checkVersion();
		}

四:

	private void setupTest() {  //初始化

		AQUtility.setDebug(true);

		aq = new AQuery(this);

		aq.id(R.id.image1).text("Hihi");

		aq.id(R.id.clicked1).clicked(this, "clicked1");

		aq.id(R.id.clicked2).clicked(new OnClickListener() {

			@Override
			public void onClick(View v) {
				TestUtility.showToast(ListenerTestActivity.this, "pass");
			}
		});

		aq.id(R.id.image_reload).clicked(this, "reloadImage");

		aq.id(R.id.image_clear_mem).clicked(this, "clearMem");
		aq.id(R.id.image_clear_disk).clicked(this, "clearDisk");

		aq.id(R.id.async_bytes).clicked(this, "asyncBytes");
		aq.id(R.id.async_json).clicked(this, "asyncJson");

		aq.id(R.id.async_bad_json).clicked(this, "asyncBadJson");

		aq.id(R.id.async_bm).clicked(this, "asyncBitmap");
		aq.id(R.id.async_html).clicked(this, "asyncHtml");

		aq.id(R.id.async_post).clicked(this, "asyncPost");

		loadImage();
	}

	public void asyncPost() {

		// String url = "http://www.google.com/uds/GnewsSearch";
		String url = "http://www.vikispot.com/api/likes";

		Map<String, Object> params = new HashMap<String, Object>();
		params.put("spotId", "1677246");

		aq.ajax(url, params, JSONObject.class, this, "jsonCallback");

	}
五:

		if(AQuery.SDK_INT >= 9 && TestUtility.isTestDevice(this)) {  //初始化
			AQUtility.debug("enable strict mode!");
			
	         StrictMode.setThreadPolicy(new StrictMode.ThreadPolicy.Builder()
             .detectAll()
             .penaltyLog()
             .build());
	         
	         StrictMode.setVmPolicy(new StrictMode.VmPolicy.Builder()
             .detectAll()
             .penaltyLog()
             //.penaltyDeath()
             .build());
	    }

六:

	
	public static void flurryStart(Context context){
		
		if(!isTestDevice(context)){
			FlurryAgent.onStartSession(context, "D29A1QDKNZEIYFJBKXNR");
		}
	}
	
	public static void flurryEvent(Context context, String name){
		
		if(!isTestDevice(context)){
			try{
				FlurryAgent.onEvent(name, null);
			}catch(Exception e){
				e.printStackTrace();
			}
		}
	}
	
	public static void flurryStop(Context context){
		if(!isTestDevice(context)){
			FlurryAgent.onEndSession(context);
		}
	}
	
	public static boolean isEmulator(){
		return "sdk".equals(Build.PRODUCT);
	}
	

	private static String[] deviceIds = {"ffffffff-b588-0cd1-ffff-ffffb12a7939", "00000000-582e-8c83-ffff-ffffb12a7939", "ffffffff-a7af-71df-0033-c5870033c587", "00000000-2e56-36d7-ffff-ffffb12a7939", "ffffffff-b588-0cd1-ae81-42290033c587"};
	private static Boolean testDevice;
	
	public static boolean isTestDevice(Context context){
		
		if(testDevice == null){
			testDevice = isTestDevice(getDeviceId(context));
		}
		
		return testDevice;
	}
	
	private static boolean isTestDevice(String deviceId){
		
		for(int i = 0; i < deviceIds.length; i++){
			if(deviceIds[i].equals(deviceId)){
				return true;
			}
		}
		return false;
	}
	
	
	private static String deviceId;
	public static String getDeviceId(Context context){
		
		if(deviceId == null){
		
			TelephonyManager tm = (TelephonyManager) context.getSystemService(Context.TELEPHONY_SERVICE);
	
		    String tmDevice, tmSerial, tmPhone, androidId;
		    tmDevice = "" + tm.getDeviceId();
		    tmSerial = "" + tm.getSimSerialNumber();
		    androidId = "" + android.provider.Settings.Secure.getString(context.getContentResolver(), android.provider.Settings.Secure.ANDROID_ID);
	
		    UUID deviceUuid = new UUID(androidId.hashCode(), ((long)tmDevice.hashCode() << 32) | tmSerial.hashCode());
		    deviceId = deviceUuid.toString();
		    
		    System.err.println(deviceId);
		}
	    return deviceId;
	}

七:

public void auth_facebook() {//身份认证


		FacebookHandle handle = new FacebookHandle(this, APP_ID, PERMISSIONS) {

			@Override
			public boolean expired(AbstractAjaxCallback<?, ?> cb,
					AjaxStatus status) {

				// custom check if re-authentication is required
				if (status.getCode() == 401) {
					return true;
				}

				return super.expired(cb, status);
			}

		};

		String url = "https://graph.facebook.com/me/feed";
		aq.auth(handle).progress(R.id.progress)
				.ajax(url, JSONObject.class, this, "facebookCb");

	}
public void auth_twitter() {   //身份认证

		TwitterHandle handle = new TwitterHandle(this, CONSUMER_KEY,
				CONSUMER_SECRET);

		String url = "http://twitter.com/statuses/mentions.json";
		aq.auth(handle).progress(R.id.progress)
				.ajax(url, JSONArray.class, this, "twitterCb");

	}
八:

public void async_json() {  //同步json分析

		// AjaxCallback.setSSF(SSLSocketFactory.getSocketFactory());

		String url = "http://www.google.com/uds/GnewsSearch?q=Obama&v=1.0";

		AjaxCallback<JSONObject> cb = new AjaxCallback<JSONObject>() {

			@Override
			public void callback(String url, JSONObject json, AjaxStatus status) {

				showResult(json, status);

			}
		};

		cb.url(url).type(JSONObject.class);
		aq.progress(R.id.progress).ajax(cb);

	}

	public void async_html() { //同步html分析

		String url = "http://www.google.com";

		aq.progress(R.id.progress).ajax(url, String.class,
				new AjaxCallback<String>() {

					@Override
					public void callback(String url, String html,
							AjaxStatus status) {

						showResult(html, status);
					}

				});

	}

	public void async_bytes() {

		String url = "http://www.vikispot.com/z/images/vikispot/android-w.png";

		aq.progress(R.id.progress).ajax(url, byte[].class,
				new AjaxCallback<byte[]>() {

					@Override
					public void callback(String url, byte[] object,
							AjaxStatus status) {

						showResult("bytes array length:" + object.length,
								status);
					}
				});

	}

	public void async_xml() {

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

		aq.progress(R.id.progress).ajax(url, XmlDom.class,
				new AjaxCallback<XmlDom>() {

					public void callback(String url, XmlDom xml,
							AjaxStatus status) {
						showResult(xml, status);
					}

				});

	}

	public void async_file() {

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

		aq.progress(R.id.progress).ajax(url, File.class,
				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);
						}
					}

				});

	}

	public void async_file_custom() {

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

		File ext = Environment.getExternalStorageDirectory();
		File target = new File(ext, "aquery/myfolder2/photos1.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);
						}
					}

				});

	}

	public void async_web() {

		String MOBILE_AGENT = "Mozilla/5.0 (Linux; U; Android 2.2) AppleWebKit/533.1 (KHTML, like Gecko) Version/4.0 Mobile Safari/533";

		AjaxCallback.setAgent(MOBILE_AGENT);

		aq.id(R.id.result).gone();
		aq.id(R.id.web).visible();

		// String url =
		// "http://www.shouda8.com/shouda/tunshixingkong/14/2618.htm";
		// String url =
		// "http://www.engadget.com/2012/05/04/samsung-releases-galaxy-tab-2-7-and-10-source-code";
		String url = "http://mashable.com/2012/05/05/new-york-city-tech-startups/";

		// wv.loadUrl("file:///android_asset/html_no_copy/demo_welcome.html");
		long expire = 3600000;

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

					@Override
					public void callback(String url, String html,
							AjaxStatus status) {

						AQUtility.debug("file length:" + html.length());

						showResult("", status);

						WebView wv = aq.id(R.id.web).getWebView();
						WebSettings ws = wv.getSettings();
						// ws.setJavaScriptEnabled(true);

						wv.loadDataWithBaseURL(url, html, "text/html", "utf-8",
								null);
						// wv.loadUrl(url);
						// showResult(html, status);
					}

				});

	}

	public void async_inputstream() {

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

		aq.progress(R.id.progress).ajax(url, InputStream.class,
				new AjaxCallback<InputStream>() {

					public void callback(String url, InputStream is,
							AjaxStatus status) {

						if (is != null) {
							showResult("InputStream:" + is, status);
						} else {
							showResult("Failed", status);
						}
					}

				});

	}

	public void async_xpp() {

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

		aq.progress(R.id.progress).ajax(url, XmlPullParser.class,
				new AjaxCallback<XmlPullParser>() {

					public void callback(String url, XmlPullParser xpp,
							AjaxStatus status) {

						Map<String, String> images = new LinkedHashMap<String, String>();
						String currentTitle = null;

						try {

							int eventType = xpp.getEventType();
							while (eventType != XmlPullParser.END_DOCUMENT) {

								if (eventType == XmlPullParser.START_TAG) {

									String tag = xpp.getName();

									if ("title".equals(tag)) {
										currentTitle = xpp.nextText();
									} else if ("content".equals(tag)) {
										String imageUrl = xpp
												.getAttributeValue(0);
										images.put(currentTitle, imageUrl);
									}
								}
								eventType = xpp.next();
							}

						} catch (Exception e) {
							AQUtility.report(e);
						}

						showResult(images, status);

					}
				});

	}

	public void async_json_array() {

		String url = "http://androidquery.appspot.com/test/jsonarray.json";

		aq.progress(R.id.progress).ajax(url, JSONArray.class,
				new AjaxCallback<JSONArray>() {

					public void callback(String url, JSONArray ja,
							AjaxStatus status) {
						showResult(ja, status);
					}

				});

	}
九:

public void location_ajax() {  /ajax请求位子信息

		aq.id(R.id.result).text("");

		LocationAjaxCallback cb = new LocationAjaxCallback();
		cb.weakHandler(this, "locationCb").timeout(30 * 1000).accuracy(1000)
				.iteration(3);
		cb.async(this);

		this.cb = cb;
	}

	public void locationCb(String url, Location loc, AjaxStatus status) {

		if (loc != null) {
			appendResult(loc);
		}

	}
十:

public void xml_ajax() {  //分析 ajax请求xml

		String url = "https://picasaweb.google.com/data/feed/base/featured?max-results=8";
		aq.progress(R.id.progress).ajax(url, XmlDom.class, this, "picasaCb");

	}

	public void picasaCb(String url, XmlDom xml, AjaxStatus status) {

		showResult(xml, status);
		if (xml == null)
			return;

		List<XmlDom> entries = xml.tags("entry");

		List<String> titles = new ArrayList<String>();

		String imageUrl = null;

		for (XmlDom entry : entries) {
			titles.add(entry.text("title"));
			imageUrl = entry.tag("content", "type", "image/jpeg").attr("src");

		}

		showTextResult(titles);

		aq.id(R.id.image).image(imageUrl);

	}
十一:

    private void image_zoom(){  //图片放大
    
    	String url = "http://farm4.static.flickr.com/3531/3769416703_b76406f9de.jpg";    	
    	aq.id(R.id.text).text("Try pinch zoom with finger.");
    	aq.id(R.id.web).progress(R.id.progress).webImage(url);
    	//aq.id(R.id.web).progress(R.id.progress).webImage(url, true, true, 0xFF000000);
    }

十二:

	public void renderNews(String url, JSONObject json, AjaxStatus status) {  //渲染
	
		if(json == null) return;
		
		JSONArray ja = json.optJSONObject("responseData").optJSONArray("results");
		if(ja == null) return;
		
		List<JSONObject> items = new ArrayList<JSONObject>();
		addItems(ja, items);
		addItems(ja, items);
		addItems(ja, items);
		addItems(ja, items);
		
		listAq = new AQuery(this);
		
		ArrayAdapter<JSONObject> aa = new ArrayAdapter<JSONObject>(this, R.layout.content_item_s, items){
			
			@Override
			public View getView(int position, View convertView, ViewGroup parent) {
				
				if(convertView == null){
					convertView = getLayoutInflater().inflate(R.layout.content_item_s, null);
				}
				
				JSONObject jo = getItem(position);
				
				AQuery aq = listAq.recycle(convertView);
				aq.id(R.id.name).text(jo.optString("titleNoFormatting", "No Title"));
				aq.id(R.id.meta).text(jo.optString("publisher", ""));
				
				String tb = jo.optJSONObject("image").optString("tbUrl");
				aq.id(R.id.tb).progress(R.id.progress).image(tb, true, true, 0, 0, null, AQuery.FADE_IN_NETWORK, 1.0f);
				
				
				return convertView;
				
			}
		};
		
		aq.id(R.id.list).adapter(aa);
		
	}

十三:

	public void image_simple(){
		
		String url = "http://www.vikispot.com/z/images/vikispot/android-w.png";
		aq.id(R.id.image).progress(R.id.progress).image(url);
		
	}
	
	public void image_cache(){
		
		boolean memCache = false;
		boolean fileCache = true;

		String url = "http://www.vikispot.com/z/images/vikispot/android-w.png";
		aq.id(R.id.image).progress(R.id.progress).image(url, memCache, fileCache);
	}
	
	
	public void image_down(){
		
		String imageUrl = "http://farm6.static.flickr.com/5035/5802797131_a729dac808_b.jpg";            
		aq.id(R.id.image).progress(R.id.progress).image(imageUrl, true, true, 200, 0);

	}
	
	
	public void image_fallback(){
		
		String imageUrl = "http://www.vikispot.com/z/images/vikispot/xyz.png";
		aq.id(R.id.image).progress(R.id.progress).image(imageUrl, true, true, 0, R.drawable.image_missing);
		
	}
	
	
	
	public void image_preload(){
		
		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).progress(R.id.progress).image(imageUrl, false, false, 0, 0, preset, 0, AQuery.RATIO_PRESERVE);
		
	}
	
	public void image_progress(){
		
		ProgressDialog dialog = new ProgressDialog(this);
		
        dialog.setIndeterminate(true);
        dialog.setCancelable(true);
        dialog.setInverseBackgroundForced(false);
        dialog.setCanceledOnTouchOutside(true);
        dialog.setTitle("Sending...");
		
		aq.id(R.id.image).clear();
		
		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);
		
		//imageUrl = "http://www.vikispot.com/z/images/vikispot/android-w.png";				
		//aq.id(R.id.image).progress(dialog).image(imageUrl, true, true);
		
	}

	public void image_animation(){
	
		String imageUrl = "http://www.vikispot.com/z/images/vikispot/android-w.png";					
		aq.id(R.id.image).progress(R.id.progress).image(imageUrl, true, true, 0, 0, null, AQuery.FADE_IN);
		
	}
	
	
	public void image_animation2(){
		
		String imageUrl = "http://www.vikispot.com/z/images/vikispot/android-w.png";		
		aq.id(R.id.image).progress(R.id.progress).image(imageUrl, true, true, 0, 0, null, R.anim.slide_in_left);
		
	}
	
	public void image_ratio(){
		
		String imageUrl = "http://farm3.static.flickr.com/2199/2218403922_062bc3bcf2.jpg";	
		aq.id(R.id.image).progress(R.id.progress).image(imageUrl, true, true, 0, 0, null, AQuery.FADE_IN, AQuery.RATIO_PRESERVE);
	
	}
	
	public void image_round(){
		
		String url = "http://www.vikispot.com/z/images/vikispot/android-w.png";
		aq.id(R.id.image);//.progress(R.id.progress).image(url);
		
		BitmapAjaxCallback.async(this, this, aq.getImageView(), url, true, true, 0, 0, null, 0, 0, 0, null, null, 0, 15);
		
	}
	
	public void image_file(){
		
		String imageUrl = "http://farm6.static.flickr.com/5035/5802797131_a729dac808_b.jpg";
		File file = aq.getCachedFile(imageUrl);
		
		if(file != null){
			aq.id(R.id.image).progress(R.id.progress).image(file, 300);
		}
		
	}
	
	public void image_custom(){
		
		String imageUrl = "http://www.vikispot.com/z/images/vikispot/android-w.png";
		final int tint = 0x77AA0000;

		aq.id(R.id.image).progress(R.id.progress).visible().image(imageUrl, true, true, 0, 0, new BitmapAjaxCallback(){

	        @Override
	        public void callback(String url, ImageView iv, Bitmap bm, AjaxStatus status){
	           
	        	iv.setBackgroundColor(0xffcc0000);
                iv.setImageBitmap(bm);
                //iv.setColorFilter(tint, PorterDuff.Mode.SRC_ATOP);
	                
                showMeta(status);
	        }
		        
		}.round(10));
	}
	
	public void image_file_custom(){
		
		String imageUrl = "http://farm6.static.flickr.com/5035/5802797131_a729dac808_b.jpg";
		File file = aq.getCachedFile(imageUrl);
		final int tint = 0x77AA0000;
		
		if(file != null){
			
			aq.id(R.id.image).progress(R.id.progress).visible().image(file, true, 300, new BitmapAjaxCallback(){

		        @Override
		        public void callback(String url, ImageView iv, Bitmap bm, AjaxStatus status){
		           
	                iv.setImageBitmap(bm);
	                iv.setColorFilter(tint, PorterDuff.Mode.SRC_ATOP);
		                
	                showMeta(status);
		        }
			        
			});
			
		}
		
	}
	
	
	public void image_dup(){
		
		String imageUrl = "http://www.vikispot.com/z/images/vikispot/android-w.png";
		aq.id(R.id.image).image(imageUrl, false, false);

		//no network fetch for 2nd request, image will be shown when first request is completed
		aq.id(R.id.image2).image(imageUrl, false, false);
		
	}
	
	public void image_button(){
			
		String tb = "http://androidquery.appspot.com/z/demo/button.png";
		aq.id(R.id.button).image(tb);
		
	}
	
	public void image_advance(){
		
		aq.id(R.id.image).width(LayoutParams.FILL_PARENT);
		
		String imageUrl = "http://farm3.static.flickr.com/2199/2218403922_062bc3bcf2.jpg";	
	
		BitmapAjaxCallback cb = new BitmapAjaxCallback();
		cb.url(imageUrl).animation(AQuery.FADE_IN).ratio(1.0f);
		
		aq.id(R.id.image).image(cb);
		
	}
	
	public void image_access_file(){ //
		
		String imageUrl = "http://www.vikispot.com/z/images/vikispot/android-w.png";
		File file = aq.getCachedFile(imageUrl);
		
		if(file != null){
			showResult("File:" + file + " Length:" + file.length(), null);
		}
		
	}
	
	public void image_access_memory(){ //
		
		String imageUrl = "http://www.vikispot.com/z/images/vikispot/android-w.png";			
		Bitmap bm = aq.getCachedImage(imageUrl);
		
		if(bm != null){
			showResult("Dimension:" + bm.getWidth() + "x" + bm.getHeight(), null);
		}
		
	}
	
	public void image_pre_cache(){
		
		String imageUrl = "http://farm3.static.flickr.com/2199/2218403922_062bc3bcf2.jpg";
		
		File file = aq.getCachedFile(imageUrl);
		
		if(file != null){
			showTextResult("File cached:" + file.getAbsolutePath() + " Length:" + file.length());
		}
		
		aq.id(R.id.image).image(imageUrl);
		
	}
	
	
	public void image_nocache(){ //无缓存图片
		
		String url = "http://www.vikispot.com/z/images/vikispot/android-w.png";
		
		//force a network refetch without any caching
		aq.id(R.id.image).image(url, false, false);
		
		//force no proxy cache by appending a random number 
		String url2 = url + "?t=" + System.currentTimeMillis();
		aq.id(R.id.image2).image(url2, false, false);
		
	}
	
	public void image_clear_mem(){ //清除内存图片
		BitmapAjaxCallback.clearCache();
		showTextResult("Bitmap Memcache cleared");
	}
	
	public void image_clear_disk(){ //清除图片目录
		
		AQUtility.cleanCacheAsync(this, 0, 0);
		showTextResult("File cache cleared");
	}
	
	public void image_cache_dir(){ //缓存目录
		
		File ext = Environment.getExternalStorageDirectory();
		File cacheDir = new File(ext, "myapp");
		
		AQUtility.setCacheDir(cacheDir);
		
		AQUtility.debug("cache dir exist", cacheDir.exists());
		
		String url = "http://www.vikispot.com/z/images/vikispot/android-w.png";
		aq.cache(url, 0);
		
		File file = AQUtility.getCacheFile(AQUtility.getCacheDir(this, AQuery.CACHE_DEFAULT), url);
		
		showTextResult(file.getAbsolutePath());
	}
	
	private static final int SEND_REQUEST = 12;
	
	public void image_send(){ //图片发送
		
		String url = "http://www.vikispot.com/z/images/vikispot/android-w.png";		
		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);
		}
	}
	
	
	public void image_chart(){ //图片
		
        // EXAMPLE from http://code.google.com/p/charts4j/
        
        final int NUM_POINTS = 25;
        final double[] competition = new double[NUM_POINTS];
        final double[] mywebsite = new double[NUM_POINTS];
        for (int i = 0; i < NUM_POINTS; i++) {
            competition[i] = 100-(Math.cos(30*i*Math.PI/180)*10 + 50)*i/20;
            mywebsite[i] = (Math.cos(30*i*Math.PI/180)*10 + 50)*i/20;
        }
        Line line1 = Plots.newLine(Data.newData(mywebsite), Color.newColor("CA3D05"), "My Website.com");
        line1.setLineStyle(LineStyle.newLineStyle(3, 1, 0));
        line1.addShapeMarkers(Shape.DIAMOND, Color.newColor("CA3D05"), 12);
        line1.addShapeMarkers(Shape.DIAMOND, Color.WHITE, 8);
        Line line2 = Plots.newLine(Data.newData(competition), SKYBLUE, "Competition.com");
        line2.setLineStyle(LineStyle.newLineStyle(3, 1, 0));
        line2.addShapeMarkers(Shape.DIAMOND, SKYBLUE, 12);
        line2.addShapeMarkers(Shape.DIAMOND, Color.WHITE, 8);


        // Defining chart.
        LineChart chart = GCharts.newLineChart(line1, line2);
        chart.setSize(600, 450);
        
        String dummy = "Lorem ipsum dolor sit amet, consectetur adipisicing elit, sed do eiusmod tempor incididunt ut labore et dolore magna aliqua. Ut enim ad minim veniam, quis nostrud exercitation ullamco laboris nisi ut aliquip ex ea commodo consequat. Duis aute irure dolor in reprehenderit in voluptate velit esse cillum dolore eu fugiat nulla pariatur. Excepteur sint occaecat cupidatat non proident, sunt in culpa qui officia deserunt mollit anim id est laborum.";
		String title = "Very long title " + dummy + dummy + dummy + dummy + dummy;
		
		chart.setTitle(title);
		
		chart.addHorizontalRangeMarker(40, 60, Color.newColor(RED, 30));
        chart.addVerticalRangeMarker(70, 90, Color.newColor(GREEN, 30));
        chart.setGrid(25, 25, 3, 2);

        // Defining axis info and styles
        AxisStyle axisStyle = AxisStyle.newAxisStyle(WHITE, 12, AxisTextAlignment.CENTER);
        AxisLabels xAxis = AxisLabelsFactory.newAxisLabels("Nov", "Dec", "Jan", "Feb", "Mar");
        xAxis.setAxisStyle(axisStyle);
        AxisLabels xAxis2 = AxisLabelsFactory.newAxisLabels("2007", "2007", "2008", "2008", "2008");
        xAxis2.setAxisStyle(axisStyle);
        AxisLabels yAxis = AxisLabelsFactory.newAxisLabels("", "25", "50", "75", "100");
        AxisLabels xAxis3 = AxisLabelsFactory.newAxisLabels("Month", 50.0);
        xAxis3.setAxisStyle(AxisStyle.newAxisStyle(WHITE, 14, AxisTextAlignment.CENTER));
        yAxis.setAxisStyle(axisStyle);
        AxisLabels yAxis2 = AxisLabelsFactory.newAxisLabels("Hits", 50.0);
        yAxis2.setAxisStyle(AxisStyle.newAxisStyle(WHITE, 14, AxisTextAlignment.CENTER));
        yAxis2.setAxisStyle(axisStyle);

        // Adding axis info to chart.
        chart.addXAxisLabels(xAxis);
        chart.addXAxisLabels(xAxis2);
        chart.addXAxisLabels(xAxis3);
        chart.addYAxisLabels(yAxis);
        chart.addYAxisLabels(yAxis2);

        // Defining background and chart fills.
        chart.setBackgroundFill(Fills.newSolidFill(Color.newColor("1F1D1D")));
        LinearGradientFill fill = Fills.newLinearGradientFill(0, Color.newColor("363433"), 100);
        fill.addColorAndOffset(Color.newColor("2E2B2A"), 0);
        chart.setAreaFill(fill);
        String url = chart.toURLString();
		
        showTextResult("Image URL:" + url);
        
		aq.id(R.id.image).progress(R.id.progress).image(url);
		
	}
十四:

	public void aspectRatio() {  //图片效果比率

		String imageUrl = "http://farm3.static.flickr.com/2199/2218403922_062bc3bcf2.jpg";

		aq.id(R.id.image1)
				.progress(R.id.progress)
				.image(imageUrl, true, true, 0, 0, null, 0,
						AQuery.RATIO_PRESERVE);
		// aq.id(R.id.image1).progress(R.id.progress).image("http://www.google.com/a.jpg",
		// true, true, 0, AQuery.GONE, null, 0, AQuery.RATIO_PRESERVE);

		aq.id(R.id.text1).text("Original Aspect Ratio");

		aq.id(R.id.image2).image(imageUrl, true, true, 0, 0, null, 0,
				1.0f / 1.0f);
		aq.id(R.id.text2).text("1:1");

		aq.id(R.id.image3).image(imageUrl, true, true, 0, 0, null, 0,
				1.5f / 1.0f);
		aq.id(R.id.text3).text("1.5:1");

		aq.id(R.id.image4).image(imageUrl, true, true, 0, 0, null, 0,
				9.0f / 16.0f);
		aq.id(R.id.text4).text("9:16");

		aq.id(R.id.image5).image(imageUrl, true, true, 0, 0, null, 0,
				3.0f / 4.0f);
		aq.id(R.id.text5).text("3:4");

	}


学习的目标是成熟!

项目下载


  • 2
    点赞
  • 19
    收藏
    觉得还不错? 一键收藏
  • 4
    评论
根据项目名称就知道它的意思了,框架、实例、测试功能! AndroidQuery 一个轻量级的库,用于实现 Android 上的异步任务和操作 UI 元素。 项目含有26 个文件源文件,分析如下: auth含有: public class WebDialog extends Dialog 对话框显示网页信息 public class BasicHandle extends AccountHandle 本地帐号用户认证(Base64Coder编解码) public class FacebookHandle extends AccountHandle Facebook帐号用户认证(Base64Coder编解码) public class TwitterHandle extends AccountHandle Twitter帐号用户认证(Base64Coder编解码) public class GoogleHandle extends AccountHandle implements DialogInterface.OnClickListener, OnCancelListener Google帐号用户认证(Base64Coder编解码) public class LocationAjaxCallback extends AbstractAjaxCallback<Location, LocationAjaxCallback> //本地位置信息回调 封装了本地手机gps、network确认手机位置信息 然后返回最新位置信息 public abstract class AbstractAQuery<T extends AbstractAQuery<T>> implements Constants 模块类,含有AQuery所有方法。 主要方法如: public T find(int id) //查找根容器 public T parent(int id) //返回id容器的父容器 public T recycle(View root) //回收 public T id(int id) //返回id容器 public T auth(AccountHandle handle) //Ajax请求进行身份验证 public T transformer(Transformer transformer) //Ajax请求所需的对象类型转换 ……图片处理、下载、以及相关控件的方法操作! public class AQuery extends AbstractAQuery<AQuery> //主要类,实现上面的模版类 public abstract class AbstractAjaxCallback<T, K> implements Runnable //封装Ajax请求、回调 public class AjaxStatus //记录ajax请求的状态信息 如头信息、cookies 等 public class BitmapAjaxCallback extends AbstractAjaxCallback<Bitmap, BitmapAjaxCallback> //封装ajax请求图片 public class AQUtility //封装了特效方法 public class BitmapCache extends LinkedHashMap<String, Bitmap> //图片缓冲 使用哈希管理 public class Common implements Comparator<File>, Runnable, OnClickListener, OnLongClickListener, OnItemClickListener, OnScrollListener, OnItemSelectedListener, TextWatcher //仅供内部使用。一个共享的监听器类,以减少类的数量。 public class PredefinedBAOS extends ByteArrayOutputStream //管理缓冲流 返回流 public class Progress implements Runnable //进度条管理 public class RatioDrawable extends BitmapDrawable //图片 public class WebImage extends WebViewClient //web图片 public class XmlDom //XML解析
评论 4
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值