編輯:高級開發
筆者以前是學的Java EE,由於項目需要要開發android,所以臨時補了一個多星期,主要是手機端和服務器端交互,雙向開發的。
首先在服務器端,我采用的是SSH框架,struts 2集合了JSON插件,服務器和客戶端的信息交互采用的JSON來傳輸,由於在服務器端用了Struts 2,所以我就用裝了一個JSON插件。這樣,很輕易的就把服務器端的信息用JSON的形式發送到了手機端。以下是代碼:
首先,在服務器端搭建好SSH框架,具體細節就不在陳述。struts.XML配置如下:
- <packagename="login"extends="JSon-default">
- <actionname="login"class="com.jclick.test.LoginAction"method="login">
- <resulttype="JSon"><paramname="includePropertIEs">result</param></result>
- </action>
- </package>
- <packagename="login"extends="JSon-default">
- <actionname="login"class="com.jclick.test.LoginAction"method="login">
- <resulttype="JSon"><paramname="includePropertIEs">result</param></result>
- </action>
- </package>
手機端的代碼如下:
首先,手機端有一個緩存類,主要用於緩存一些手機端需要訪問的數據,這樣的好處是可以達達節省手機和服務器的交互,用單例實現的:
- packagecom.jclick.cache;
- importcom.jclick.bean.User;
- publicclassCache{
- privateUserUser;
- privateCache(){
- }
- /**構造單例*/
- privatestaticclassCacheHolder{
- privatestaticfinalCacheINSTANCE=newCache();
- }
- publicCachegetInstance(){
- returnCacheHolder.INSTANCE;
- }
- publicUsergetUser(){
- returnUser;
- }
- publicvoidsetUser(UserUser){
- this.User=User;
- }
- }
- packagecom.jclick.cache;
- importcom.jclick.bean.User;
- publicclassCache{
- privateUserUser;
- privateCache(){
- }
- /**構造單例*/
- privatestaticclassCacheHolder{
- privatestaticfinalCacheINSTANCE=newCache();
- }
- publicCachegetInstance(){
- returnCacheHolder.INSTANCE;
- }
- publicUsergetUser(){
- returnUser;
- }
- publicvoidsetUser(UserUser){
- this.User=User;
- }
- }
接著開始書寫手機端的協議,用戶向服務器發送請求,同時服務器反饋給手機端信息的:
- packagecom.jclick.protocol;
- importJava.io.BufferedReader;
- importJava.io.InputStreamReader;
- importJava.util.ArrayList;
- importJava.util.List;
- importorg.apache.http.HttpResponse;
- importorg.apache.http.NameValuePair;
- importorg.apache.http.client.HttpClIEnt;
- importorg.apache.http.clIEnt.entity.UrlEncodedFormEntity;
- importorg.apache.http.clIEnt.methods.HttpPost;
- importorg.apache.http.impl.client.DefaultHttpClIEnt;
- importorg.apache.http.message.BasicNameValuePair;
- importorg.json.JSONException;
- importorg.json.JSONObject;
- publicclassBaseProtocol{
- privateStringBuildersb=newStringBuilder();
- privateHttpClienthttpClIEnt;
- privateHttpPosthttpRequest;
- privateHttpResponseresponse;
- privateList<NameValuePair>nameValuePair=newArrayList<NameValuePair>();
- BaseProtocol(){
- httpClient=newDefaultHttpClIEnt();
- }
- /**
- *向服務器端發送請求
- *
- *@paramurl
- *@throwsException
- */
- protectedvoidpack(Stringurl)throwsException{
- httpClient=newDefaultHttpClIEnt();
- httpRequest=newHttpPost(url);
- httpRequest.setEntity(newUrlEncodedFormEntity(nameValuePair));
- response=httpClIEnt.execute(httpRequest);
- }
- /**
- *得到返回數據
- *
- *@paramurl
- *@return
- *@throwsException
- */
- protectedvoidparse()throwsException{
- //TODO狀態處理500200
- if(response.getStatusLine().getStatusCode()==200){
- BufferedReaderbufferedReader2=newBufferedReader(
- newInputStreamReader(response.getEntity().getContent()));
- for(Strings=bufferedReader2.readLine();s!=null;s=bufferedReader2
- .readLine()){
- sb.append(s);
- }
- }
- }
- /**
- *向服務器發送信息
- *
- *@paramkey
- *@paramvalue
- */
- publicvoidaddNameValuePair(Stringkey,Stringvalue){
- nameValuePair.add(newBasicNameValuePair(key,value));
- }
- /**
- *返回JSONObject對象數據模型
- *
- *@return
- *@throwsJSONException
- */
- publicJSONObjectgetJSON()throwsJSONException{
- returnnewJSONObject(sb.toString());
- }
- }
- packagecom.jclick.protocol;
- importJava.io.BufferedReader;
- importJava.io.InputStreamReader;
- importJava.util.ArrayList;
- importJava.util.List;
- importorg.apache.http.HttpResponse;
- importorg.apache.http.NameValuePair;
- importorg.apache.http.client.HttpClIEnt;
- importorg.apache.http.clIEnt.entity.UrlEncodedFormEntity;
- importorg.apache.http.clIEnt.methods.HttpPost;
- importorg.apache.http.impl.client.DefaultHttpClIEnt;
- importorg.apache.http.message.BasicNameValuePair;
- importorg.json.JSONException;
- importorg.json.JSONObject;
- publicclassBaseProtocol{
- privateStringBuildersb=newStringBuilder();
- privateHttpClienthttpClIEnt;
- privateHttpPosthttpRequest;
- privateHttpResponseresponse;
- privateList<NameValuePair>nameValuePair=newArrayList<NameValuePair>();
- BaseProtocol(){
- httpClient=newDefaultHttpClIEnt();
- }
- /**
- *向服務器端發送請求
- *
- *@paramurl
- *@throwsException
- */
- protectedvoidpack(Stringurl)throwsException{
- httpClient=newDefaultHttpClIEnt();
- httpRequest=newHttpPost(url);
- httpRequest.setEntity(newUrlEncodedFormEntity(nameValuePair));
- response=httpClIEnt.execute(httpRequest);
- }
- /**
- *得到返回數據
- *
- *@paramurl
- *@return
- *@throwsException
- */
- protectedvoidparse()throwsException{
- //TODO狀態處理500200
- if(response.getStatusLine().getStatusCode()==200){
- BufferedReaderbufferedReader2=newBufferedReader(
- newInputStreamReader(response.getEntity().getContent()));
- for(Strings=bufferedReader2.readLine();s!=null;s=bufferedReader2
- .readLine()){
- sb.append(s);
- }
- }
- }
- /**
- *向服務器發送信息
- *
- *@paramkey
- *@paramvalue
- */
- publicvoidaddNameValuePair(Stringkey,Stringvalue){
- nameValuePair.add(newBasicNameValuePair(key,value));
- }
- /**
- *返回JSONObject對象數據模型
- *
- *@return
- *@throwsJSONException
- */
- publicJSONObjectgetJSON()throwsJSONException{
- returnnewJSONObject(sb.toString());
- }
- }
接著是登陸協議,在這裡我只是模擬登陸使用的一個類,僅供大家參考:
- packagecom.jclick.protocol;
- importorg.json.JSONObject;
- importcom.jclick.bean.User;
- publicclassLoginProtocolextendsBaseProtocol{
- privatefinalstaticStringURL="http://localhost:8080/test/login";
- publicbooleancheckLogin(Userusr){
- try{
- pack(URL);
- parse();
- JSONObjectobj=this.getJSON();
- if(obj.getString("result").equals("failed")){
- returnfalse;
- }else{
- returntrue;
- }
- }catch(Exceptione){
- e.printStackTrace();
- returnfalse;
- }
- }
- }
- packagecom.jclick.protocol;
- importorg.json.JSONObject;
- importcom.jclick.bean.User;
- publicclassLoginProtocolextendsBaseProtocol{
- privatefinalstaticStringURL="http://localhost:8080/test/login";
- publicbooleancheckLogin(Userusr){
- try{
- pack(URL);
- parse();
- JSONObjectobj=this.getJSON();
- if(obj.getString("result").equals("failed")){
- returnfalse;
- }else{
- returntrue;
- }
- }catch(Exceptione){
- e.printStackTrace();
- returnfalse;
- }
- }
- }
然後是User實體類,主要用於保存用戶信息:
- packagecom.jclick.bean;
- publicclassUser{
- privateStringusername;
- privateStringpassWord;
- publicStringgetUsername(){
- returnusername;
- }
- publicvoidsetUsername(Stringusername){
- this.username=username;
- }
- publicStringgetPassWord(){
- returnpassWord;
- }
- publicvoidsetPassword(StringpassWord){
- this.password=passWord;
- }
- }
- packagecom.jclick.bean;
- publicclassUser{
- privateStringusername;
- privateStringpassWord;
- publicStringgetUsername(){
- returnusername;
- }
- publicvoidsetUsername(Stringusername){
- this.username=username;
- }
- publicStringgetPassWord(){
- returnpassWord;
- }
- publicvoidsetPassword(StringpassWord){
- this.password=passWord;
- }
- }
最後就是LoginActivity裡邊判斷登陸的代碼了,詳細代碼不再貼出來了,僅貼一個判斷登陸的代碼:
- privatevoidcheckedData(){
- username=((EditText)findVIEwById(R.id.username)).getText().toString();
- password=((EditText)findVIEwById(R.id.passWord)).getText().toString();
- Useruser=newUser();
- user.setUsername(username);
- user.setPassword(passWord);
- LoginProtocollogin=newLoginProtocol();
- booleanresult=login.checkLogin(user);
- if(result){SpiderCache.getInstance().setUserSession(user);
- Toast.makeText(getApplicationContext(),"登錄成功",1000).show();
- Intentintent=newIntent();
- intent.setClass(LoginActivity.this,WelcomeActivity.class);
- startActivity(intent);
- }else{Toast.makeText(LoginActivity.this,"密碼或用戶名不匹配,請重新輸入!",1000).show();
- }
- }
- privatevoidcheckedData(){
- username=((EditText)findVIEwById(R.id.username)).getText().toString();
- password=((EditText)findVIEwById(R.id.passWord)).getText().toString();
- Useruser=newUser();
- user.setUsername(username);
- user.setPassword(passWord);
- LoginProtocollogin=newLoginProtocol();
- booleanresult=login.checkLogin(user);
- if(result){ SpiderCache.getInstance().setUserSession(user);
- Toast.makeText(getApplicationContext(),"登錄成功",1000).show();
- Intentintent=newIntent();
- intent.setClass(LoginActivity.this,WelcomeActivity.class);
- startActivity(intent);
- }else{ Toast.makeText(LoginActivity.this,"密碼或用戶名不匹配,請重新輸入!",1000).show();
- }
- }
以上代碼為了跟大家分享一下,感覺手機端和服務器雙向開發非常過瘾。同時對android的興趣大大提升,它也沒有我們想象中的那麼難。
做出相應的處理,比如掛掉電話、比如靜音等等。 Demo 分析: 下面通過一個小DEMO 來講解一下廣播在android 中如何編寫,在Demo中我們設置了一個按鈕為
android 3.0是谷歌用來進軍平板市場的利器,但在iPad發布會上,由於應用稀少發展後勁不足而被史蒂夫·喬布斯(Steve Paul Jobs)特地提出來嘲笑。i
隨著android應用系統的問世,廣大的Android迷都平復了心中的願望,android 作為谷歌企業戰略的重要組成部分,一定在會手機操作系統界占有一席之地,相信一定
Javascript:return big(this) width=625 height=200 src=/School/UploadFiles_7810/201203