版权说明:本文档由用户提供并上传,收益归属内容提供方,若内容存在侵权,请进行举报或认领
文档简介
【移动应用开发技术】
挑战独立开发项目能力--IT蓝豹
做了5年的android开发,今天没事写写刚入行不久的时候第一次独立开发项目的心得体会,
当时我刚工作8个月,由于公司运营不善倒闭了,在2011年3月份我开始准备跳槽,
看了一周android笔试题和面试题后,然后就去找工作,当时去面试的时候说自己有独立项目开发的经验。
结果面上了几家公司,后来选择一家游戏公司,开始游戏开发的生涯。当时我去的时候就android组就我一个人,
也没有人带领,去公司一个月后公司决定要我把网游游戏移植到手游,那时候确实没有独立开发项目的经验。
但是又只有一个人做,没办法只有自己慢慢研究,那时候没有像现在资源多,网上随便找。
还是坚持慢慢从网络框架一步一步开始搭建。当时独立做完项目后感觉个人技术能力瞬间提高了很多,因为不在还怕独立承担项目了。
希望我的感受能给同样刚入行的朋友能给与帮助。如今本人自己做一个技术网站:IT蓝豹()
当时使用的网络框架是HttpClient,先实现ReceiveDataListener接口用来接收数据返回,然后设置如下代码调用
调用方法:
privatevoidinitHttpClient(){
if(mHttpClient==null){
mHttpClient=HttpClientFactory
.newInstance(Constants.CONNECTION_TIMEOUT);
mHttpTransport=newHttpTransport(mHttpClient);
mHttpTransport.setReceiveDataListener(this);
}
}
网络请求代码部分如下:HttpClientFactory类
importjava.io.InputStream;importjava.security.KeyManagementException;importjava.security.KeyStore;importjava.security.KeyStoreException;importjava.security.NoSuchAlgorithmException;importjava.security.UnrecoverableKeyException;importorg.apache.http.HttpVersion;importorg.apache.http.client.HttpClient;importorg.apache.http.conn.params.ConnManagerParams;importorg.apache.http.conn.scheme.PlainSocketFactory;importorg.apache.http.conn.scheme.Scheme;importorg.apache.http.conn.scheme.SchemeRegistry;importorg.apache.http.impl.client.DefaultHttpClient;importorg.apache.http.impl.conn.tsccm.ThreadSafeClientConnManager;importorg.apache.http.params.BasicHttpParams;importorg.apache.http.params.HttpConnectionParams;importorg.apache.http.params.HttpParams;importorg.apache.http.params.HttpProtocolParams;/**
*Afactoryclasstoobtainasetup{@linkHttpClient}instancetobeused
*amongmultiplethreads.Thisinstanceshouldbekeptopenthroughoutthe
*applicationslifetimeandmustonlybeclosediftheclientisnotneeded
*anymore.
*<p>
*Thisfactorywillneverreturnasingletonsuchthateachcallto
*{@linkHttpClientFactory#newInstance(int,KeyStore)}resultsinanew
*instance.Commonlyonlyonecalltothismethodisneededforanapplicaiton.
*</p>
*/publicclassHttpClientFactory{
/**
*CreatesanewHttpClientinstancesetupwiththegiven{@linkKeyStore}.
*Theinstanceusesamulti-threadedconnectionmanagerwitha
*max-connectionsizesetto10.Aconnectionisreleasedbacktothepool
*oncetheresponse{@linkInputStream}isclosedorreaduntilEOF.
*<p>
*<b>Note:</b>AndroiddoesnotsupporttheJKSkeystoreprovider.For
*androidBKSshouldbeused.See<ahref="/">
*BouncyCastle</a>fordetails.
*</p>
*
*@paramaConnectionTimeout
*
theconnectiontimeoutforthis{@linkHttpClient}
*@paramaKeyStore
*
acryptographickeystorecontainingCA-Certificatesfor
*
trustedhosts.
*@returnanew{@linkHttpClient}instance.
*@throwsKeyManagementException
*
Ifthe{@linkKeyStore}initializationthrowsanexception
*@throwsNoSuchAlgorithmException
*
ifsslsocketfactorydoesnotsupportthekeystores
*
algorithm
*@throwsKeyStoreException
*
ifthe{@linkKeyStore}cannotbeopened.
*@throwsUnrecoverableKeyException
*
Ihavenotideawhenthishappens:)
*/
publicstaticHttpClientnewInstance(intaConnectionTimeout/*
*,KeyStore
*aKeyStore
*/)
/*
*throwsKeyManagementException,NoSuchAlgorithmException,
*KeyStoreException,UnrecoverableKeyException
*/{
finalHttpParamsparams=newBasicHttpParams();
HttpProtocolParams.setVersion(params,HttpVersion.HTTP_1_1);
HttpProtocolParams.setContentCharset(params,"UTF-8");
HttpConnectionParams.setConnectionTimeout(params,aConnectionTimeout);
HttpConnectionParams.setTcpNoDelay(params,false);
//finalSSLSocketFactorysocketFactory=new
//SSLSocketFactory(aKeyStore);
//socketFactory
//.setHostnameVerifier(SSLSocketFactory.STRICT_HOSTNAME_VERIFIER);
finalSchemeRegistryregistry=newSchemeRegistry();
registry.register(newScheme("http",newPlainSocketFactory(),80));
//registry.register(newScheme("https",socketFactory,443));
//connectionpoolislimitedto20connections
ConnManagerParams.setMaxTotalConnections(params,20);
//ServoConnPerRoutelimitsconnectionsperroute/host-currently
//thisisaconstant
ConnManagerParams.setMaxConnectionsPerRoute(params,
newAndhatConnPerRoute());
finalDefaultHttpClientdefaultHttpClient=newDefaultHttpClient(
newThreadSafeClientConnManager(params,registry),params);
returndefaultHttpClient;
}}
、、、、、、、、、、、、、、、、、、、、、、、、、、、、、、、、、、、、、、
HttpTransport类代码如下:packagecom.andhat.android.http;importjava.io.ByteArrayOutputStream;importjava.io.Closeable;importjava.io.IOException;importjava.io.InputStream;import.URI;importjava.util.List;importorg.apache.http.HttpHost;importorg.apache.http.HttpRequest;importorg.apache.http.HttpResponse;importorg.apache.http.HttpStatus;importorg.apache.http.NameValuePair;importorg.apache.http.StatusLine;importorg.apache.http.client.ClientProtocolException;importorg.apache.http.client.HttpClient;importorg.apache.http.client.entity.UrlEncodedFormEntity;importorg.apache.http.client.methods.HttpGet;importorg.apache.http.client.methods.HttpPost;importorg.apache.http.conn.params.ConnRoutePNames;importtocol.HTTP;importcom.andhat.android.utils.Constants;importcom.andhat.android.utils.UserPreference;importcom.andhat.android.utils.Utils;importandroid.content.Context;importandroid.os.Handler;importandroid.util.Log;publicclassHttpTransport{
privatefinalHttpClient_client;
privateReceiveDataListenermRecListener;
publicfinalstaticintRECEIVE_DATA_MIME_STRING=0;
publicfinalstaticintRECEIVE_DATA_MIME_PICTURE=1;
publicfinalstaticintRECEIVE_DATA_MIME_AUDIO=2;
publicHttpTransport(HttpClientaClient){
_client=aClient;
}
/**
*关闭连接
*/
publicvoidshutdown(){
if(_client!=null&&_client.getConnectionManager()!=null){
_client.getConnectionManager().shutdown();
}
}
publicvoidpost(booleanproxy,Handlerhandler,Stringurl,
List<NameValuePair>params,intmime)
throwsClientProtocolException,IOException{
if(proxy){
postByCMCCProxy(url,handler,params,mime);
}else{
post(URI.create(url),handler,params,mime);
}
}
privatevoidpostByCMCCProxy(Stringurl,Handlerhandler,
List<NameValuePair>params,intmime)
throwsClientProtocolException,IOException{
Stringhost=getHostByUrl(url);
Stringport=getPortByUrl(url);
HttpHostproxy=newHttpHost("72",80,"http");
HttpHosttarget=newHttpHost(host,Integer.parseInt(port),"http");
_client.getParams().setParameter(ConnRoutePNames.DEFAULT_PROXY,proxy);
HttpPostpost=newHttpPost(url);
if(params!=null&¶ms.size()>0){
post.setEntity(newUrlEncodedFormEntity(params,HTTP.UTF_8));
}
HttpResponsehttpResponse=_client.execute(target,post);
StatusLinestatusLine=httpResponse.getStatusLine();
finalintstatus=statusLine.getStatusCode();
if(status!=HttpStatus.SC_OK){
Stringmessage="HTTPResponsecode:"
+statusLine.getStatusCode()+"-"
+statusLine.getReasonPhrase();
Log.e("connectmsg",message);
thrownewIOException(message);
}
InputStreamin=httpResponse.getEntity().getContent();
longlength=httpResponse.getEntity().getContentLength();
byte[]data=receiveData(null,url,in,length);
if(mRecListener!=null){
mRecListener.receive(data,mime);
}
handler.sendEmptyMessage(Constants.MSG_THAN_FILE);
post.abort();
}
//54:8080/AnimeInterface/Interface.do
privatevoidpost(URIuri,Handlerhandler,List<NameValuePair>params,
intmime)throwsClientProtocolException,IOException{
Log.e("Goo","HttpTransportpost()");
//try{
HttpPostpost=newHttpPost(uri);
if(params!=null&¶ms.size()>0){
post.setEntity(newUrlEncodedFormEntity(params,HTTP.UTF_8));
}
HttpResponsehttpResponse=_client.execute(post);
StatusLinestatusLine=httpResponse.getStatusLine();
finalintstatus=statusLine.getStatusCode();
if(status!=HttpStatus.SC_OK){
Stringmessage="HTTPResponsecode:"
+statusLine.getStatusCode()+"-"
+statusLine.getReasonPhrase();
shutdown();
thrownewIOException(message);
}
InputStreamin=httpResponse.getEntity().getContent();
longlength=httpResponse.getEntity().getContentLength();
byte[]data=receiveData(null,uri.toString(),in,length);
if(mRecListener!=null){
mRecListener.receive(data,mime);
}
handler.sendEmptyMessage(Constants.MSG_THAN_FILE);
post.abort();
//}catch(IllegalStateExceptione){
//Log.e("Goo","程序异常");
//shutdown();
//e.printStackTrace();
//}
}
publicvoidget(booleanproxy,Contextcontext,Handlerhanlder,
Stringurl,intmime)throwsIOException{
if(proxy){
getByCMCCProxy(url,context,hanlder,mime);
}else{
get(URI.create(url),context,hanlder,mime);
}
UserPreference.ensureIntializePreference(context);
}
privateStringgetPortByUrl(Stringurl){
intstart=url.indexOf(":");
if(start<0)
return"80";
ints=url.indexOf(":",start+1);
if(s<0)
return"80";
inte=url.indexOf("/",s+1);
if(e<0){
returnurl.substring(s+1);
}else{
returnurl.substring(s+1,e);
}
}
privateStringgetHostByUrl(Stringurl){
intstart=url.indexOf(":");
if(start<0)
returnnull;
ints=url.indexOf(":",start+1);
if(s>=0)
returnurl.substring(0,s);
inte=url.indexOf("/",start+3);
if(e>=0){
returnurl.substring(0,e);
}else{
returnurl;
}
}
privatevoidgetByCMCCProxy(Stringurl,Contextcontext,Handlerhandler,
intmime)throwsClientProtocolException,IOException{
Log.e("requesturl",url);
//try{
Stringhost=getHostByUrl(url);
Stringport=getPortByUrl(url);
HttpHostproxy=newHttpHost("72",80,"http");
HttpHosttarget=newHttpHost(host,Integer.parseInt(port),"http");
_client.getParams().setParameter(ConnRoutePNames.DEFAULT_PROXY,proxy);
HttpGetget=newHttpGet(url);
HttpResponsehttpResponse=_client.execute(target,get);
StatusLinestatusLine=httpResponse.getStatusLine();
finalintstatus=statusLine.getStatusCode();
Log.e("getByCMCCProxystatus",""+status);
if(status!=HttpStatus.SC_OK){
Stringmessage="HTTPResponsecode:"
+statusLine.getStatusCode()+"-"
+statusLine.getReasonPhrase();
Log.e("getByCMCCProxy",message);
thrownewIOException(message);
}
InputStreamin=httpResponse.getEntity().getContent();
longlength=httpResponse.getEntity().getContentLength();
Log.e("Goo","GetRequestEntityLength:"+String.valueOf(length));
byte[]data=receiveData(context,url.toString(),in,length);
Log.e("Goo","datalength:"+String.valueOf(data.length));
if(mRecListener!=null&&length==data.length){
mRecListener.receive(data,mime);
}
handler.sendEmptyMessage(Constants.MSG_THAN_FILE);
get.abort();
//}catch(Exceptione){
//shutdown();
//e.printStackTrace();
//}
}
privatevoidget(URIuri,Contextcontext,Handlerhandler,intmime)
throwsIOException{
//try{
finalHttpGetget=newHttpGet(uri);
HttpResponsehttpResponse=_client.execute(get);
StatusLinestatusLine=httpResponse.getStatusLine();
finalintstatus=statusLine.getStatusCode();
if(status!=HttpStatus.SC_OK){
Stringmessage="HTTPResponsecode:"
+statusLine.getStatusCode()+"-"
+statusLine.getReasonPhrase();
thrownewIOException(message);
}
InputStreamin=httpResponse.getEntity().getContent();
longdownloadLength=httpResponse.getEntity().getContentLength();
byte[]data=receiveData(context,uri.toString(),in,downloadLength);
if(mRecListener!=null){
mRecListener.receive(data,mime);
}
handler.sendEmptyMessage(Constants.MSG_THAN_FILE);
get.abort();
//}catch(IllegalStateExceptione){
//shutdown();
//e.printStackTrace();
//}
}
publicbyte[]receiveData(Contextcontext,Stringurl,InputStreamin,longlength)
throwsIOException{
ByteArrayOutputStreambos=null;
intdownloadSize=0;
byte[]retval=null;
Stringstr=url;
String[]s=str.split("/");
for(Strings1:s){
if(s1.contains(".")&&s1.endsWith(".gif")
||s1.endsWith(".amr")){
saveFailFile(context,s1);
Log.e("Goo_downLoadSize","fileName:"+s1);
}
}
try{
bos=newByteArrayOutputStream();
byte[]buf=newbyte[1024];
intlen=0;
while((len=in.read(buf))!=-1){
bos.write(buf,0,len);
downloadSize=len+downloadSize;
}
Log.e("Goo_downLoadSize","downloadSize:"+downloadSize+"");
Log.e("Goo_downLoadSize","length:"+length+"");
if(downloadSize==length&&downloadSize!=-1){
saveFailFile(context,null);
}
retval=bos.toByteArray();
}catch(Exceptione){
e.printStackTrace();
}finally{
try{
温馨提示
- 1. 本站所有资源如无特殊说明,都需要本地电脑安装OFFICE2007和PDF阅读器。图纸软件为CAD,CAXA,PROE,UG,SolidWorks等.压缩文件请下载最新的WinRAR软件解压。
- 2. 本站的文档不包含任何第三方提供的附件图纸等,如果需要附件,请联系上传者。文件的所有权益归上传用户所有。
- 3. 本站RAR压缩包中若带图纸,网页内容里面会有图纸预览,若没有图纸预览就没有图纸。
- 4. 未经权益所有人同意不得将文件中的内容挪作商业或盈利用途。
- 5. 人人文库网仅提供信息存储空间,仅对用户上传内容的表现方式做保护处理,对用户上传分享的文档内容本身不做任何修改或编辑,并不能对任何下载内容负责。
- 6. 下载文件中如有侵权或不适当内容,请与我们联系,我们立即纠正。
- 7. 本站不保证下载资源的准确性、安全性和完整性, 同时也不承担用户因使用这些下载资源对自己和他人造成任何形式的伤害或损失。
最新文档
- 小学语文个人述职报告锦集8篇
- 现代水墨课程设计教案
- 企业业务集成与协同平台解决方案
- 养老院老人康复设施维修人员表彰制度
- 学校出纳工作总结
- 网络营销 第3版 教案汇 魏亚萍 1.2项目一定义、岗位 - 5-4信息流推广
- 房地产总企业行政规章制度
- 建筑垃圾运输合同
- 培训场地租赁协议书模板
- 公寓租赁合作合同
- 电仪工段工段长职位说明书
- 铝合金门窗制作工艺卡片 - 修改
- 恒亚水泥厂电工基础试题
- 简易送货单EXCEL打印模板
- 4s店信息员岗位工作职责
- 旋转导向+地质导向+水平井工具仪器介绍
- 无心磨的导轮及心高调整讲解
- 乳腺癌化疗的不良反应级处理ppt课件
- 艾灸疗法(课堂PPT)
- 给水管网设计计算说明书
- 四川地质勘查单位大全
评论
0/150
提交评论