1、android常用的代码 直接复制粘贴可用1.FILE工具/ 创建文件,参数包括路径(不能为空),文件名称,内容 publicstaticvoidmakefile(String path, String filename, String content) File dir = newFile(path); if (!dir.exists() dir.mkdir(); / dir.mkdir(); File newFile = null; if(path!=null) newFile = newFile(dir.getAbsolutePath()+/+filename); FileOutputS
2、tream fos = null; try newFile.createNewFile(); if (newFile.exists() & newFile.canWrite() fos = newFileOutputStream(newFile); fos.write(content.getBytes(); catch (IOException e) / TODO Auto-generated catch block e.printStackTrace(); finally if (fos != null) try fos.flush(); fos.close(); catch (IOExce
3、ption e) / TODO: handle exception 2.下载图片工具publicclassDownloadPicUtil /*paramurl*paramfilename*return0没有图片;return1成功;return2IO异常;*/ publicstaticintDownLoadBitmap(String url,Stringfilename) / TODO Auto-generated method stub InputStream inputStream= null; DefaultHttpClient client = newDefaultHttpClient
4、(); try HttpGet request=newHttpGet(url); HttpResponse response=client.execute(request); int statusCode = response.getStatusLine().getStatusCode(); if(statusCode!=HttpStatus.SC_OK) return 0; else HttpEntity entity =response.getEntity(); inputStream = entity.getContent(); Bitmap bitmap = BitmapFactory
5、.decodeStream(inputStream); /图片可以在这个时候存储到sdcard上 saveBitmap(bitmap,filename); return 1; catch (Exception e) / TODO Auto-generated catch block e.printStackTrace(); return 2; finally if(inputStream!=null) try inputStream.close(); catch (IOException e) / TODO Auto-generated catch block e.printStackTrac
6、e(); publicstaticvoidsaveBitmap(Bitmap bitName,String filename) String filepath = /sdcard/baomi/; File f = newFile(filepath+filename); FileOutputStream fout = null; try f.createNewFile(); fout = newFileOutputStream(f); bitNpress(Bitmap.CompressFormat.PNG,100,fout); fout.flush(); fout.close(); catch(
7、Exception e) e.printStackTrace(); 3.http请求工具publicclassHttpUtil publicstaticStringSESSION_ID=null; publicstaticHttpResponsegetHttpResponse(HttpGet request) throws ClientProtocolException,IOException BasicHttpParams httpParams = newBasicHttpParams(); LogService.getInstance().recordLog(进入getHttpRespon
8、se); HttpConnectionParams.setConnectionTimeout(httpParams, SysConfig.nConnectionTimeout); LogService.getInstance().recordLog(超时时间为:+SysConfig.nConnectionTimeout); HttpConnectionParams.setSoTimeout(httpParams, SysConfig.nSoTimeout); LogService.getInstance().recordLog(Socket超时时间为:+SysConfig.nSoTimeout
9、); DefaultHttpClient httpClient = newDefaultHttpClient(httpParams); LogService.getInstance().recordLog(获得响应客户端); HttpResponse response=httpClient.execute(request); LogService.getInstance().recordLog(获得结果); httpClient.getConnectionManager().shutdown(); LogService.getInstance().recordLog(关闭连接); return
10、 response; publicstaticHttpResponsegetHttpResponse(HttpPost request) throws ClientProtocolException,IOException BasicHttpParams httpParams = newBasicHttpParams(); HttpConnectionParams.setConnectionTimeout(httpParams, SysConfig.nConnectionTimeout); HttpConnectionParams.setSoTimeout(httpParams, SysCon
11、fig.nSoTimeout); DefaultHttpClient httpClient = newDefaultHttpClient(httpParams); HttpResponse response=httpClient.execute(request); httpClient.getConnectionManager().shutdown(); return response; /通过url发送post请求,并返回结果 publicstaticStringqueryStringForPost(String url) LogService.getInstance().recordLog
12、(发送POST请求); HttpPost request = newHttpPost(url); String result=null; try HttpResponse response=HttpUtil.getHttpResponse(request); LogService.getInstance().recordLog(POST返回状态为+response.getStatusLine().getStatusCode(); if(response.getStatusLine().getStatusCode()=200) result=EntityUtils.toString(respon
13、se.getEntity(); return result; catch (Exception e) LogService.getInstance().recordLog(POST异常:+e.getMessage(); e.printStackTrace(); result=网络异常;return result; returnnull; /通过url发送GET请求并返回结果 publicstaticStringqueryStringForGet(String url) LogService.getInstance().recordLog(发送GET请求); String result=null
14、; try ResponseHandler responseHandler = newBasicResponseHandler(); HttpClient httpclient = newDefaultHttpClient(); LogService.getInstance().recordLog(提交的地址为:+url); HttpGet httpget = newHttpGet(url); result = httpclient.execute(httpget, responseHandler); LogService.getInstance().recordLog(GET返回状态为+re
15、sult); return result; catch (Exception e) LogService.getInstance().recordLog(GET异常:+e.getMessage(); e.printStackTrace(); result=网络异常;return result; /通过HttpPost发送POST请求,并返回结果 publicstaticStringqueryStringForPost(HttpPost request) String result=null; try HttpResponse response=HttpUtil.getHttpResponse(
16、request); if(response.getStatusLine().getStatusCode()=200) result=EntityUtils.toString(response.getEntity(); return result; catch (Exception e) e.printStackTrace(); result=网络异常;return result; returnnull; 4.JSon工具public class JSonUtil public static String string2json(String s) StringBuilder sb = new
17、StringBuilder(s.length()+20); sb.append(); for (int i=0;is.length();i+) char c =s.charAt(i); switch(c) case : sb.append(); break; case : sb.append(); break; case /: sb.append(/); break; case b: sb.append(b); break; case f: sb.append(f); break; case n: sb.append(n); break; case r: sb.append(r); break
18、; case t: sb.append(t); break; default: sb.append(c); sb.append(); return sb.toString(); public static String number2json(Number number) return number.toString(); public static String boolean2json(Boolean bool) return bool.toString(); public static String map2json(Map map) if(map.isEmpty() return ;
19、StringBuilder sb = new StringBuilder(map.size()4); sb.append(); Set keys = map.keySet(); for(String key :keys) Object value = map.get(key); sb.append(); sb.append(key); sb.append(); sb.append(:); sb.append(tojson(value); sb.append(,); sb.setCharAt(sb.length()-1, ); return sb.toString(); public stati
20、c String array2json(Object array) if(array.length=0) return ; StringBuilder sb = new StringBuilder(array.length4); sb.append(); for(Object o:array) sb.append(tojson(o); sb.append(,); sb.setCharAt(sb.length()-1, ); return sb.toString(); public static String tojson(Object o) if(o=null) return null; if
21、(o instanceof String) return string2json(String)o); if(o instanceof Boolean) return boolean2json(Boolean)o); if(o instanceof Number) return number2json(Number)o); if(o instanceof Map) return map2json(Map)o); if(o instanceof Object) return array2json(Object)o); throw new RuntimeException(Unsupported
22、type :+o.getClass().getName(); /*Servlet 输出json response.setContentType(application/json;charset=UTF-8); response.setCharacterEncoding(UTF-8); PrintWriter pw = response.getWriter(); pw.write(JSonUtil.tojson(obj); pw.flush(); */5.Stirng encode 转ucs2码双字节publicclassStringUtil publicstaticStringStringTo
23、Hex(String input) String result = ; if (input != null) byte bytes = null; try bytes = input.getBytes(UTF-16BE); catch (Exception e) / TODO Auto-generated catch block returnnull; StringBuffer reValue = newStringBuffer(); StringBuffer tem = newStringBuffer(); for (int i = 0; i bytes.length; i+) tem.de
24、lete(0, tem.length(); tem.append(Integer.toHexString(bytesi & 0xFF); if (tem.length() = 1) tem.insert(0, 0); reValue.append(tem); result = reValue.toString().toUpperCase(); return result; else return; publicstaticStringHexToUTF16BE(String input) Stringresult = ; if (input != null) byte bytes1 = newb
25、yteinput.length() / 2; for (int i = 0; i input.length(); i += 2) bytes1i / 2 = (byte) (Integer.parseInt(input.substring(i, i + 2), 16); try result = newString(bytes1, UTF-16BE); catch (UnsupportedEncodingException e) / TODO Auto-generated catch block return null; return result; else return ; 6.Notif
26、ication实例NotificationManager notificationManager=(NotificationManager)context.getSystemService(NOTIFICATION_SERVICE); /定义一个Notification Notification m_notification = newNotification(); /设置Notification的各种属性 /设置通知在状态栏的图标 m_notification.icon = R.drawable.icon; /当我们点击通知时显示的内容 m_notification.tickerText =
27、 BUTTON1通知内容; /通知时发出的默认声音 m_notification.defaults = Notification.DEFAULT_SOUND; /设置通知显示的参数 Intent intent = newIntent(); PendingIntent m_pendingIntent = PendingIntent.getActivity(testNotification.this,0,intent,0); m_notification.setLatestEventInfo(testNotification.this,BUTTON,BUTTON1通知内容,m_pendingIntent); /开始执行通知 i+; notificationManager.notify(i,m_notification);7.POSTURL TheardpublicclassPostThreadextendsThread privatestaticContextcontex
copyright@ 2008-2022 冰豆网网站版权所有
经营许可证编号:鄂ICP备2022015515号-1