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各个版本

点击打开链接





  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值