Android为了给开发这实现某些功能提供了很多的方法,下面是我的一些总结,希望对某些同学有所帮助,大概有照片保存、转换格式、http访问网络等等。
一、照片的保存转换
1、在某些情况下我们会加载本地的照片设置在界面作为背景或者头像,当然背景的设置是需要bitmap对 象或者drawable,这就需要我们对本地照片进行转换,将文件转换成bitmap:
/** * 获取本地照片转换成Bitmap * * @param url 本地照片的路径 * @return */ public static Bitmap getLoacalBitmap(String url) { try { FileInputStream fis = new FileInputStream(url); fis.close(); return BitmapFactory.decodeStream(fis); ///把流转化为Bitmap图片 } catch (FileNotFoundException e) { e.printStackTrace(); } catch (IOException e) { e.printStackTrace(); } return null; }
2、也可能是将一个bitmap的对象转换成文件:
/** * 将bitmap转换成照片存放在本地 * * @param bitmapPahth 存放地址 * @param bitmap bitmap对象,将要转换的bitmap */ public static void getBitmapImageFile(String bitmapPahth, Bitmap bitmap) { File bitmapFile = new File(bitmapPahth); FileOutputStream bitmapWtriter = null; try { if (bitmapFile.exists()) { bitmapWtriter = new FileOutputStream(bitmapFile); } else { bitmapFile.mkdirs(); bitmapWtriter = new FileOutputStream(bitmapFile); } } catch (FileNotFoundException e) { e.printStackTrace(); } if (bitmapFile.exists()) { bitmap.compress(Bitmap.CompressFormat.PNG, 90, bitmapWtriter); } try { bitmapWtriter.close(); } catch (IOException e) { e.printStackTrace(); } }
3、在某些时候我们需要的是bitmap的对象而不是drawable,所以我们还是要转:
/** * 将drawable转换成bitmap * * @param drawable * @return */ public static Bitmap drawableToBitmap(Drawable drawable) { int width = drawable.getIntrinsicWidth(); int height = drawable.getIntrinsicHeight(); Bitmap bitmap = Bitmap.createBitmap(width, height, drawable.getOpacity() != PixelFormat.OPAQUE ? Bitmap.Config.ARGB_8888 : Bitmap.Config.RGB_565); Canvas canvas = new Canvas(bitmap); drawable.setBounds(0, 0, width, height); drawable.draw(canvas); return bitmap; }
二、HttpUrlConnection访问网络
1、我们要从后台获取照片的时候:
/** * 从服务器取图片 * * @param httpUrl * @return */ public static Bitmap getConnectionBitmap(String httpUrl) { URL url = null; Bitmap bitmap = null; try { url = new URL(httpUrl); } catch (MalformedURLException e) { e.printStackTrace(); } try { HttpURLConnection conn = (HttpURLConnection) url.openConnection(); conn.setConnectTimeout(0); conn.setDoInput(true); conn.connect(); InputStream is = conn.getInputStream(); bitmap = BitmapFactory.decodeStream(is); is.close(); conn.disconnect(); } catch (IOException e) { e.printStackTrace(); } return bitmap; }
2、后台下载文件
/** * 获取后台文件 * * @param url 后台地址 * @param filePath 本地文件地址 * @param fileName 文件存放的名称 * @return */ public static boolean getConnectionFiles(String url, String filePath, String fileName) { try { URL realUrl = new URL(url); HttpURLConnection urlConnection = (HttpURLConnection) realUrl.openConnection(); urlConnection.setReadTimeout(30000); InputStream stream = urlConnection.getInputStream(); FileOutputStream fos = new FileOutputStream(new File(filePath, fileName)); byte[] buffer = new byte[1024]; int len; downSize = 0; Size = urlConnection.getContentLength(); while (cando && (len = stream.read(buffer, 0, buffer.length)) != -1) { downSize += len; fos.write(buffer, 0, len); } fos.close(); stream.close(); urlConnection.disconnect(); return cando; } catch (Exception e) { System.out.println("发送GET请求出现异常!----->" + e); e.printStackTrace(); return false; } }
/** * * @param url 请求地址 * @param param 参数 * @return */ public static String getConnectionParam(String url, String param) { String result = ""; try { URL realUrl = new URL(url + "?" + param); HttpURLConnection urlConnection = (HttpURLConnection) realUrl.openConnection(); urlConnection.setReadTimeout(30000); InputStream stream = urlConnection.getInputStream();//得到读取的内容 InputStreamReader in = new InputStreamReader(stream); BufferedReader buffer = new BufferedReader(in); //为输出创建BufferedReader String line; while (cando && (line = buffer.readLine()) != null) {//使用while循环来取得获取的数据 result += line; } in.close();//关闭InputStreamReader urlConnection.disconnect();//关闭http连接 } catch (Exception e) { System.out.println("发送GET请求出现异常!----->" + e); e.printStackTrace(); result = ""; } return result; }
/** * @param url 发送请求的 URL * @param param 请求参数,请求参数应该是 name1=value1&name2=value2 的形式。 * @return 所代表远程资源的响应结果 */ public static String postConnectionParam(String url, String param) { PrintWriter out = null; BufferedReader in = null; String result = ""; try { URL realUrl = new URL(url); // 打开和URL之间的连接 URLConnection conn = realUrl.openConnection(); conn.setReadTimeout(5000); // 设置通用的请求属性 conn.setRequestProperty("accept", "*/*"); conn.setRequestProperty("connection", "Keep-Alive"); conn.setRequestProperty("user-agent", "Mozilla/4.0 (compatible; MSIE 6.0; Windows NT 5.1;SV1)"); // 发送POST请求必须设置如下两行 conn.setDoOutput(true); conn.setDoInput(true); // 获取URLConnection对象对应的输出流 out = new PrintWriter(conn.getOutputStream()); // 发送请求参数 out.print(param); // flush输出流的缓冲 out.flush(); // 定义BufferedReader输入流来读取URL的响应 in = new BufferedReader(new InputStreamReader(conn.getInputStream())); String line; while (cando && (line = in.readLine()) != null) { result += line; } } catch (Exception e) { System.out.println("发送 POST 请求出现异常!" + e); e.printStackTrace(); result = ""; } //使用finally块来关闭输出流、输入流 finally { try { if (out != null) { out.close(); } if (in != null) { in.close(); } } catch (IOException ex) { ex.printStackTrace(); } } return result; }
三、字符串的处理
1、非空判断,为了少些错误,所以判断的条件增加了。
/*** * 判断字符串是否为空 * * @param strContent 你要判断的字符串 * @return 非空返回true */ public static boolean isStrTrue(String strContent) { if (strContent != null && !"".equals(strContent) && !TextUtils.isEmpty(strContent) && !"".equals(strContent.trim())) { return true; } return false; }
2、字符串的大小写转换
//把一个字符串中的大写转为小写,小写转换为大写 public static String exChange1(String str) { StringBuffer sbuffer = new StringBuffer(); if (str != null) { for (int i = 0; i < str.length(); i++) { char c = str.charAt(i); if (Character.isUpperCase(c)) { sbuffer.append(Character.toLowerCase(c)); } else if (Character.isLowerCase(c)) { sbuffer.append(Character.toUpperCase(c)); } } } return sbuffer.toString(); }
3、生成一个唯一的ID UUID+IMEI
/** * @return 获取一个唯一的ID UUID+IMEI */ public static String getOnlyID(Context context) { final TelephonyManager tm = (TelephonyManager) context .getSystemService(Context.TELEPHONY_SERVICE); final 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()); String uniqueId = deviceUuid.toString(); return uniqueId; }
四、httpclient访问网络请求的代码(单例模式)
这种适合后台保存session值的,不需要去获取保存后台的session值。根据情况使用
public class CHttpClient { private static HttpClient httpClient = new DefaultHttpClient(); public static String doGet(String url) { //将URL与参数拼接 HttpGet getMethod = new HttpGet(url); try { HttpResponse response = httpClient.execute(getMethod); //发起GET请求 if (response.getStatusLine().getStatusCode() == 200) { HttpEntity entity = response.getEntity(); InputStream is = entity.getContent(); BufferedReader reader = new BufferedReader(new InputStreamReader(is)); String content = reader.readLine(); return content; } } catch (ClientProtocolException e) { e.printStackTrace(); } catch (IOException e) { e.printStackTrace(); } return null; } public static String doGet3(String url, String param) { //将URL与参数拼接 HttpGet getMethod = new HttpGet(url + "?" + param); try { HttpResponse response = httpClient.execute(getMethod); //发起GET请求 if (response.getStatusLine().getStatusCode() == 200) { HttpEntity entity = response.getEntity(); InputStream is = entity.getContent(); BufferedReader reader = new BufferedReader(new InputStreamReader(is)); String content = reader.readLine(); return content; } } catch (ClientProtocolException e) { e.printStackTrace(); } catch (IOException e) { e.printStackTrace(); } return null; } public static Bitmap doGet2(String url) { //将URL与参数拼接 HttpGet getMethod = new HttpGet(url); try { httpClient.getParams().setParameter(CoreConnectionPNames.CONNECTION_TIMEOUT, 1000 * 5); // 链接超时 httpClient.getParams().setParameter(CoreConnectionPNames.SO_TIMEOUT, 1000 * 5); // 读取超时 HttpResponse response = httpClient.execute(getMethod); //发起GET请求 if (response.getStatusLine().getStatusCode() == 200) { InputStream is = response.getEntity().getContent(); //如果是返回得字符串,可以直接用 EntityUtils来处理 //EntityUtils.toString(response.getEntity()); Bitmap img = BitmapFactory.decodeStream(is); return img; } } catch (ClientProtocolException e) { e.printStackTrace(); } catch (IOException e) { e.printStackTrace(); } return null; } public static String doPost(String url, List<BasicNameValuePair> params) { try { HttpPost postMethod = new HttpPost(url); postMethod.setEntity(new UrlEncodedFormEntity(params, "utf-8")); //将参数填入POST Entity中 postMethod.setHeader("Content-Type", "application/x-www-form-urlencoded; charset=utf-8"); HttpResponse response = httpClient.execute(postMethod); //执行POST方法 String content = EntityUtils.toString(response.getEntity(), "utf-8"); Log.v("show",content+"评价返回的数据"); return content; } catch (IOException e) { e.printStackTrace(); } return null; } /** * 从服务器取图片 * * @param url * @return */ public static Bitmap getHttpBitmap(String url) { URL myFileUrl = null; Bitmap bitmap = null; try { myFileUrl = new URL(url); } catch (MalformedURLException e) { e.printStackTrace(); } try { HttpURLConnection conn = (HttpURLConnection) myFileUrl.openConnection(); conn.setConnectTimeout(0); conn.setDoInput(true); conn.connect(); InputStream is = conn.getInputStream(); bitmap = BitmapFactory.decodeStream(is); is.close(); conn.disconnect(); } catch (IOException e) { e.printStackTrace(); } return bitmap; } }
这些就是我最近使用的一些方法,还有一些方法正在编辑中后续会陆续发表。