android常用的代码 直接复制粘贴可用.docx
《android常用的代码 直接复制粘贴可用.docx》由会员分享,可在线阅读,更多相关《android常用的代码 直接复制粘贴可用.docx(87页珍藏版)》请在冰豆网上搜索。
![android常用的代码 直接复制粘贴可用.docx](https://file1.bdocx.com/fileroot1/2023-1/26/46fc0e9c-2920-48ff-83ec-21c40838afcc/46fc0e9c-2920-48ff-83ec-21c40838afcc1.gif)
android常用的代码直接复制粘贴可用
1.FILE工具
//创建文件,参数包括路径(不能为空),文件名称,内容
publicstaticvoidmakefile(Stringpath,Stringfilename,Stringcontent){
Filedir=newFile(path);
if(!
dir.exists()){
dir.mkdir();
}
//dir.mkdir();
FilenewFile=null;
if(path!
=null){
newFile=newFile(dir.getAbsolutePath()+"/"+filename);
FileOutputStreamfos=null;
try{
newFile.createNewFile();
if(newFile.exists()&&newFile.canWrite()){
fos=newFileOutputStream(newFile);
fos.write(content.getBytes());
}
}catch(IOExceptione){
//TODOAuto-generatedcatchblock
e.printStackTrace();
}finally{
if(fos!
=null){
try{
fos.flush();
fos.close();
}catch(IOExceptione){
//TODO:
handleexception
}
}
}
}
}
2.下载图片工具
publicclassDownloadPicUtil{
/**
*
*@paramurl
*@paramfilename
*@return0没有图片;return1成功;return2IO异常;
*/
publicstaticintDownLoadBitmap(Stringurl,Stringfilename){
//TODOAuto-generatedmethodstub
InputStreaminputStream=null;
DefaultHttpClientclient=newDefaultHttpClient();
try{
HttpGetrequest=newHttpGet(url);
HttpResponseresponse=client.execute(request);
intstatusCode=response.getStatusLine().getStatusCode();
if(statusCode!
=HttpStatus.SC_OK){
return0;
}else{
HttpEntityentity=response.getEntity();
inputStream=entity.getContent();
Bitmapbitmap=BitmapFactory.decodeStream(inputStream);
//图片可以在这个时候存储到sdcard上
saveBitmap(bitmap,filename);
return1;
}
}catch(Exceptione){
//TODOAuto-generatedcatchblock
e.printStackTrace();
return2;
}finally{
if(inputStream!
=null){
try{
inputStream.close();
}catch(IOExceptione){
//TODOAuto-generatedcatchblock
e.printStackTrace();
}
}
}
}
publicstaticvoidsaveBitmap(BitmapbitName,Stringfilename){
Stringfilepath="/sdcard/baomi/";
Filef=newFile(filepath+filename);
FileOutputStreamfout=null;
try{
f.createNewFile();
fout=newFileOutputStream(f);
bitNpress(Bitmap.CompressFormat.PNG,100,fout);
fout.flush();
fout.close();
}catch(Exceptione){
e.printStackTrace();
}
}
}
3.http请求工具
publicclassHttpUtil{
publicstaticStringSESSION_ID=null;
publicstaticHttpResponsegetHttpResponse(HttpGetrequest)throwsClientProtocolException,IOException{
BasicHttpParamshttpParams=newBasicHttpParams();
LogService.getInstance().recordLog("进入getHttpResponse");
HttpConnectionParams.setConnectionTimeout(httpParams,
SysConfig.nConnectionTimeout);
LogService.getInstance().recordLog("超时时间为:
"+SysConfig.nConnectionTimeout);
HttpConnectionParams.setSoTimeout(httpParams,SysConfig.nSoTimeout);
LogService.getInstance().recordLog("Socket超时时间为:
"+SysConfig.nSoTimeout);
DefaultHttpClienthttpClient=newDefaultHttpClient(httpParams);
LogService.getInstance().recordLog("获得响应客户端");
HttpResponseresponse=httpClient.execute(request);
LogService.getInstance().recordLog("获得结果");
httpClient.getConnectionManager().shutdown();
LogService.getInstance().recordLog("关闭连接");
returnresponse;
}
publicstaticHttpResponsegetHttpResponse(HttpPostrequest)throwsClientProtocolException,IOException{
BasicHttpParamshttpParams=newBasicHttpParams();
HttpConnectionParams.setConnectionTimeout(httpParams,
SysConfig.nConnectionTimeout);
HttpConnectionParams.setSoTimeout(httpParams,SysConfig.nSoTimeout);
DefaultHttpClienthttpClient=newDefaultHttpClient(httpParams);
HttpResponseresponse=httpClient.execute(request);
httpClient.getConnectionManager().shutdown();
returnresponse;
}
//通过url发送post请求,并返回结果
publicstaticStringqueryStringForPost(Stringurl){
LogService.getInstance().recordLog("发送POST请求");
HttpPostrequest=newHttpPost(url);
Stringresult=null;
try{
HttpResponseresponse=HttpUtil.getHttpResponse(request);
LogService.getInstance().recordLog("POST返回状态为"+response.getStatusLine().getStatusCode());
if(response.getStatusLine().getStatusCode()==200){
result=EntityUtils.toString(response.getEntity());
returnresult;
}
}catch(Exceptione){
LogService.getInstance().recordLog("POST异常:
"+e.getMessage());
e.printStackTrace();
result="网络异常";
returnresult;
}
returnnull;
}
//通过url发送GET请求并返回结果
publicstaticStringqueryStringForGet(Stringurl){
LogService.getInstance().recordLog("发送GET请求");
Stringresult=null;
try{
ResponseHandlerresponseHandler=newBasicResponseHandler();
HttpClienthttpclient=newDefaultHttpClient();
LogService.getInstance().recordLog("提交的地址为:
"+url);
HttpGethttpget=newHttpGet(url);
result=httpclient.execute(httpget,responseHandler);
LogService.getInstance().recordLog("GET返回状态为"+result);
returnresult;
}catch(Exceptione){
LogService.getInstance().recordLog("GET异常:
"+e.getMessage());
e.printStackTrace();
result="网络异常";
returnresult;
}
}
//通过HttpPost发送POST请求,并返回结果
publicstaticStringqueryStringForPost(HttpPostrequest){
Stringresult=null;
try{
HttpResponseresponse=HttpUtil.getHttpResponse(request);
if(response.getStatusLine().getStatusCode()==200){
result=EntityUtils.toString(response.getEntity());
returnresult;
}
}catch(Exceptione){
e.printStackTrace();
result="网络异常";
returnresult;
}
returnnull;
}
}
4.JSon工具
publicclassJSonUtil{
publicstaticStringstring2json(Strings){
StringBuildersb=newStringBuilder(s.length()+20);
sb.append('\"');
for(inti=0;icharc=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;
case'\t':
sb.append("\\t");
break;
default:
sb.append(c);
}
}
sb.append('\"');
returnsb.toString();
}
publicstaticStringnumber2json(Numbernumber){
returnnumber.toString();
}
publicstaticStringboolean2json(Booleanbool){
returnbool.toString();
}
publicstaticStringmap2json(Mapmap){
if(map.isEmpty()){
return"[]";
}
StringBuildersb=newStringBuilder(map.size()<<4);
sb.append("{");
Setkeys=map.keySet();
for(Stringkey:
keys){
Objectvalue=map.get(key);
sb.append('\"');
sb.append(key);
sb.append('\"');
sb.append(":
");
sb.append(tojson(value));
sb.append(',');
}
sb.setCharAt(sb.length()-1,'}');
returnsb.toString();
}
publicstaticStringarray2json(Object[]array){
if(array.length==0){
return"[]";
}
StringBuildersb=newStringBuilder(array.length<<4);
sb.append("[");
for(Objecto:
array){
sb.append(tojson(o));
sb.append(',');
}
sb.setCharAt(sb.length()-1,']');
returnsb.toString();
}
publicstaticStringtojson(Objecto){
if(o==null)
return"null";
if(oinstanceofString)
returnstring2json((String)o);
if(oinstanceofBoolean)
returnboolean2json((Boolean)o);
if(oinstanceofNumber)
returnnumber2json((Number)o);
if(oinstanceofMap)
returnmap2json((Map)o);
if(oinstanceofObject[])
returnarray2json((Object[])o);
thrownewRuntimeException("Unsupportedtype:
"+o.getClass().getName());
}
/*Servlet输出json
response.setContentType("application/json;charset=UTF-8");
response.setCharacterEncoding("UTF-8");
PrintWriterpw=response.getWriter();
pw.write(JSonUtil.tojson(obj));
pw.flush();
*/
}
5.Stirngencode转ucs2码双字节
publicclassStringUtil{
publicstaticStringStringToHex(Stringinput){
Stringresult="";
if(input!
=null){
byte[]bytes=null;
try{
bytes=input.getBytes("UTF-16BE");
}catch(Exceptione){
//TODOAuto-generatedcatchblock
returnnull;
}
StringBufferreValue=newStringBuffer();
StringBuffertem=newStringBuffer();
for(inti=0;item.delete(0,tem.length());
tem.append(Integer.toHexString(bytes[i]&0xFF));
if(tem.length()==1){
tem.insert(0,'0');
}
reValue.append(tem);
}
result=reValue.toString().toUpperCase();
returnresult;
}else{
return"";
}
}
publicstaticStringHexToUTF16BE(Stringinput){
Stringresult="";
if(input!
=null){
byte[]bytes1=newbyte[input.length()/2];
for(inti=0;ibytes1[i/2]=(byte)(Integer.parseInt(input.substring(i,
i+2),16));
}
try{
result=newString(bytes1,"UTF-16BE");
}catch(UnsupportedEncodingExceptione){
//TODOAuto-generatedcatchblock
returnnull;
}
returnresult;
}else{
return"";
}
}
}
6.Notification实例
NotificationManagernotificationManager=(NotificationManager)context.getSystemService(NOTIFICATION_SERVICE);
//定义一个Notification
Notificationm_notification=newNotification();
//设置Notification的各种属性
//设置通知在状态栏的图标
m_notification.icon=R.drawable.icon;
//当我们点击通知时显示的内容
m_notification.tickerText="BUTTON1通知内容";
//通知时发出的默认声音
m_notification.defaults=Notification.DEFAULT_SOUND;
//设置通知显示的参数
Intentintent=newIntent();
PendingIntentm_pendingIntent=PendingIntent.getActivity(testNotification.this,0,intent,0);
m_notification.setLatestEventInfo(testNotification.this,"BUTTON","BUTTON1通知内容",m_pendingIntent);
//开始执行通知
i++;
notificationManager.notify(i,m_notification);
7.POSTURLTheard
publicclassPostThreadextendsThread{
privatestaticContextcontex