android代碼片段整理,持續更新中(二)。。。。。。

一.Volley請求post

RequestQueue requestQueue = Volley.newRequestQueue(getApplicationContext());
		StringRequest stringRequest = new StringRequest(Method.POST, httpUrl, new Listener<String>() {

			@Override
			public void onResponse(String response) {
				// TODO Auto-generated method stub
				System.out.println(">>>>>>>>>>response" + response);
			}
		}, new Response.ErrorListener() {

			@Override
			public void onErrorResponse(VolleyError error) {
				// TODO Auto-generated method stub
				System.out.println(">>>>>>>>>>error" + error);
			}
		}) {
			public Map<String, String> getParams() {
				Map<String, String> map = new HashMap<String, String>();
				map.put("name", "xiaoxiao");
				map.put("id", "33");
				return map;
			}

			public Map<String, String> getHeaders() {
				HashMap<String, String> headers = new HashMap<String, String>();
				headers.put("Accept", "application/json");
				headers.put("Content-Type", "application/json; charset=UTF-8");

				return headers;
			}
		};
		requestQueue.add(stringRequest);
	}

二.httpclient請求傳入json

	public static void httpPostWithJSON(String url, String json) throws Exception {
        // 將JSON進行UTF-8編碼,以便傳輸中文
        String encoderJson = URLEncoder.encode(json, HTTP.UTF_8);
        DefaultHttpClient httpClient = new DefaultHttpClient();
        HttpPost httpPost = new HttpPost(url);
        httpPost.addHeader(HTTP.CONTENT_TYPE, "application/json");
        StringEntity se = new StringEntity(encoderJson);
        se.setContentType("text/json");
        se.setContentEncoding(new BasicHeader(HTTP.CONTENT_TYPE,"application/json"));
        httpPost.setEntity(se);
        HttpResponse httpResponse =httpClient.execute(httpPost);
        if (httpResponse.getStatusLine().getStatusCode() == HttpStatus.SC_OK) {
			// 取得返回的字符串
			String strResult = EntityUtils.toString(httpResponse.getEntity());
			System.out.println(">>>>>>>>>>" + strResult);
			
		}
    }

三.AsyncHttpClient工具類

public class HttpUtil {
	private static AsyncHttpClient client = new AsyncHttpClient(); // 實例話對象
	static {
		client.setTimeout(10000); // 設置鏈接超時,如果不設置,默認爲10s
	}

	// 用一個完整url獲取一個string對象
	public static void get(String urlString, AsyncHttpResponseHandler res) {
		client.get(urlString, res);
	}

	// url裏面帶參數
	public static void get(String urlString, RequestParams params, AsyncHttpResponseHandler res) {
		client.get(urlString, params, res);
	}

	// 不帶參數,獲取json對象或者數組
	public static void get(String urlString, JsonHttpResponseHandler res) {
		client.get(urlString, res);
	}

	// 帶參數,獲取json對象或者數組
	public static void get(String urlString, RequestParams params, JsonHttpResponseHandler res) {
		client.get(urlString, params, res);
	}

	// 下載數據使用,會返回byte數據
	public static void get(String uString, BinaryHttpResponseHandler bHandler) {
		client.get(uString, bHandler);
	}

	public static AsyncHttpClient getClient() {
		return client;
	}

四.獲得預覽分辨率二

	List<Size> preSize = parameters.getSupportedPreviewSizes();
	previewWidth = preSize.get(0).width;
	previewHeight = preSize.get(0).height;
	for (int i = 1; i < preSize.size(); i++) {
		//rotate 90
	double diff2 = Math.abs((double) preSize.get(i).width
	/ preSize.get(i).height - (double) screenHeight
			/ screenWidth);
		if(diff2<0.1)
		{
		int diff3 = Math.abs(previewHeight * previewWidth
		- DEFAULT_RESOLUTION);
		int diff4 = Math.abs(preSize.get(i).height
		* preSize.get(i).width - DEFAULT_RESOLUTION);
			if (diff3 > diff4)
			{
			previewWidth = preSize.get(i).width;
			previewHeight = preSize.get(i).height;
				}			
			}
		}
		//current only support landscape
		parameters.setPreviewSize(previewWidth, previewHeight);

五.AudioRecord錄音寫入文件

while (isRecord == true) {    
            readsize = audioRecord.read(audiodata, 0, bufferSizeInBytes);    
            if (AudioRecord.ERROR_INVALID_OPERATION != readsize && fos!=null) {    
                try {    
                    fos.write(audiodata,0, readsize);  // 只從當前位置,寫入到實際讀到的字節數  
                } catch (IOException e) {    
                    e.printStackTrace();    
                }    
            }    
        } 

六.httpUrlconnection

 Runnable runnable = new Runnable() {
        @Override
        public void run() {
            try {
                URL url = new URL(imgUrl);
                HttpURLConnection conn = (HttpURLConnection) url.openConnection();
                conn.setRequestMethod("GET");
                conn.setReadTimeout(10000);
                if (conn.getResponseCode() == 200) {
                    InputStream in = conn.getInputStream();
                    ByteArrayOutputStream out = new ByteArrayOutputStream();
                    byte[] bytes = new byte[1024];
                    int length = -1;
                    while ((length = in.read(bytes)) != -1) {
                        out.write(bytes, 0, length);
                    }
                    picByte = out.toByteArray();
                    in.close();
                    out.close();
                    handler.sendEmptyMessage(0x123);
                }

            } catch (IOException e) {
                e.printStackTrace();
            }
        }
    };

七安全轉換爲int

public final static int convertToInt(Object value, int defaultValue) {
    if (value == null || "".equals(value.toString().trim())) {
        return defaultValue;
    }
    try {
        return Integer.valueOf(value.toString());
    } catch (Exception e) {
        try {
            return Double.valueOf(value.toString()).intValue();
        } catch (Exception e1) {
            return defaultValue;
        }
    }
}

八防止被重複點擊

/*
	 * 防止按鈕被重複點擊
	 */
	private static long lastClickTime;
	
	public synchronized static boolean isFastClick()
	{
		long time = System.currentTimeMillis();
		if (time - lastClickTime < 1000)
		{
//			LogUtils.i("kkkk", "time - lastClickTime:" + (time - lastClickTime));
			return true;
		}
		lastClickTime = time;
		return false;
	}

九顯示隱藏鍵盤

//彈出鍵盤
  protected void showInputMethod(final EditText editText)
    {
        // 彈出鍵盤
        new Handler().postDelayed(new Runnable()
        {
            @Override
            public void run()
            {
                editText.setFocusableInTouchMode(true);
                editText.setFocusable(true);
                editText.requestFocus();
                editText.setSelection(editText.getText().length());
                ((InputMethodManager) getSystemService(Context.INPUT_METHOD_SERVICE)).showSoftInput(
                        editText, 0);
            }
        }, 300);
    }

    //關閉鍵盤
     protected void closeInputMethod(EditText editText)
    {
        ((InputMethodManager) getSystemService(
                Context.INPUT_METHOD_SERVICE)).hideSoftInputFromWindow(editText.getWindowToken(),
                0);
    }<

十.gradle各個版本

點擊打開鏈接





發佈了88 篇原創文章 · 獲贊 18 · 訪問量 17萬+
發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章