在安卓开发中,经常会使用Webservice进行网络访问获取数据,由于网络访问在新的安卓开发中不允许在主线程中运行,所以需要在子线程进行实现,为了方便进行Webservice中多个方法的调用,对Webservice操作进行了继承Thread的方式,方便开发和代码优化,对此进行了总结,希望进行分享和讨论。
1.引入ksoap2-android-assembly-3.0.0jar包
2.编程Webservice线程类
public class MXNWebserviceThread extends Thread { String url="http://WebXml.com.cn"; String urlPartnerServiceApi="http://webservice.webxml.com.cn/WebServices/MobileCodeWS.asmx"; String methodName; //设置方法名 String result=null; //定义返回结果的字符串 private Handler handler; //设置消息,通知主线程进行相关操作 String mobileCode=null; //webservice 需要的参数 String userID=null; public MXNWebserviceThread(String methodName, Handler handler){ // 构造方法,传入方法名和消息 super(); this.methodName=methodName; this.handler=handler; } public void setMobileCode(String mobileCode) { this.mobileCode = mobileCode; } //设置方法对应的参数 public void setUserID(String userID) { this.userID = userID; } @Override public void run(){ String str = url + "/" +methodName; SoapObject localSoapObject = new SoapObject(url,methodName); if(methodName.equals("getMobileCodeInfo")){ //根据不同的方法名,设置不同的参数 System.out.println(mobileCode); localSoapObject.addProperty("mobileCode",mobileCode); localSoapObject.addProperty("userID",userID); } SoapSerializationEnvelope localSoapSerializationEnvelope = new SoapSerializationEnvelope(110); localSoapSerializationEnvelope.dotNet = true; localSoapSerializationEnvelope.bodyOut = localSoapObject; localSoapSerializationEnvelope.setOutputSoapObject(localSoapObject); HttpTransportSE localHttpTransportSE = new HttpTransportSE(urlPartnerServiceApi,3000); try //进行异常处理 { localHttpTransportSE.call(str, localSoapSerializationEnvelope); result=((SoapObject)localSoapSerializationEnvelope.bodyIn).getProperty(0).toString(); } catch (SocketTimeoutException socketTimeoutException) { socketTimeoutException.printStackTrace(); result="网络异常"; } catch (Exception localException) { localException.printStackTrace(); result="其他异常"; } Message msg=new Message(); msg.what=0x123; handler.sendMessage(msg); } public String getResult(){ //调用此方法获取返回结果 System.out.println(methodName + ":" + result); return result; } }
3.在Activity里进行调用
MXNWebserviceThread myThread;
Handler handler;
String result;
@Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_main); getInfo(); } private void getInfo(){ handler=new Handler(){ @Override public void handleMessage(Message msg) { if(msg.what==0x123){ //更新UI或其他操作 result=myThread.getResult(); if(result=="网络异常"||result=="其他异常"){ Toast.makeText(MainActivity.this,"异常",Toast.LENGTH_LONG).show(); }else{ Toast.makeText(MainActivity.this,result,Toast.LENGTH_LONG).show(); } } } }; myThread=new MXNWebserviceThread("getMobileCodeInfo",handler); myThread.setMobileCode("15022512067"); myThread.setUserID(""); myThread.start(); }
转载地址:http://blog.csdn.net/max1198/article/details/46907709
点击查看更多内容
为 TA 点赞
评论
共同学习,写下你的评论
评论加载中...
作者其他优质文章
正在加载中
感谢您的支持,我会继续努力的~
扫码打赏,你说多少就多少
赞赏金额会直接到老师账户
支付方式
打开微信扫一扫,即可进行扫码打赏哦