c#如何写与andriod之间的接口

2024-10-27 01:04:36

1、由于我对C#比较熟悉,所以我优先使用自己熟悉的技术来搭建WebService的项目。很简单我们就用VS工具创建一个Web服务应用程序(VS2008,而从VS2010开始优先使用WCF来创建服务应用程序了,不过用WCF框架创建WebService也是很容易的)。

c#如何写与andriod之间的接口

3、这个方法是我从网上随便找到的一个方法,比较土了,就是直接拼接JSON字符串(无所谓,这不是我们要关心的重点)。WebService端准备好,就可以将其发布到IIS。发布方法跟网站一样,如果是本机的话,可以直接测试WebService方法返回得到的结果,比如调用后会得到如下结果:这里肯定有人问,这外面是XML,里面又是JSON,这不是“四不像”吗?是的,我这样做是想说明一点,WebService是基于Soap的,数据传输的格式就是XML,所以这里得到XML文档是理所当然。如果你想得到纯净的JSON字符串,可以使用C#中的WCF框架(可以指定客户端返回JSON格式)或者Java中的Servlet(直接刷出JSON文本)。好,接下来我们要做两件事:1、请求这个WebService得到这个JSON字符串2、格式化这个JSON字符串在Android中显示我们先提供一个助手类,这是我自己动手封装了一下这两个操作所需要的方法。

4、/*** @author gary.gu 助手类*/ public final class Ut坡纠课柩il { /** * @param nameSpace WS的命名空间 * @param methodName WS的方法名 * @param wsdl WS的wsdl的完整路径名 * @param params WS的方法所需要的参数 * @return SoapObject对象 */ public static SoapObject callWS(String nameSpace, String methodName, String wsdl, Map<String, Object> params) { final String SOAP_ACTION = nameSpace + methodName; SoapObject soapObject = new SoapObject(nameSpace, methodName); if ((params != null) && (!params.isEmpty())) { Iterator<Entry<String, Object>> it = params.entrySet().iterator(); while (it.hasNext()) { Map.Entry<String, Object> e = (Map.Entry<String, Object>) it .next(); soapObject.addProperty(e.getKey(), e.getValue()); } } SoapSerializationEnvelope envelope = new SoapSerializationEnvelope( SoapEnvelope.VER11); envelope.bodyOut = soapObject; // 兼容.NET开发的Web Service envelope.dotNet = true; HttpTransportSE ht = new HttpTransportSE(wsdl); try { ht.call(SOAP_ACTION, envelope); if (envelope.getResponse() != null) { SoapObject result = (SoapObject) envelope.bodyIn; return result; } else { return null; } } catch (Exception e) { Log.e("error", e.getMessage()); } return null; } /** * * @param result JSON字符串 * @param name JSON数组名称 * @param fields JSON字符串所包含的字段 * @return 返回List<Map<String,Object>>类型的列表,Map<String,Object>对应于 "id":"1"的结构 */ public static List<Map<String, Object>> convertJSON2List(String result, String name, String[] fields) { List<Map<String, Object>> list = new ArrayList<Map<String, Object>>(); try { JSONArray array = new JSONObject(result).getJSONArray(name); for (int i = 0; i < array.length(); i++) { JSONObject object = (JSONObject) array.opt(i); Map<String, Object> map = new HashMap<String, Object>(); for (String str : fields) { map.put(str, object.get(str)); } list.add(map); } } catch (JSONException e) { Log.e("error", e.getMessage()); } return list; } }

5、Tips:我们都知道C#中给方法加注释,可以按3次“/”,借助于VS就可以自动生成。而在Eclipse当中,可以在方法上面输入“/**”然后按下回车就可以自动生成。

6、publicclassTestWSextendsActivity{@Overrideprotectedvoi颊俄岿髭donCreate(BundlesavedInstanceState){super.onCreate(savedInstanceState);RelativeLayoutl=newRelativeLayout(this);Buttonbutton=newButton(l.getContext());button.setText("点击本机webservice");l.addView(button);setContentView(l);button.setOnClickListener(newView.OnClickListener(){@OverridepublicvoidonClick(Viewv){finalStringnameSpace="http://tempuri.org/";finalStringmethodName="DataTableTest";finalStringwsdl="http://10.77.137.119:8888/webserviceTest/Service1.asmx?WSDL";//调用WebService返回SoapObject对象SoapObjectsoapObject=Util.callWS(nameSpace,methodName,wsdl,null);if(soapObject!=null){//获得soapObject对象的DataTableTestResult属性的值Stringresult=soapObject.getProperty("DataTableTestResult").toString();Toast.makeText(TestWS.this,result,Toast.LENGTH_SHORT).show();try{//将JSON字符串转换为List的结构List<Map<String,Object>>list=Util.convertJSON2List(result,"Result_List",newString[]{"id","name","email"});//通过Intent将List传入到新的ActivityIntentnewIntent=newIntent(TestWS.this,GridViewTest.class);Bundlebundle=newBundle();//List一定是一个Serializable类型bundle.putSerializable("key",(Serializable)list);newIntent.putExtras(bundle);//启动新的ActivitystartActivity(newIntent);}catch(Exceptione){e.printStackTrace();}}else{System.out.println("Thisisnull...");}}});}}

7、这里面有两点需要注意:1、这个Activity并没有加载layout布局文件,而是通过代码创建了一个Button,这也是一种创建视图的方法。2、通过I荏鱿胫协ntent对象,我们将List<Map<String,Object>>传入到了新的Activity当中,这种Intent之间的传值方式需要注意。publicclassGridViewTestextendsActivity{GridViewgrid;@OverrideprotectedvoidonCreate(BundlesavedInstanceState){super.onCreate(savedInstanceState);setContentView(R.layout.activity_gridview);Intentintent=this.getIntent();Bundlebundle=intent.getExtras();//获得传进来的List<Map<String,Object>>对象@SuppressWarnings("unchecked")List<Map<String,Object>>list=(List<Map<String,Object>>)bundle.getSerializable("key");//通过findViewById方法找到GridView对象grid=(GridView)findViewById(R.id.grid01);//SimpleAdapter适配器填充//1.context当前上下文,用this表示,或者GridViewTest.this//2.dataAListofMaps.要求是List<Map<String,Object>>结构的列表,即数据源//3.resource布局文件//4.from从哪里来,即提取数据源List中的哪些key//5.to到哪里去,即填充布局文件中的控件SimpleAdapteradapter=newSimpleAdapter(this,list,R.layout.list_item,newString[]{"id","name","email"},newint[]{R.id.id,R.id.name,R.id.email});//将GridView和适配器绑定grid.setAdapter(adapter);}}

8、先获得传过来的List对象,然后通过SimpleAdapter绑定到GridView。activity_gridview.xml 布局文件:<?xmlversion="1.0"encoding="utf-8"?><LinearLayoutxmlns:android="http://schemas.android.com/apk/res/android"android:layout_width="match_parent"android:layout_height="match_parent"android:orientation="vertical"><GridViewandroid:id="@+id/grid01"android:layout_width="fill_parent"android:layout_height="wrap_content"android:horizontalSpacing="1pt"android:verticalSpacing="1pt"android:numColumns="3"android:gravity="center"/></LinearLayout>

9、list_item.xml 布局文件:<?xmlversion="1.0"encoding="utf-8"?><LinearLayoutxmlns:android="http://schemas.android.com/apk/res/android"android:layout_width="match_parent"android:layout_height="wrap_content"android:gravity="center_vertical"android:orientation="vertical"><TextViewandroid:id="@+id/id"android:layout_width="wrap_content"android:layout_height="wrap_content"/><TextViewandroid:id="@+id/name"android:layout_width="wrap_content"android:layout_height="wrap_content"/><TextViewandroid:id="@+id/email"android:layout_width="wrap_content"android:layout_height="wrap_content"/></LinearLayout>

10、AndroidManifest.xml完整配置:<?xmlversion="1.0"encoding="utf-8"?><manifestxmlns:android="http://schemas.android.com/apk/res/android"package="com.example.webservicedemo"android:versionCode="1"android:versionName="1.0"><uses-sdkandroid:minSdkVersion="8"android:targetSdkVersion="14"/><uses-permissionandroid:name="android.permission.INTERNET"/><applicationandroid:allowBackup="true"android:icon="@drawable/ic_launcher"android:label="@string/app_name"android:theme="@style/AppTheme"><activityandroid:name=".TestWS"android:label="@string/app_name"><intent-filter><actionandroid:name="android.intent.action.MAIN"/><categoryandroid:name="android.intent.category.LAUNCHER"/></intent-filter></activity><activityandroid:name=".GridViewTest"android:label="@string/app_name"></activity></application></manifest>

猜你喜欢