Android之与服务端通信一

本文详细介绍了如何使用手机访问web应用,包括建立web工程、创建servlet、处理客户端信息和服务器响应等关键步骤。

1.Android访问Web应用

这里我们写一个用手机访问web应用的demo,整体思路是:

 

1、通过手机访问web应用,并向服务器发送信息。

2、服务器接收客户端信息。

3、服务器处理数据(解析xml文件)。

4、重组信息,返回给客户端。

 

 

一、服务器代码

首先,建立一个web工程:Test1

 

然后新建一个servlet,用于手机客户端调用。

 

  1. import java.io.BufferedReader;  
  2. import java.io.BufferedWriter;  
  3. import java.io.FileNotFoundException;  
  4. import java.io.IOException;  
  5. import java.io.InputStreamReader;  
  6. import java.io.OutputStreamWriter;  
  7. import java.io.PrintWriter;  
  8. import java.util.ArrayList;  
  9. import java.util.List;  
  10. import javax.servlet.ServletException;  
  11. import javax.servlet.ServletInputStream;  
  12. import javax.servlet.ServletOutputStream;  
  13. import javax.servlet.http.HttpServlet;  
  14. import javax.servlet.http.HttpServletRequest;  
  15. import javax.servlet.http.HttpServletResponse;  
  16. import javax.xml.parsers.DocumentBuilder;  
  17. import javax.xml.parsers.DocumentBuilderFactory;  
  18. import javax.xml.parsers.ParserConfigurationException;  
  19.   
  20. import org.w3c.dom.Document;  
  21. import org.w3c.dom.Node;  
  22. import org.w3c.dom.NodeList;  
  23. import org.xml.sax.SAXException;  
  24.   
  25.   
  26. public class ServletDemo extends HttpServlet {  
  27.   
  28.     /** 
  29.      * Constructor of the object. 
  30.      */  
  31.     public ServletDemo() {  
  32.         super();  
  33.     }  
  34.   
  35.     /** 
  36.      * Destruction of the servlet. <br> 
  37.      */  
  38.     public void destroy() {  
  39.         super.destroy();   
  40.     }  
  41.   
  42.     /** 
  43.      * The doGet method of the servlet. <br> 
  44.      * 
  45.      * This method is called when a form has its tag value method equals to get. 
  46.      *  
  47.      * @param request the request send by the client to the server 
  48.      * @param response the response send by the server to the client 
  49.      * @throws ServletException if an error occurred 
  50.      * @throws IOException if an error occurred 
  51.      */  
  52.     public void doGet(HttpServletRequest request, HttpServletResponse response)  
  53.             throws ServletException, IOException {  
  54.   
  55.         response.setContentType("text/html");  
  56.         this.doPost(request, response);  
  57.     }  
  58.   
  59.     /** 
  60.      * The doPost method of the servlet. <br> 
  61.      * 
  62.      * This method is called when a form has its tag value method equals to post. 
  63.      *  
  64.      * @param request the request send by the client to the server 
  65.      * @param response the response send by the server to the client 
  66.      * @throws ServletException if an error occurred 
  67.      * @throws IOException if an error occurred 
  68.      */  
  69.     public void doPost(HttpServletRequest request, HttpServletResponse response)  
  70.             throws ServletException, IOException {  
  71.   
  72.         response.setContentType("text/html");  
  73.           
  74.         //获得客户端发送的数据  
  75.         ServletInputStream is = request.getInputStream();  
  76.         BufferedReader reader = new BufferedReader(new InputStreamReader(is));  
  77.         String requestString = reader.readLine();  
  78.         //向客户端返回数据  
  79.         String responseString = processStringRequest(requestString,request);  
  80.         ServletOutputStream os = response.getOutputStream();  
  81.         BufferedWriter writer = new BufferedWriter(new OutputStreamWriter(os));  
  82.         writer.write(responseString);  
  83.         //关闭资源  
  84.         writer.flush();  
  85.         writer.close();  
  86.         reader.close();  
  87.         os.close();  
  88.   
  89.     }  
  90.   
  91.     /** 
  92.      * Initialization of the servlet. <br> 
  93.      * 
  94.      * @throws ServletException if an error occure 
  95.      */  
  96.     public void init() throws ServletException {  
  97.           
  98.     }  
  99.       
  100.     private String processStringRequest(String requestString,HttpServletRequest request){  
  101.           
  102.   
  103.         List list = this.toRead(request.getRealPath("/")+"user.xml");  
  104.         String response = "";  
  105.         if(null != list && list.size() > 0){  
  106.             for(int i = 0 ; i < list.size(); i++){  
  107.                 JavaBean a = (JavaBean)list.get(i);  
  108.                 response += "client say:"+requestString+"server say: this is your info:"+a.getName()+"@"+a.getSex()+"@"+a.getAge();  
  109.                 System.out.println(a.getName());  
  110.             }  
  111.         }else{  
  112.             response = "is wrong!";  
  113.         }  
  114.   
  115.         return response;  
  116.     }  
  117.       
  118.     public List toRead(String filename) {  
  119.   
  120.         List alist = new ArrayList();  
  121.           
  122.         try {  
  123.               
  124.             DocumentBuilderFactory dbf = DocumentBuilderFactory.newInstance();  
  125.             DocumentBuilder db = dbf.newDocumentBuilder();  
  126.             Document document = db.parse(filename);  
  127.             NodeList employees = document.getChildNodes();  
  128.             for (int i = 0; i < employees.getLength(); i++) {  
  129.                   
  130.                 Node employee = employees.item(i);  
  131.                 NodeList employeeInfo = employee.getChildNodes();  
  132.                 for (int j = 0; j < employeeInfo.getLength(); j++) {  
  133.                     Node node = employeeInfo.item(j);  
  134.                     NodeList employeeMeta = node.getChildNodes();  
  135.                     JavaBean bean = new JavaBean();  
  136.                     boolean status = false;  
  137.                     for (int k = 0; k < employeeMeta.getLength(); k++) {  
  138.                         if(employeeMeta.item(k).getNodeName().equals("name")){  
  139.                             bean.setName(employeeMeta.item(k).getTextContent());  
  140.                         }  
  141.                         if(employeeMeta.item(k).getNodeName().equals("age")){  
  142.                             bean.setAge(employeeMeta.item(k).getTextContent());  
  143.                         }  
  144.                         if(employeeMeta.item(k).getNodeName().equals("sex")){  
  145.                             bean.setSex(employeeMeta.item(k).getTextContent());  
  146.                         }  
  147.                         status = true;  
  148.                     }  
  149.                     if(status){  
  150.                         alist.add(bean);  
  151.                     }  
  152.                 }  
  153.             }  
  154.         } catch (FileNotFoundException e) {  
  155.             System.out.println(e.getMessage());  
  156.         } catch (ParserConfigurationException e) {  
  157.             System.out.println(e.getMessage());  
  158.         } catch (SAXException e) {  
  159.             System.out.println(e.getMessage());  
  160.         } catch (IOException e) {  
  161.             System.out.println(e.getMessage());  
  162.         }  
  163.         return alist;  
  164.           
  165.     }  
  166.   
  167. }  

 

web工程的web.xml

 

  1. <?xml version="1.0" encoding="UTF-8"?>  
  2. <web-app version="2.4"   
  3.     xmlns="http://java.sun.com/xml/ns/j2ee"   
  4.     xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"   
  5.     xsi:schemaLocation="http://java.sun.com/xml/ns/j2ee   
  6.     http://java.sun.com/xml/ns/j2ee/web-app_2_4.xsd">  
  7.   <servlet>  
  8.     <description>This is the description of my J2EE component</description>  
  9.     <display-name>This is the display name of my J2EE component</display-name>  
  10.     <servlet-name>ServletDemo</servlet-name>  
  11.     <servlet-class>ServletDemo</servlet-class>  
  12.   </servlet>  
  13.   
  14.   <servlet-mapping>  
  15.     <servlet-name>ServletDemo</servlet-name>  
  16.     <url-pattern>/servlet/ServletDemo</url-pattern>  
  17.   </servlet-mapping>  
  18.   <welcome-file-list>  
  19.     <welcome-file>index.jsp</welcome-file>  
  20.   </welcome-file-list>  
  21. </web-app>  

 

 

xml文件格式

 

  1. <?xml version="1.0" encoding="GB2312" standalone="no"?>  
  2. <employees>  
  3.     <employee>  
  4.         <name>user0</name>  
  5.         <sex>m</sex>  
  6.         <age>30</age>  
  7.     </employee>  
  8. </employees>  

 

 

解析xml文件用到的javabean:

 

  1. public class JavaBean {  
  2.       
  3.     private String name;  
  4.     private String sex;  
  5.     private String age;  
  6.     public String getAge() {  
  7.         return age;  
  8.     }  
  9.     public void setAge(String age) {  
  10.         this.age = age;  
  11.     }  
  12.     public String getName() {  
  13.         return name;  
  14.     }  
  15.     public void setName(String name) {  
  16.         this.name = name;  
  17.     }  
  18.     public String getSex() {  
  19.         return sex;  
  20.     }  
  21.     public void setSex(String sex) {  
  22.         this.sex = sex;  
  23.     }  
  24. }  

 

 

这样  服务器端的工作就准备好了,启动、等待客户端连接。

 

二,客户端代码

 

1、新建Android工程

 

2、修改main。xml文件

 

  1. <?xml version="1.0" encoding="utf-8"?>  
  2. <LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"  
  3.     android:orientation="vertical"  
  4.     android:layout_width="fill_parent"  
  5.     android:layout_height="fill_parent"  
  6.     >  
  7. <EditText   
  8.     android:layout_height="wrap_content"  
  9.     android:id="@+id/address"  
  10.     android:layout_width="fill_parent"  
  11.     android:text="http://192.168.1.111:8089/Test1/servlet/ServletDemo"  
  12. >  
  13. </EditText>  
  14. <Button  
  15.      android:id="@+id/ButtonGo"   
  16.      android:layout_width="wrap_content"   
  17.      android:layout_height="wrap_content"  
  18.      android:text="go!"  
  19.  >  
  20. </Button>  
  21. <TextView    
  22.     android:layout_width="fill_parent"   
  23.     android:layout_height="fill_parent"   
  24.     android:background="#ffffff"  
  25.     android:textColor="#000000"  
  26.     android:id="@+id/pagetext"  
  27.     />  
  28. </LinearLayout>  

 

 

3、添加关键代码

 

  1. import android.app.Activity;  
  2. import android.os.Bundle;  
  3. import android.widget.Button;  
  4. import android.widget.TextView;  
  5. import android.util.Log;  
  6. import android.view.View;  
  7. import java.io.BufferedReader;  
  8. import java.io.BufferedWriter;  
  9. import java.io.InputStreamReader;  
  10. import java.io.OutputStreamWriter;  
  11. import java.net.URL;  
  12. import java.net.URLConnection;  
  13.   
  14.   
  15. public class ClientDemo extends Activity {  
  16.     /** Called when the activity is first created. */  
  17.   
  18.     @Override  
  19.     public void onCreate(Bundle savedInstanceState) {  
  20.         super.onCreate(savedInstanceState);  
  21.         setContentView(R.layout.main);  
  22.           
  23.   
  24.         final TextView tView = (TextView) findViewById(R.id.pagetext);  
  25.           
  26.          
  27.         final Button button = (Button) findViewById(R.id.ButtonGo);  
  28.         button.setOnClickListener(new Button.OnClickListener() {  
  29.             public void onClick(View v) {  
  30.                   
  31.                   
  32.                 String response_string = "";  
  33.                 boolean out = true;  
  34.                 boolean in = true;  
  35.                 try {  
  36.                     System.out.println("ty"+tView.getText().toString());  
  37.                     URL url = new URL("http://192.168.1.111:8089/Test1/servlet/ServletDemo");  
  38.                     URLConnection connection = url.openConnection();  
  39.                       
  40.                     connection.setDoInput(in);  
  41.                     connection.setDoOutput(out);  
  42.                       
  43.                     BufferedWriter writer = null;  
  44.                     //向服务器发送数据  
  45.                     if(out){  
  46.                         writer = new BufferedWriter(new OutputStreamWriter(connection.getOutputStream()));  
  47.                         writer.write("I am clent request!!");  
  48.                         writer.flush();  
  49.                     }  
  50.                     //接受服务器返回的数据  
  51.                     BufferedReader reader = null;  
  52.                     if(in){  
  53.                         reader = new BufferedReader(new InputStreamReader(connection.getInputStream()));  
  54.                         response_string = reader.readLine();  
  55.                         System.out.println("response: "+response_string);  
  56.                         Log.v("test", response_string);  
  57.                         tView.setText(response_string);  
  58.                     }  
  59.                       
  60.                     if(writer != null){  
  61.                         writer.close();  
  62.                     }  
  63.                       
  64.                     if(reader != null){  
  65.                         reader.close();  
  66.                     }  
  67.                 } catch (Exception e) {  
  68.                     // TODO: handle exception  
  69.                     System.out.println(e.getMessage());  
  70.                 }  
  71.             }  
  72.         });          
  73.     }  
  74. }  

 

这样,整个demo就完成了

运行结果如下

1、程序启动 

2、发送请求后


2.Android--模拟登陆用户名密码,使用File或openFileOutput保存文件


一、File:xml布局文件

[html]  view plain copy 在CODE上查看代码片 派生到我的代码片
  1. <RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"  
  2.     xmlns:tools="http://schemas.android.com/tools"  
  3.     android:layout_width="match_parent"  
  4.     android:layout_height="match_parent"  
  5.     android:paddingBottom="@dimen/activity_vertical_margin"  
  6.     android:paddingLeft="@dimen/activity_horizontal_margin"  
  7.     android:paddingRight="@dimen/activity_horizontal_margin"  
  8.     android:paddingTop="@dimen/activity_vertical_margin"  
  9.     tools:context=".MainActivity" >  
  10.   
  11.     <TextView  
  12.         android:id="@+id/textView1"  
  13.         android:layout_width="wrap_content"  
  14.         android:layout_height="wrap_content"  
  15.         android:layout_alignParentLeft="true"  
  16.         android:layout_alignParentTop="true"  
  17.         android:text="请输入用户名" />  
  18.   
  19.     <EditText  
  20.         android:id="@+id/et_username"  
  21.         android:layout_width="wrap_content"  
  22.         android:layout_height="wrap_content"  
  23.         android:layout_alignLeft="@+id/textView1"  
  24.         android:layout_below="@+id/textView1"  
  25.         android:ems="10"/>  
  26.   
  27.     <TextView  
  28.         android:id="@+id/textView2"  
  29.         android:layout_width="wrap_content"  
  30.         android:layout_height="wrap_content"  
  31.         android:layout_alignLeft="@+id/et_username"  
  32.         android:layout_below="@+id/et_username"  
  33.         android:layout_marginTop="20dp"  
  34.         android:text="请输入用户密码" />  
  35.   
  36.     <EditText  
  37.         android:id="@+id/ed_password"  
  38.         android:layout_width="wrap_content"  
  39.         android:layout_height="wrap_content"  
  40.         android:layout_alignLeft="@+id/textView2"  
  41.         android:layout_below="@+id/textView2"  
  42.         android:ems="10"  
  43.         android:inputType="textPassword" >  
  44.   
  45.         <requestFocus />  
  46.     </EditText>  
  47.   
  48.     <CheckBox  
  49.         android:id="@+id/checkbox_remeber"  
  50.         android:layout_width="wrap_content"  
  51.         android:layout_height="wrap_content"  
  52.         android:layout_alignParentLeft="true"  
  53.         android:layout_alignTop="@+id/btn_login"  
  54.         android:text="记住我" />  
  55.   
  56.     <Button  
  57.         android:id="@+id/btn_login"  
  58.         android:layout_width="wrap_content"  
  59.         android:layout_height="wrap_content"  
  60.         android:layout_alignRight="@+id/et_username"  
  61.         android:layout_below="@+id/ed_password"  
  62.         android:layout_marginTop="27dp"  
  63.         android:gravity="left"  
  64.         android:onClick="login"  
  65.         android:text="登陆" />  
  66.   
  67. </RelativeLayout>  
效果图:



二、


File: MainActivity.java

[java]  view plain copy 在CODE上查看代码片 派生到我的代码片
  1. package com.jiangge.login;  
  2.   
  3. import java.util.Map;  
  4.   
  5. import android.app.Activity;  
  6. import android.os.Bundle;  
  7. import android.text.TextUtils;  
  8. import android.util.Log;  
  9. import android.view.View;  
  10. import android.widget.CheckBox;  
  11. import android.widget.EditText;  
  12. import android.widget.Toast;  
  13.   
  14. import com.jiangge.login.service.LoginService;  
  15. import com.jiangge.logindemo.R;  
  16.   
  17. public class MainActivity extends Activity {  
  18.       
  19.     private static final String TAG = "MainActivity";  
  20.       
  21.     private EditText mUsername;  
  22.     private EditText mPassword;  
  23.     private CheckBox mRemember;  
  24.       
  25.     @Override  
  26.     protected void onCreate(Bundle savedInstanceState) {  
  27.         super.onCreate(savedInstanceState);  
  28.         setContentView(R.layout.activity_main);  
  29.         mUsername = (EditText) findViewById(R.id.et_username);  
  30.         mPassword = (EditText) findViewById(R.id.ed_password);  
  31.         mRemember = (CheckBox) findViewById(R.id.checkbox_remeber);  
  32.           
  33.         Map<String, String> map = LoginService.getSavedUserInfo(this);  
  34.         if (map != null) {  
  35.             mUsername.setText(map.get("username"));  
  36.             mPassword.setText(map.get("password"));  
  37.         }  
  38.           
  39.     }  
  40.   
  41.     public void login(View view) {  
  42.         String username = mUsername.getText().toString().trim();  
  43.         String password = mPassword.getText().toString().trim();  
  44.         if (TextUtils.isEmpty(username) || TextUtils.isEmpty(password)) {  
  45.             Toast.makeText(this"用户名和密码不能为空", Toast.LENGTH_LONG).show();  
  46.         }  
  47.           
  48.         if (mRemember.isChecked()) {  
  49.             //保存用户名和密码  
  50.             Log.i(TAG, "保存用户名和密码");  
  51.             boolean result = LoginService.saveUserInfo(this, username, password);  
  52.             if (result) {  
  53.                 Toast.makeText(this"保存用户名和密码成功", Toast.LENGTH_LONG).show();  
  54.             }  
  55.         }  
  56.           
  57.         //登录发送到服务器,服务器验证是否正确。模拟。  
  58.         if ("jiangge".equals(username) && "123".equals(password)) {  
  59.             Toast.makeText(this"登录成功", Toast.LENGTH_LONG).show();  
  60.         }  
  61.     }  
  62. }  



File:   LoginService.java

[java]  view plain copy 在CODE上查看代码片 派生到我的代码片
  1. package com.jiangge.login.service;  
  2.   
  3. import java.io.BufferedReader;  
  4. import java.io.File;  
  5. import java.io.FileInputStream;  
  6. import java.io.FileNotFoundException;  
  7. import java.io.FileOutputStream;  
  8. import java.io.IOException;  
  9. import java.io.InputStreamReader;  
  10. import java.util.HashMap;  
  11. import java.util.Map;  
  12.   
  13. import android.content.Context;  
  14.   
  15. public class LoginService {  
  16.     //存数据  
  17.     public static boolean saveUserInfo(Context context, String username, String password){  
  18.         try {  
  19.             File file = new File(context.getFilesDir(), "info.txt"); //Do not hardcode "/data/"; use Context.getFilesDir().getPath() instead  
  20.             System.out.println("====>>>"+ context.getFilesDir());//  /data/data/com.jiangge.logindemo/files  
  21.             FileOutputStream fos = new FileOutputStream(file);  
  22.             fos.write((username + "##" + password).getBytes());  
  23.             fos.close();  
  24.             return true;  
  25.         } catch (FileNotFoundException e) {  
  26.             e.printStackTrace();  
  27.             return false;  
  28.         } catch (IOException e) {  
  29.             e.printStackTrace();  
  30.             return false;  
  31.         }  
  32.   
  33.     }  
  34.       
  35.     //取数据  
  36.     public static Map<String,String> getSavedUserInfo(Context context){  
  37.         try {  
  38.             File file = new File(context.getFilesDir(), "info.txt");  
  39.             FileInputStream fis = new FileInputStream(file);  
  40.             BufferedReader br = new BufferedReader(new InputStreamReader(fis));  
  41.             String str = br.readLine();  
  42.             br.close();  
  43.               
  44.             String [] infos = str.split("##"); //jiangge##123  
  45.               
  46.             Map<String,String> map = new HashMap<String, String>();  
  47.             map.put("username", infos[0]);  
  48.             map.put("password", infos[1]);  
  49.             return map;  
  50.         } catch (Exception e) {  
  51.             e.printStackTrace();  
  52.             return null;  
  53.         }  
  54.               
  55.           
  56.     }  
  57. }  

注:

保存文件:

[java]  view plain copy 在CODE上查看代码片 派生到我的代码片
  1. File file = new File(context.getFilesDir(), "info.txt"); //Do not hardcode "/data/"; use Context.getFilesDir().getPath() instead  
  2. System.out.println("====>>>"+ context.getFilesDir());//  /data/data/com.jiangge.logindemo/files  
  3. FileOutputStream fos = new FileOutputStream(file);  
  4. fos.write((username + "##" + password).getBytes());  
  5. fos.close();      



也可以将以上的核心代码,使用Activity提供的方法 openFileOutput(String name, int mode)

 
  

[java]  view plain copy 在CODE上查看代码片 派生到我的代码片
  1. FileOutputStream fos = context.openFileOutput("private.txt", Context.MODE_PRIVATE);  
  2. fos.write((username + "##" + password).getBytes());  
  3. fos.close();  


对应的,也有读取





保存到了 /data/data/包名/files/目录下





3.Android之记住登录名和密码 --- 使用Preference


简述:

在登陆的时候,有时候会遇到一个勾选框,用来询问是否保留用户名和密码


知识点:

SharedPreferences

用来访问程序的文件,从里面读出用户名和密码



代码实现:

MyPreference.java

[java]  view plain copy
  1. package com.aimp.help;  
  2.   
  3. import android.content.Context;  
  4. import android.content.SharedPreferences;  
  5. import android.content.SharedPreferences.Editor;  
  6.   
  7. /** 
  8.  *  
  9.  * 记录用户名,密码之类的首选项 
  10.  * 
  11.  */  
  12. public class MyPreference {  
  13.     private static MyPreference preference = null;  
  14.     private SharedPreferences sharedPreference;  
  15.     private String packageName = "";  
  16.       
  17.     private static final String LOGIN_NAME = "loginName"//登录名  
  18.     private static final String PASSWORD = "password";  //密码  
  19.     private static final String IS_SAVE_PWD = "isSavePwd"//是否保留密码  
  20.       
  21.     public static synchronized MyPreference getInstance(Context context){  
  22.         if(preference == null)  
  23.             preference = new MyPreference(context);  
  24.         return preference;  
  25.     }  
  26.       
  27.       
  28.     public MyPreference(Context context){  
  29.         packageName = context.getPackageName() + "_preferences";  
  30.         sharedPreference = context.getSharedPreferences(  
  31.                 packageName, context.MODE_PRIVATE);  
  32.     }  
  33.       
  34.       
  35.     public String getLoginName(){  
  36.         String loginName = sharedPreference.getString(LOGIN_NAME, "");  
  37.         return loginName;  
  38.     }  
  39.       
  40.       
  41.     public void SetLoginName(String loginName){  
  42.         Editor editor = sharedPreference.edit();  
  43.         editor.putString(LOGIN_NAME, loginName);  
  44.         editor.commit();  
  45.     }  
  46.       
  47.       
  48.     public String getPassword(){  
  49.         String password = sharedPreference.getString(PASSWORD, "");  
  50.         return password;  
  51.     }  
  52.       
  53.       
  54.     public void SetPassword(String password){  
  55.         Editor editor = sharedPreference.edit();  
  56.         editor.putString(PASSWORD, password);  
  57.         editor.commit();  
  58.     }  
  59.       
  60.       
  61.     public boolean IsSavePwd(){  
  62.         Boolean isSavePwd = sharedPreference.getBoolean(IS_SAVE_PWD, false);  
  63.         return isSavePwd;  
  64.     }  
  65.       
  66.       
  67.     public void SetIsSavePwd(Boolean isSave){  
  68.         Editor edit = sharedPreference.edit();  
  69.         edit.putBoolean(IS_SAVE_PWD, isSave);  
  70.         edit.commit();  
  71.     }  
  72. }  

LoginActivity.java

[java]  view plain copy
  1. package com.aimp.ui;  
  2.   
  3. import android.app.Activity;  
  4. import android.content.Context;  
  5. import android.content.Intent;  
  6. import android.os.Bundle;  
  7. import android.view.View;  
  8. import android.view.View.OnClickListener;  
  9. import android.widget.Button;  
  10. import android.widget.CheckBox;  
  11. import android.widget.EditText;  
  12.   
  13. import com.aimp.R;  
  14. import com.aimp.help.MyPreference;  
  15.   
  16. public class LoginActivity extends Activity implements OnClickListener {  
  17.     public final static String TAG = "LogingActivity";  
  18.   
  19.     private EditText et_loginName, et_password;  
  20.     private Button bt_login;  
  21.     private CheckBox chk_keep_pwd;  
  22.     private Context mContext;  
  23.   
  24.     @Override  
  25.     protected void onCreate(Bundle savedInstanceState) {  
  26.         super.onCreate(savedInstanceState);  
  27.         mContext = this;  
  28.         setContentViewID(R.layout.activity_login);  
  29.     }  
  30.   
  31.     public void setContentViewID(int viewId) {  
  32.         setContentView(viewId);  
  33.         initView();  
  34.     }  
  35.   
  36.   
  37.     public void initView() {  
  38.         et_loginName = (EditText) findViewById(R.id.username);  
  39.         et_password = (EditText) findViewById(R.id.password);  
  40.         bt_login = (Button) findViewById(R.id.login);  
  41.         bt_login.setOnClickListener(this);  
  42.         chk_keep_pwd = (CheckBox) findViewById(R.id.store_pwd);  
  43.         chk_keep_pwd.setChecked(  
  44.                 MyPreference.getInstance(mContext).IsSavePwd());  
  45.     }  
  46.   
  47.   
  48.     @Override  
  49.     protected void onResume() {  
  50.         super.onResume();  
  51.         mContext = this;  
  52.         chk_keep_pwd.setChecked(MyPreference.getInstance(mContext).IsSavePwd());  
  53.         if (chk_keep_pwd.isChecked()) {  
  54.             et_loginName.setText(MyPreference.getInstance(mContext)  
  55.                     .getLoginName());  
  56.             et_password  
  57.             .setText(MyPreference.getInstance(mContext).getPassword());  
  58.         }  
  59.     }  
  60.   
  61.   
  62.     @Override  
  63.     public void onClick(View v) {  
  64.         switch (v.getId()){  
  65.         //登陆的时候,根据是否保留登陆名保留登录名,密码  
  66.         case R.id.login:  
  67.             if(chk_keep_pwd.isChecked()){  
  68.                 MyPreference.getInstance(mContext)  
  69.                     .SetLoginName(et_loginName.getText().toString().trim());  
  70.                 MyPreference.getInstance(mContext)  
  71.                     .SetPassword(et_password.getText().toString().trim());  
  72.                 MyPreference.getInstance(mContext)  
  73.                     .SetIsSavePwd(chk_keep_pwd.isChecked());  
  74.             }else{  
  75.                 MyPreference.getInstance(mContext)  
  76.                     .SetLoginName("");  
  77.                 MyPreference.getInstance(mContext)  
  78.                     .SetPassword("");  
  79.                 MyPreference.getInstance(mContext)  
  80.                     .SetIsSavePwd(chk_keep_pwd.isChecked());  
  81.             }  
  82.             Intent intent = new Intent(LoginActivity.this, SecondActivity.class);  
  83.             startActivity(intent);  
  84.             break;  
  85.         case R.id.store_pwd:  
  86.             chk_keep_pwd.setChecked(!chk_keep_pwd.isChecked());  
  87.             break;  
  88.         }  
  89.     }  
  90. }  

4.Android自定义框架之网络请求


框架起始篇...意义重大,影响深远....

适用场景,为了便于秒速我们定义网络请求的对象为Action,UI层调起Action发起网络请求,Action处理请求响应的结果,并通知UI层令其得到Action处理后的数据。

1、定义网络请求监听

[java]  view plain copy
  1. public interface HttpListener {  
  2.     /** 
  3.      * 完成网络请求 
  4.      * @param response 
  5.      */  
  6.     public void onComplete(String response);  
  7.     /** 
  8.      * 网络请求失败 
  9.      */  
  10.     public void onError();  
  11. }  

2、定义HTTP工具

主要用到request方法

[java]  view plain copy
  1. /** 
  2.  * HTTP工具类 
  3.  * @author: linxcool.hu 
  4.  */  
  5. public class HttpUtil {  
  6.     private Context context;  
  7.     /**HTTP常量-GET请求*/  
  8.     public static final int HTTP_METHOD_GET=1;  
  9.     /**HTTP常量-POST请求*/  
  10.     public static final int HTTP_METHOD_POST=2;  
  11.     /**HTTP常量-请求限制时间*/  
  12.     public static final int HTTP_REQ_LIMIT_TIME=15*1000;  
  13.     /**HTTP常量-响应限制时间*/  
  14.     public static final int HTTP_RES_LIMIT_TIME=25*1000;  
  15.   
  16.     //返回码  
  17.     public static final int RES_CODE_SUCCESS=200;  
  18.     public static final int RES_CODE_ERROR=1;  
  19.     public static final int RES_CODE_FAIL=2;  
  20.   
  21.     private HttpClient client;  
  22.     private HttpResponse response;  
  23.   
  24.     public HttpUtil(Context context) {  
  25.         this.context=context;  
  26.     }  
  27.   
  28.     public HttpClient createHttpClient(){  
  29.         HttpParams params = new BasicHttpParams();  
  30.         HttpConnectionParams.setConnectionTimeout(params, HTTP_REQ_LIMIT_TIME);  
  31.         HttpConnectionParams.setSoTimeout(params,HTTP_RES_LIMIT_TIME);  
  32.         HttpProtocolParams.setVersion(params, HttpVersion.HTTP_1_1);  
  33.         HttpProtocolParams.setContentCharset(params, HTTP.UTF_8);  
  34.   
  35.         return new DefaultHttpClient(params);  
  36.     }  
  37.   
  38.     public HttpUriRequest createHttpRequest(String url,int method){  
  39.         HttpUriRequest request=null;  
  40.         if(method == HTTP_METHOD_GET){  
  41.             request=new HttpGet(url);  
  42.         }else{  
  43.             request=new HttpPost(url);  
  44.         }  
  45.         //关闭 100-Continue 询问  
  46.         request.getParams().setBooleanParameter(  
  47.                 CoreProtocolPNames.USE_EXPECT_CONTINUE, false);  
  48.         return request;  
  49.     }  
  50.   
  51.     public boolean openUrl(HttpUriRequest request){  
  52.         client=createHttpClient();  
  53.         try {  
  54.             response=client.execute(request);  
  55.             return true;  
  56.         } catch (IOException e) {  
  57.             e.printStackTrace();  
  58.             response=null;  
  59.         }  
  60.         return false;  
  61.     }  
  62.   
  63.     public String getHttpResponse(){  
  64.         String result = null;  
  65.         try {  
  66.             if(response==null)return null;  
  67.             HttpEntity entity = response.getEntity();  
  68.             InputStream inputStream = entity.getContent();  
  69.             ByteArrayOutputStream content = new ByteArrayOutputStream();  
  70.             int readBytes = 0;  
  71.             byte[] sBuffer = new byte[512];  
  72.             while ((readBytes = inputStream.read(sBuffer)) != -1)  
  73.                 content.write(sBuffer, 0, readBytes);  
  74.             result = new String(content.toByteArray());  
  75.             result=URLDecoder.decode(result, "UTF-8");  
  76.             try {  
  77.                 inputStream.close();  
  78.             } catch (IOException e) {  
  79.                 e.printStackTrace();  
  80.             }  
  81.         } catch (IOException e) {  
  82.             e.printStackTrace();  
  83.         }finally{  
  84.             if(client!=null)  
  85.                 client.getConnectionManager().shutdown();  
  86.         }  
  87.         return result;  
  88.     }  
  89.   
  90.     public void request(  
  91.             final String url,final HttpUriRequest request,final HttpListener listerner) {  
  92.         new Thread() {  
  93.             @Override  
  94.             public void run() {  
  95.                 boolean ret = openUrl(request);  
  96.                 if(!ret){  
  97.                     listerner.onError();  
  98.                     return;  
  99.                 }  
  100.                 listerner.onComplete(getHttpResponse());  
  101.             }  
  102.         }.start();  
  103.     }  
  104.       
  105. }  

3、定义网络请求动作Action

每个网络请求动作都继承以下类

[java]  view plain copy
  1. /** 
  2.  * 基础动作类 
  3.  * @author: linxcool.hu 
  4.  */  
  5. public abstract class BaseAction extends Observable implements HttpListener,Runnable{  
  6.     private static final String TAG="BaseAction";  
  7.       
  8.     //动作ID列表 根据实际情况更改  
  9.     public static final int ACTION_ID_INTRO=1;  
  10.     public static final int ACTION_ID_SHARE=2;  
  11.     //响应状态结果  
  12.     public static final int SUCCESS=0;  
  13.     public static final int ERROR=1;  
  14.     public static final int EXCEPTION=2;  
  15.     //上下文对象  
  16.     protected Context context;  
  17.     protected ActionService actionService;  
  18.     //动作信息列表  
  19.     protected int actionId;  
  20.     protected HttpUtil httpUtil;  
  21.     protected int method;  
  22.     protected String content;  
  23.     //响应信息  
  24.     protected String response;  
  25.     protected String resMsg;  
  26.       
  27.     public String getResMsg() {  
  28.         return resMsg;  
  29.     }  
  30.       
  31.     public BaseAction(ActionService actionService,int actionId){  
  32.         this.actionService=actionService;  
  33.         this.context=actionService.getActivity();  
  34.         this.actionId=actionId;  
  35.         httpUtil=new HttpUtil(context);  
  36.         method=HttpUtil.HTTP_METHOD_POST;  
  37.     }  
  38.   
  39.     /** 
  40.      * 执行网络请求动作 
  41.      */  
  42.     public void actionStart(){  
  43.         try {  
  44.             doRequest(  
  45.                     httpUtil.REQUEST_HOST+getURL(),  
  46.                     content);  
  47.         } catch (UnsupportedEncodingException e) {  
  48.             e.printStackTrace();  
  49.         }  
  50.     }  
  51.       
  52.     protected void putBasicData(JSONObject jsonObj) throws JSONException{  
  53.           
  54.     }  
  55.       
  56.     public abstract void putData(Object... datas);  
  57.       
  58.     public void doRequest(String url,String content) throws UnsupportedEncodingException{  
  59.         HttpUriRequest request=httpUtil.createHttpRequest(url, method);  
  60.         if(content != null){  
  61.             HttpPost post=(HttpPost) request;  
  62.             post.setEntity(new StringEntity(content));  
  63.         }  
  64.         httpUtil.request(url, request, this);  
  65.     }  
  66.       
  67.     @Override  
  68.     public void onComplete(String response) {  
  69.         this.response=response;  
  70.         ((Activity)context).runOnUiThread(this);  
  71.     }  
  72.   
  73.     @Override  
  74.     public void onError() {  
  75.         response=null;  
  76.         ((Activity)context).runOnUiThread(this);  
  77.     }  
  78.       
  79.     private String getURL(){  
  80.         switch (actionId) {  
  81.         case ACTION_ID_INTRO:  
  82.             return "login";  
  83.         }  
  84.     }  
  85.   
  86.     @Override  
  87.     public void run() {  
  88.         setChanged();  
  89.         if(response==null){  
  90.             notifyObservers(ERROR);   
  91.             return;  
  92.         }  
  93.         try {  
  94.             JSONObject obj = new JSONObject(response);  
  95.             int code=obj.getInt("code");  
  96.             if(code==HttpUtil.RES_CODE_SUCCESS){  
  97.                 onResSuccess(obj);  
  98.                 notifyObservers(SUCCESS);  
  99.             }else{  
  100.                 resMsg=obj.getString("msg");  
  101.                 notifyObservers(EXCEPTION);  
  102.             }  
  103.         } catch (Exception e) {  
  104.             e.printStackTrace();  
  105.             resMsg="数据解析错误";  
  106.             notifyObservers(ERROR);  
  107.         }  
  108.     }  
  109.       
  110.     /** 
  111.      * 网络请求成功后将执行该方法 
  112.      * @param obj 
  113.      * @throws Exception 
  114.      */  
  115.     public abstract void onResSuccess(JSONObject obj) throws Exception;  
  116.       
  117. }  

4、动作服务类根据ActionId获取对应Action

[java]  view plain copy
  1. /** 
  2.  * 动作服务对象 
  3.  * @author: linxcool.hu 
  4.  */  
  5. public class ActionService {  
  6.     private Activity activity;  
  7.       
  8.     public ActionService(Activity activity){  
  9.         this.activity=activity;  
  10.     }  
  11.   
  12.     /** 
  13.      * 根据动作ID获取动作对象 
  14.      * @param actionId 
  15.      * @return 
  16.      */  
  17.     public BaseAction getAction(int actionId){  
  18.         switch (actionId) {  
  19.         case BaseAction.ACTION_ID_INTRO:  
  20.             return new IntroAction(this);  
  21.         case BaseAction.ACTION_ID_SHARE:  
  22.             return new ShareAction(this);  
  23.         }  
  24.         return null;  
  25.     }  
  26.   
  27.     /** 
  28.      * 获取Context对象 
  29.      * @return 
  30.      */  
  31.     public Activity getActivity() {  
  32.         return activity;  
  33.     }  
  34. }  

5、在UI视图上实现Observer接口,并将该视图添加到对应的Action观察者队列中,在Update方法中处理界面逻辑

[java]  view plain copy
  1. @Override  
  2. public void update(Observable observable, Object data) {  
  3.     int code=(Integer) data;  
  4.     switch (code) {  
  5.     case BaseAction.SUCCESS:  
  6.               
  7.         break;  
  8.     case BaseAction.EXCEPTION:  
  9.               
  10.         break;  
  11.     case BaseAction.ERROR:  
  12.               
  13.         break;  
  14.     }  
  15. }  

代码下载地址: https://pan.quark.cn/s/a4b39357ea24 在计算机视觉技术中,数据集扮演着训练评估模型的核心角色。Labelme作为个广受欢迎的开源工具,能够支持用户以交互方式对图像进行标注,而COCO(Common Objects in Context)则是种被广泛采纳的数据集标准格式,适用于包括物体检测、图像分割在内的多种任务。本文将详细阐述如何将Labelme生成的标注数据转换为COCO数据集的标准格式。 Labelme标注的图像在输出为JSON格式时,会包含以下核心内容: 1. `version`: 指明JSON文件的版本信息。 2. `flags`: 目前未定义或保持为空,预留用于未来的功能扩展。 3. `shapes`: 列表形式存储对象的形状信息,每个形状项包含`label`(对象类别名称),`points`(构成对象边缘的多边形顶点),以及`shape_type`(通常为“polygon”)。 4. `imagePath``imageData`: 提供原始图像的存储路径二进制数据,便于后续图像的还原。 5. `imageHeight``imageWidth`: 明确标注图像的垂直水平尺寸。 COCO数据集的标准格式中定义了三种主要的标注类型: 1. Object instances(目标实例):主要用于执行物体检测任务。 2. Object keypoints(目标上的关键点):适用于人体姿态估计相关应用。 3. Image captions(看图说话):用于生成图像的文本描述。 COCO的JSON结构中包含以下基本组成部分: 1. `images`:记录图像的基本属性,包括`height`(高度)、`...
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值