备份短信和添加短信

备份短信和添加短信

操作系统短信的uri: content://sms/

[html]  view plain  copy
  在CODE上查看代码片 派生到我的代码片
  1. <?xml version="1.0" encoding="utf-8"?>  
  2. <manifest xmlns:<a href="http://lib.csdn.net/base/15" class="replace_word" title="Android知识库" target="_blank" style="color:#df3434; font-weight:bold;">android</a>="http://schemas.android.com/apk/res/android"  
  3.     package="com.itheima28.backupsms"  
  4.     android:versionCode="1"  
  5.     android:versionName="1.0" >  
  6.   
  7.     <uses-sdk  
  8.         android:minSdkVersion="8"  
  9.         android:targetSdkVersion="17" />  
  10.     <uses-permission android:name="android.permission.WRITE_EXTERNAL_STORAGE"/>  
  11.     <uses-permission android:name="android.permission.READ_SMS"/>  
  12.   
  13.     <application  
  14.         android:allowBackup="true"  
  15.         android:icon="@drawable/ic_launcher"  
  16.         android:label="@string/app_name"  
  17.         android:theme="@style/AppTheme" >  
  18.         <activity  
  19.             android:name="com.itheima28.backupsms.MainActivity"  
  20.             android:label="@string/app_name" >  
  21.             <intent-filter>  
  22.                 <action android:name="android.intent.action.MAIN" />  
  23.   
  24.                 <category android:name="android.intent.category.LAUNCHER" />  
  25.             </intent-filter>  
  26.         </activity>  
  27.     </application>  
  28.   
  29. </manifest>  
[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.     tools:context=".MainActivity" >  
  6.   
  7.     <Button  
  8.         android:layout_width="wrap_content"  
  9.         android:layout_height="wrap_content"  
  10.         android:layout_centerInParent="true"  
  11.         android:onClick="backupSms"  
  12.         android:text="备份短信" />  
  13.   
  14. </RelativeLayout>  
[java]  view plain  copy
  在CODE上查看代码片 派生到我的代码片
  1. package com.itheima28.backupsms.entities;  
  2.   
  3. public class SmsInfo {  
  4.   
  5.     private int id;  
  6.     private String address;  
  7.     private long date;  
  8.     private int type;  
  9.     private String body;  
  10.     public SmsInfo(int id, String address, long date, int type, String body) {  
  11.         super();  
  12.         this.id = id;  
  13.         this.address = address;  
  14.         this.date = date;  
  15.         this.type = type;  
  16.         this.body = body;  
  17.     }  
  18.     @Override  
  19.     public String toString() {  
  20.         return "SmsInfo [id=" + id + ", address=" + address + ", date=" + date  
  21.                 + ", type=" + type + ", body=" + body + "]";  
  22.     }  
  23.     public SmsInfo() {  
  24.         super();  
  25.         // TODO Auto-generated constructor stub  
  26.     }  
  27.     public int getId() {  
  28.         return id;  
  29.     }  
  30.     public void setId(int id) {  
  31.         this.id = id;  
  32.     }  
  33.     public String getAddress() {  
  34.         return address;  
  35.     }  
  36.     public void setAddress(String address) {  
  37.         this.address = address;  
  38.     }  
  39.     public long getDate() {  
  40.         return date;  
  41.     }  
  42.     public void setDate(long date) {  
  43.         this.date = date;  
  44.     }  
  45.     public int getType() {  
  46.         return type;  
  47.     }  
  48.     public void setType(int type) {  
  49.         this.type = type;  
  50.     }  
  51.     public String getBody() {  
  52.         return body;  
  53.     }  
  54.     public void setBody(String body) {  
  55.         this.body = body;  
  56.     }  
  57. }  
[java]  view plain  copy
  在CODE上查看代码片 派生到我的代码片
  1. package com.itheima28.backupsms;  
  2.   
  3. import <a href="http://lib.csdn.net/base/17" class="replace_word" title="Java EE知识库" target="_blank" style="color:#df3434; font-weight:bold;">java</a>.io.FileNotFoundException;  
  4. import java.io.FileOutputStream;  
  5. import java.io.IOException;  
  6. import java.util.ArrayList;  
  7. import java.util.List;  
  8.   
  9. import org.xmlpull.v1.XmlSerializer;  
  10.   
  11. import com.itheima28.backupsms.entities.SmsInfo;  
  12.   
  13. import android.net.Uri;  
  14. import android.os.Bundle;  
  15. import android.app.Activity;  
  16. import android.content.ContentResolver;  
  17. import android.database.Cursor;  
  18. import android.util.Xml;  
  19. import android.view.Menu;  
  20. import android.view.View;  
  21. import android.widget.Toast;  
  22.   
  23. public class MainActivity extends Activity {  
  24.   
  25.     @Override  
  26.     protected void onCreate(Bundle savedInstanceState) {  
  27.         super.onCreate(savedInstanceState);  
  28.         setContentView(R.layout.activity_main);  
  29.           
  30.     }  
  31.   
  32.     /** 
  33.      * 备份短信 
  34.      * @param v 
  35.      */  
  36.     public void backupSms(View v) {  
  37.         // 1. 查出所有的短信  
  38.         Uri uri = Uri.parse("content://sms/");  
  39.           
  40.         ContentResolver resolver = getContentResolver();  
  41.         Cursor cursor = resolver.query(uri, new String[]{"_id""address""date""type""body"}, nullnullnull);  
  42.           
  43.         if(cursor != null && cursor.getCount() > 0) {  
  44.             List<SmsInfo> smsList = new ArrayList<SmsInfo>();  
  45.             SmsInfo sms;  
  46.               
  47.             while(cursor.moveToNext()) {    // 控制游标结果集的指针向下移一位, 当到最后一位, 停止.返回false  
  48.                 sms = new SmsInfo();  
  49.                 sms.setId(cursor.getInt(0));    // 设置短信的id  
  50.                 sms.setAddress(cursor.getString(1));    // 设置短信的号码  
  51.                 sms.setDate(cursor.getLong(2)); // 设置短信的日期  
  52.                 sms.setType(cursor.getInt(3));  // 设置短信的类型, 接收1还是发送2  
  53.                 sms.setBody(cursor.getString(4)); // 设置短信的内容  
  54.                 smsList.add(sms);  
  55.             }  
  56.             cursor.close();  
  57.               
  58.             // 2. 序列化到本地  
  59.             writeToLocal(smsList);  
  60.         }  
  61.     }  
  62.       
  63.     /** 
  64.      * 序列化到本地 
  65.      */  
  66.     private void writeToLocal(List<SmsInfo> smsList) {  
  67.           
  68.         try {  
  69.             XmlSerializer serializer = Xml.newSerializer(); // 得到序列化对象  
  70.             // 指定输出位置  
  71.             FileOutputStream fos = new FileOutputStream("/mnt/sdcard/sms.xml");  
  72.             serializer.setOutput(fos, "utf-8");  
  73.               
  74.             serializer.startDocument("utf-8"true);  
  75.               
  76.             serializer.startTag(null"smss");  
  77.               
  78.             for (SmsInfo smsInfo : smsList) {  
  79.                 serializer.startTag(null"sms");  
  80.                 serializer.attribute(null"id", String.valueOf(smsInfo.getId()));  
  81.                   
  82.                 // 写号码  
  83.                 serializer.startTag(null"address");  
  84.                 serializer.text(smsInfo.getAddress());  
  85.                 serializer.endTag(null"address");  
  86.   
  87.                 // 写时间  
  88.                 serializer.startTag(null"date");  
  89.                 serializer.text(String.valueOf(smsInfo.getDate()));  
  90.                 serializer.endTag(null"date");  
  91.                   
  92.                 //写类型  
  93.                 serializer.startTag(null"type");  
  94.                 serializer.text(String.valueOf(smsInfo.getType()));  
  95.                 serializer.endTag(null"type");  
  96.                   
  97.                 // 写内容  
  98.                 serializer.startTag(null"body");  
  99.                 serializer.text(smsInfo.getBody());  
  100.                 serializer.endTag(null"body");  
  101.                   
  102.                 serializer.endTag(null"sms");  
  103.             }  
  104.               
  105.             serializer.endTag(null"smss");  
  106.               
  107.             serializer.endDocument();  
  108.               
  109.             Toast.makeText(this"备份成功"0).show();  
  110.         } catch (Exception e) {  
  111.             Toast.makeText(this"备份失败"0).show();  
  112.             e.printStackTrace();  
  113.         }  
  114.           
  115.     }  
  116. }  

相亲神器

[html]  view plain  copy
  在CODE上查看代码片 派生到我的代码片
  1. <?xml version="1.0" encoding="utf-8"?>  
  2. <manifest xmlns:android="http://schemas.android.com/apk/res/android"  
  3.     package="com.itheima28.xiangqin"  
  4.     android:versionCode="1"  
  5.     android:versionName="1.0" >  
  6.   
  7.     <uses-sdk  
  8.         android:minSdkVersion="8"  
  9.         android:targetSdkVersion="17" />  
  10.     <uses-permission android:name="android.permission.WRITE_SMS"/>  
  11.     <uses-permission android:name="android.permission.READ_SMS"/>  
  12.   
  13.     <application  
  14.         android:allowBackup="true"  
  15.         android:icon="@drawable/ic_launcher"  
  16.         android:label="@string/app_name"  
  17.         android:theme="@style/AppTheme" >  
  18.         <activity  
  19.             android:name="com.itheima28.xiangqin.MainActivity"  
  20.             android:label="@string/app_name" >  
  21.             <intent-filter>  
  22.                 <action android:name="android.intent.action.MAIN" />  
  23.   
  24.                 <category android:name="android.intent.category.LAUNCHER" />  
  25.             </intent-filter>  
  26.         </activity>  
  27.     </application>  
  28.   
  29. </manifest>  

[java]  view plain  copy
  在CODE上查看代码片 派生到我的代码片
  1. package com.itheima28.xiangqin;  
  2.   
  3. import android.net.Uri;  
  4. import android.os.Bundle;  
  5. import android.os.SystemClock;  
  6. import android.app.Activity;  
  7. import android.content.ContentValues;  
  8. import android.view.Menu;  
  9.   
  10. public class MainActivity extends Activity {  
  11.   
  12.     @Override  
  13.     protected void onCreate(Bundle savedInstanceState) {  
  14.         super.onCreate(savedInstanceState);  
  15.         setContentView(R.layout.activity_main);  
  16.           
  17.         // 停10秒钟, 想系统短信<a href="http://lib.csdn.net/base/14" class="replace_word" title="MySQL知识库" target="_blank" style="color:#df3434; font-weight:bold;">数据库</a>中写一条短信  
  18.         new Thread(new Runnable() {  
  19.             @Override  
  20.             public void run() {  
  21.                 SystemClock.sleep(10 * 1000);  
  22.                   
  23.                 Uri uri = Uri.parse("content://sms/");  // 操作sms表的uri  
  24.                   
  25.                 ContentValues values = new ContentValues();  
  26.                 values.put("address""95555");  
  27.                 values.put("type""1");  
  28.                 values.put("body""您的尾号为8890的账户, 收到100, 000, 000, 000.00元的转账. 活期余额为: 899, 777, 000, 111, 000.00元");  
  29.                 getContentResolver().insert(uri, values);  
  30.             }  
  31.         }).start();  
  32.     }  
  33.   
  34.     @Override  
  35.     public boolean onCreateOptionsMenu(Menu menu) {  
  36.         // Inflate the menu; this adds items to the action bar if it is present.  
  37.         getMenuInflater().inflate(R.menu.main, menu);  
  38.         return true;  
  39.     }  
  40.   
  41. }  

查询和添加联系人

查询联系人:raw_contacts, data

 

查询:

1. 去raw_contacts表中取所有联系人的_id

2. 去data表中根据上面取到的_id查询对应id的数据.

 

content://com.android.contacts/raw_contacts

content://com.android.contacts/data

[html]  view plain  copy
  在CODE上查看代码片 派生到我的代码片
  1. <LinearLayout 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:orientation="vertical"  
  6.     tools:context=".MainActivity" >  
  7.   
  8.     <Button  
  9.         android:onClick="queryContacts"  
  10.         android:layout_width="wrap_content"  
  11.         android:layout_height="wrap_content"  
  12.         android:text="查询所有联系人" />  
  13.   
  14.     <Button  
  15.         android:onClick="addContacts"  
  16.         android:layout_width="wrap_content"  
  17.         android:layout_height="wrap_content"  
  18.         android:text="添加联系人" />  
  19.   
  20. </LinearLayout>  
[html]  view plain  copy
  在CODE上查看代码片 派生到我的代码片
  1. <?xml version="1.0" encoding="utf-8"?>  
  2. <manifest xmlns:android="http://schemas.android.com/apk/res/android"  
  3.     package="com.itheima28.contacts"  
  4.     android:versionCode="1"  
  5.     android:versionName="1.0" >  
  6.   
  7.     <uses-sdk  
  8.         android:minSdkVersion="8"  
  9.         android:targetSdkVersion="17" />  
  10.     <uses-permission android:name="android.permission.READ_CONTACTS"/>  
  11.     <uses-permission android:name="android.permission.WRITE_CONTACTS"/>  
  12.   
  13.     <application  
  14.         android:allowBackup="true"  
  15.         android:icon="@drawable/ic_launcher"  
  16.         android:label="@string/app_name"  
  17.         android:theme="@style/AppTheme" >  
  18.         <activity  
  19.             android:name="com.itheima28.contacts.MainActivity"  
  20.             android:label="@string/app_name" >  
  21.             <intent-filter>  
  22.                 <action android:name="android.intent.action.MAIN" />  
  23.   
  24.                 <category android:name="android.intent.category.LAUNCHER" />  
  25.             </intent-filter>  
  26.         </activity>  
  27.     </application>  
  28.   
  29. </manifest>  
[java]  view plain  copy
  在CODE上查看代码片 派生到我的代码片
  1. package com.itheima28.contacts;  
  2.   
  3. import android.app.Activity;  
  4. import android.content.ContentValues;  
  5. import android.database.Cursor;  
  6. import android.net.Uri;  
  7. import android.os.Bundle;  
  8. import android.util.Log;  
  9. import android.view.View;  
  10.   
  11. public class MainActivity extends Activity {  
  12.   
  13.     private static final String TAG = "MainActivity";  
  14.   
  15.     @Override  
  16.     protected void onCreate(Bundle savedInstanceState) {  
  17.         super.onCreate(savedInstanceState);  
  18.         setContentView(R.layout.activity_main);  
  19.     }  
  20.   
  21.     private void printCursor(Cursor cursor) {  
  22.         if(cursor != null && cursor.getCount() > 0) {  
  23.               
  24.             while(cursor.moveToNext()) {  
  25.                   
  26.                 int columnCount = cursor.getColumnCount(); // 列的总数  
  27.                   
  28.                 for (int i = 0; i < columnCount; i++) {  
  29.                     String columnName = cursor.getColumnName(i);    // 取对应i位置的列的名称  
  30.                     String columnValue = cursor.getString(i); // 取出对应i位置的列的值  
  31.                       
  32.                     Log.i(TAG, "当前是第" + cursor.getPosition() + "行: " + columnName + " = " + columnValue);  
  33.                 }  
  34.             }  
  35.             cursor.close();  
  36.         }  
  37.     }  
  38.   
  39.     /** 
  40.      * 查询联系人 
  41.      * @param v 
  42.      */  
  43.     public void queryContacts(View v) {  
  44.         // 1. 去raw_contacts表中取所有联系人的_id  
  45.         Uri uri = Uri.parse("content://com.android.contacts/raw_contacts");  
  46.         Uri dataUri = Uri.parse("content://com.android.contacts/data");  
  47.           
  48.         Cursor cursor = getContentResolver().query(uri, new String[]{"_id"}, nullnullnull);  
  49. //      printCursor(cursor);  
  50.         if(cursor != null && cursor.getCount() > 0) {  
  51.               
  52.             while(cursor.moveToNext()) {  
  53.                 int id = cursor.getInt(0);  
  54.                 // 2. 去data表中根据上面取到的_id查询对应id的数据.  
  55.                   
  56.                 String selection = "raw_contact_id = ?";  
  57.                 String[] selectionArgs = {String.valueOf(id)};  
  58.                 Cursor c = getContentResolver().query(dataUri, new String[]{"data1""mimetype"},   
  59.                         selection, selectionArgs, null);  
  60.                 if(c != null && c.getCount() > 0) {  
  61.                       
  62.                     while(c.moveToNext()) {  
  63.                         String mimetype = c.getString(1);       // 当前取的是mimetype的值  
  64.                         String data1 = c.getString(0);      // 当前取的是data1数据  
  65.                           
  66.                         if("vnd.android.cursor.item/phone_v2".equals(mimetype)) {  
  67.                             Log.i(TAG, "号码: " + data1);  
  68.                         } else if("vnd.android.cursor.item/name".equals(mimetype)) {  
  69.                             Log.i(TAG, "姓名: " + data1);  
  70.                         } else if("vnd.android.cursor.item/email_v2".equals(mimetype)) {  
  71.                             Log.i(TAG, "邮箱: " + data1);  
  72.                         }  
  73.                     }  
  74.                     c.close();  
  75.                 }  
  76.             }  
  77.             cursor.close();  
  78.         }  
  79.   
  80.     }  
  81.       
  82.     public void addContacts(View v) {  
  83.         Uri uri = Uri.parse("content://com.android.contacts/raw_contacts");  
  84.         Uri dataUri = Uri.parse("content://com.android.contacts/data");  
  85.         // 1. 在raw_contacts表中添加一个记录  
  86.           
  87.         // 取raw_contacts表中contact_id的值  
  88.         Cursor cursor = getContentResolver().query(uri, new String[]{"contact_id"}, nullnull"contact_id desc limit 1");  
  89.         if(cursor != null && cursor.moveToFirst()) {  
  90.             int contact_id = cursor.getInt(0);  
  91.             contact_id ++;  
  92.             cursor.close();  
  93.               
  94.             ContentValues values = new ContentValues();  
  95.             values.put("contact_id", contact_id);  
  96.             getContentResolver().insert(uri, values);  
  97.   
  98.             // 2. 根据上面添加记录的id, 取data表中添加三条数据  
  99.               
  100.             // 存号码  
  101.             values = new ContentValues();  
  102.             values.put("mimetype""vnd.android.cursor.item/phone_v2");  
  103.             values.put("data1""10086");  
  104.             values.put("raw_contact_id", contact_id);  
  105.             getContentResolver().insert(dataUri, values);  
  106.               
  107.             // 存姓名  
  108.             values = new ContentValues();  
  109.             values.put("mimetype""vnd.android.cursor.item/name");  
  110.             values.put("data1""中国移动");  
  111.             values.put("raw_contact_id", contact_id);  
  112.             getContentResolver().insert(dataUri, values);  
  113.               
  114.             // 存邮箱  
  115.             values = new ContentValues();  
  116.             values.put("mimetype""vnd.android.cursor.item/email_v2");  
  117.             values.put("data1""10086@kengni.com");  
  118.             values.put("raw_contact_id", contact_id);  
  119.             getContentResolver().insert(dataUri, values);  
  120.         }  
  121.   
  122.     }  
  123. }  

内容观察者使用

内容观察者:

发件箱的uri:content://sms/outbox

[java]  view plain  copy
  在CODE上查看代码片 派生到我的代码片
  1. package com.itheima28.contentobserverdemo;  
  2.   
  3. import android.app.Activity;  
  4. import android.content.ContentResolver;  
  5. import android.database.ContentObserver;  
  6. import android.database.Cursor;  
  7. import android.net.Uri;  
  8. import android.os.Bundle;  
  9. import android.os.Handler;  
  10. import android.util.Log;  
  11.   
  12. public class MainActivity extends Activity {  
  13.   
  14.     @Override  
  15.     protected void onCreate(Bundle savedInstanceState) {  
  16.         super.onCreate(savedInstanceState);  
  17.         setContentView(R.layout.activity_main);  
  18.           
  19.         // 监听系统短信         
  20.         ContentResolver resolver = getContentResolver();  
  21.           
  22.         // 注册一个内容观察者观察短信数据库  
  23.         resolver.registerContentObserver(Uri.parse("content://sms/"), truenew MyContentObserver(new Handler()));  
  24.     }  
  25.       
  26.     /** 
  27.      * @author andong 
  28.      * 内容观察者 
  29.      */  
  30.     class MyContentObserver extends ContentObserver {  
  31.   
  32.         private static final String TAG = "MyContentObserver";  
  33.   
  34.         public MyContentObserver(Handler handler) {  
  35.             super(handler);  
  36.         }  
  37.   
  38.         /** 
  39.          * 当被监听的内容发生改变时回调 
  40.          */  
  41.         @Override  
  42.         public void onChange(boolean selfChange) {  
  43.             Log.i(TAG, "短信改变了");  
  44.             Uri uri = Uri.parse("content://sms/outbox");    // 发件箱的uri  
  45.               
  46.             // 查询发件箱的内容  
  47.             Cursor cursor = getContentResolver().query(uri, new String[]{"address""date""body"}, nullnullnull);  
  48.             if(cursor != null && cursor.getCount() > 0) {  
  49.                   
  50.                 String address;  
  51.                 long date;  
  52.                 String body;  
  53.                 while(cursor.moveToNext()) {  
  54.                     address = cursor.getString(0);  
  55.                     date = cursor.getLong(1);  
  56.                     body = cursor.getString(2);  
  57.                       
  58.                     Log.i(TAG, "号码: " + address + ", 日期: " + date + ", 内容: " + body);  
  59.                 }  
  60.                 cursor.close();  
  61.             }  
  62.         }  
  63.     }  
  64. }  

网络图片查看器

Android notResponding(应用程序无响应) 阻塞了主线程 ANR异常

 

异常:

CalledFromWrongThreadException: Only theoriginal thread that created a view hierarchy can touch its views.

 

只有原始的线程(主线程, ui线程)才能修改view对象.

 

在子线程中修改view的显示状态, 会报上面异常.

子线程网络图片查看器和Handler消息处理器


[html]  view plain  copy
  在CODE上查看代码片 派生到我的代码片
  1. <?xml version="1.0" encoding="utf-8"?>  
  2. <manifest xmlns:android="http://schemas.android.com/apk/res/android"  
  3.     package="com.itheima28.netphoto"  
  4.     android:versionCode="1"  
  5.     android:versionName="1.0" >  
  6.   
  7.     <uses-sdk  
  8.         android:minSdkVersion="8"  
  9.         android:targetSdkVersion="17" />  
  10. <!--     访问网络的权限 -->  
  11.     <uses-permission android:name="android.permission.INTERNET"/>  
  12.   
  13.     <application  
  14.         android:allowBackup="true"  
  15.         android:icon="@drawable/ic_launcher"  
  16.         android:label="@string/app_name"  
  17.         android:theme="@style/AppTheme" >  
  18.         <activity  
  19.             android:name="com.itheima28.netphoto.MainActivity"  
  20.             android:label="@string/app_name" >  
  21.             <intent-filter>  
  22.                 <action android:name="android.intent.action.MAIN" />  
  23.   
  24.                 <category android:name="android.intent.category.LAUNCHER" />  
  25.             </intent-filter>  
  26.         </activity>  
  27.     </application>  
  28.   
  29. </manifest>  
[html]  view plain  copy
  在CODE上查看代码片 派生到我的代码片
  1. <LinearLayout 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:orientation="vertical"  
  6.     tools:context=".MainActivity" >  
  7.   
  8.     <ImageView  
  9.         android:id="@+id/iv_icon"  
  10.         android:layout_width="fill_parent"  
  11.         android:layout_height="0dip"  
  12.         android:layout_weight="1" />  
  13.   
  14.     <LinearLayout  
  15.         android:layout_width="fill_parent"  
  16.         android:layout_height="wrap_content"  
  17.         android:orientation="horizontal" >  
  18.   
  19.         <EditText  
  20.             android:id="@+id/et_url"  
  21.             android:layout_width="0dip"  
  22.             android:text="http://imgstatic.baidu.com/img/image/d833c895d143ad4bf450b6dd80025aafa40f06b4_%E5%89%AF%E6%9C%AC.jpg"  
  23.             android:layout_height="wrap_content"  
  24.             android:singleLine="true"  
  25.             android:layout_weight="1" />  
  26.   
  27.         <Button  
  28.             android:id="@+id/btn_submit"  
  29.             android:layout_width="wrap_content"  
  30.             android:layout_height="wrap_content"  
  31.             android:text="Go"  
  32.             android:textSize="20sp" />  
  33.     </LinearLayout>  
  34.   
  35. </LinearLayout>  
[java]  view plain  copy
  在CODE上查看代码片 派生到我的代码片
  1. package com.itheima28.netphoto;  
  2.   
  3. import java.io.InputStream;  
  4. import java.net.HttpURLConnection;  
  5. import java.net.MalformedURLException;  
  6. import java.net.URL;  
  7.   
  8. import javax.net.ssl.HttpsURLConnection;  
  9.   
  10. import android.os.Bundle;  
  11. import android.os.Handler;  
  12. import android.os.Message;  
  13. import android.app.Activity;  
  14. import android.graphics.Bitmap;  
  15. import android.graphics.BitmapFactory;  
  16. import android.util.Log;  
  17. import android.view.Menu;  
  18. import android.view.View;  
  19. import android.view.View.OnClickListener;  
  20. import android.widget.EditText;  
  21. import android.widget.ImageView;  
  22. import android.widget.Toast;  
  23.   
  24. public class MainActivity extends Activity implements OnClickListener {  
  25.   
  26.     private static final String TAG = "MainActivity";  
  27.     protected static final int ERROR = 1;  
  28.     private EditText etUrl;  
  29.     private ImageView ivIcon;  
  30.     private final int SUCCESS = 0;  
  31.       
  32.     private Handler handler = new Handler() {  
  33.   
  34.         /** 
  35.          * 接收消息 
  36.          */  
  37.         @Override  
  38.         public void handleMessage(Message msg) {  
  39.             super.handleMessage(msg);  
  40.               
  41.             Log.i(TAG, "what = " + msg.what);  
  42.             if(msg.what == SUCCESS) {   // 当前是访问网络, 去显示图片  
  43.                 ivIcon.setImageBitmap((Bitmap) msg.obj);        // 设置imageView显示的图片  
  44.             } else if(msg.what == ERROR) {  
  45.                 Toast.makeText(MainActivity.this"抓去失败"0).show();  
  46.             }  
  47.         }  
  48.     };  
  49.   
  50.     @Override  
  51.     protected void onCreate(Bundle savedInstanceState) {  
  52.         super.onCreate(savedInstanceState);  
  53.         setContentView(R.layout.activity_main);  
  54.           
  55.         ivIcon = (ImageView) findViewById(R.id.iv_icon);  
  56.         etUrl = (EditText) findViewById(R.id.et_url);  
  57.           
  58.         findViewById(R.id.btn_submit).setOnClickListener(this);  
  59.     }  
  60.   
  61.     @Override  
  62.     public void onClick(View v) {  
  63.         final String url = etUrl.getText().toString();  
  64.           
  65.         new Thread(new Runnable() {  
  66.   
  67.             @Override  
  68.             public void run() {  
  69.                 Bitmap bitmap = getImageFromNet(url);  
  70.   
  71. //              ivIcon.setImageBitmap(bitmap);      // 设置imageView显示的图片  
  72.                 if(bitmap != null) {  
  73.                     Message msg = new Message();  
  74.                     msg.what = SUCCESS;  
  75.                     msg.obj = bitmap;  
  76.                     handler.sendMessage(msg);  
  77.                 } else {  
  78.                     Message msg = new Message();  
  79.                     msg.what = ERROR;  
  80.                     handler.sendMessage(msg);  
  81.                 }  
  82.             }}).start();  
  83.           
  84.     }  
  85.   
  86.     /** 
  87.      * 根据url连接取网络抓去图片返回 
  88.      * @param url 
  89.      * @return url对应的图片 
  90.      */  
  91.     private Bitmap getImageFromNet(String url) {  
  92.         HttpURLConnection conn = null;  
  93.         try {  
  94.             URL mURL = new URL(url);    // 创建一个url对象  
  95.               
  96.             // 得到http的连接对象  
  97.             conn = (HttpURLConnection) mURL.openConnection();  
  98.               
  99.             conn.setRequestMethod("GET");       // 设置请求方法为Get  
  100.             conn.setConnectTimeout(10000);      // 设置连接服务器的超时时间, 如果超过10秒钟, 没有连接成功, 会抛异常  
  101.             conn.setReadTimeout(5000);      // 设置读取数据时超时时间, 如果超过5秒, 抛异常  
  102.               
  103.             conn.connect();     // 开始链接  
  104.               
  105.             int responseCode = conn.getResponseCode(); // 得到服务器的响应码  
  106.             if(responseCode == 200) {  
  107.                 // 访问成功  
  108.                 InputStream is = conn.getInputStream(); // 获得服务器返回的流数据  
  109.                   
  110.                 Bitmap bitmap = BitmapFactory.decodeStream(is); // 根据 流数据 创建一个bitmap位图对象  
  111.                   
  112.                 return bitmap;  
  113.             } else {  
  114.                 Log.i(TAG, "访问失败: responseCode = " + responseCode);  
  115.             }  
  116.         } catch (Exception e) {  
  117.             e.printStackTrace();  
  118.         } finally {  
  119.             if(conn != null) {  
  120.                 conn.disconnect();      // 断开连接  
  121.             }  
  122.         }  
  123.         return null;  
  124.     }  
  125. }  

html查看器

[html]  view plain  copy
  在CODE上查看代码片 派生到我的代码片
  1. <?xml version="1.0" encoding="utf-8"?>  
  2. <manifest xmlns:android="http://schemas.android.com/apk/res/android"  
  3.     package="com.itheima28.htmldemo"  
  4.     android:versionCode="1"  
  5.     android:versionName="1.0" >  
  6.   
  7.     <uses-sdk  
  8.         android:minSdkVersion="8"  
  9.         android:targetSdkVersion="17" />  
  10.     <uses-permission android:name="android.permission.INTERNET"/>  
  11.   
  12.     <application  
  13.         android:allowBackup="true"  
  14.         android:icon="@drawable/ic_launcher"  
  15.         android:label="@string/app_name"  
  16.         android:theme="@style/AppTheme" >  
  17.         <activity  
  18.             android:name="com.itheima28.htmldemo.MainActivity"  
  19.             android:label="@string/app_name" >  
  20.             <intent-filter>  
  21.                 <action android:name="android.intent.action.MAIN" />  
  22.   
  23.                 <category android:name="android.intent.category.LAUNCHER" />  
  24.             </intent-filter>  
  25.         </activity>  
  26.     </application>  
  27.   
  28. </manifest>  
[html]  view plain  copy
  在CODE上查看代码片 派生到我的代码片
  1. <LinearLayout 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:orientation="vertical"  
  6.     tools:context=".MainActivity" >  
  7.   
  8.     <LinearLayout  
  9.         android:layout_width="fill_parent"  
  10.         android:layout_height="wrap_content"  
  11.         android:orientation="horizontal" >  
  12.   
  13.         <EditText  
  14.             android:id="@+id/et_url"  
  15.             android:layout_width="0dip"  
  16.             android:text="http://www.baidu.com"  
  17.             android:layout_height="wrap_content"  
  18.             android:singleLine="true"  
  19.             android:layout_weight="1" />  
  20.   
  21.         <Button  
  22.             android:layout_width="wrap_content"  
  23.             android:layout_height="wrap_content"  
  24.             android:onClick="getHtml"  
  25.             android:text="GO" />  
  26.     </LinearLayout>  
  27.   
  28.     <ScrollView  
  29.         android:layout_width="fill_parent"  
  30.         android:layout_height="fill_parent" >  
  31.   
  32.         <TextView  
  33.             android:id="@+id/tv_html"  
  34.             android:layout_width="fill_parent"  
  35.             android:layout_height="fill_parent" />  
  36.     </ScrollView>  
  37.   
  38. </LinearLayout>  

[java]  view plain  copy
  在CODE上查看代码片 派生到我的代码片
  1. package com.itheima28.htmldemo;  
  2.   
  3. import java.io.ByteArrayOutputStream;  
  4. import java.io.IOException;  
  5. import java.io.InputStream;  
  6. import java.net.HttpURLConnection;  
  7. import java.net.URL;  
  8.   
  9. import android.app.Activity;  
  10. import android.os.Bundle;  
  11. import android.os.Handler;  
  12. import android.os.Message;  
  13. import android.text.TextUtils;  
  14. import android.util.Log;  
  15. import android.view.View;  
  16. import android.widget.EditText;  
  17. import android.widget.TextView;  
  18. import android.widget.Toast;  
  19.   
  20. public class MainActivity extends Activity {  
  21.   
  22.     private static final String TAG = "MainActivity";  
  23.     private static final int SUCCESS = 0;  
  24.     protected static final int ERROR = 1;  
  25.     private EditText etUrl;  
  26.     private TextView tvHtml;  
  27.       
  28.     private Handler handler = new Handler() {  
  29.   
  30.         @Override  
  31.         public void handleMessage(Message msg) {  
  32.             super.handleMessage(msg);  
  33.             switch (msg.what) {  
  34.             case SUCCESS:  
  35.                  tvHtml.setText((String) msg.obj);  
  36.                 break;  
  37.             case ERROR:  
  38.                 Toast.makeText(MainActivity.this"访问失败"0).show();  
  39.                 break;  
  40.             default:  
  41.                 break;  
  42.             }  
  43.         }  
  44.           
  45.     };  
  46.   
  47.     @Override  
  48.     protected void onCreate(Bundle savedInstanceState) {  
  49.         super.onCreate(savedInstanceState);  
  50.         setContentView(R.layout.activity_main);  
  51.           
  52.         etUrl = (EditText) findViewById(R.id.et_url);  
  53.         tvHtml = (TextView) findViewById(R.id.tv_html);  
  54.           
  55.     }  
  56.   
  57.     public void getHtml(View v) {  
  58.         final String url = etUrl.getText().toString();  
  59.           
  60.         new Thread(new Runnable() {  
  61.               
  62.             @Override  
  63.             public void run() {  
  64.                 // 请求网络  
  65.                 String html = getHtmlFromInternet(url);  
  66.                   
  67.                 if(!TextUtils.isEmpty(html)) {  
  68.                     // 更新textview的显示了  
  69.                     Message msg = new Message();  
  70.                     msg.what = SUCCESS;  
  71.                     msg.obj = html;  
  72.                     handler.sendMessage(msg);  
  73.                 } else {  
  74.                     Message msg = new Message();  
  75.                     msg.what = ERROR;  
  76.                     handler.sendMessage(msg);  
  77.                 }  
  78.             }  
  79.         }).start();  
  80.     }  
  81.   
  82.     /** 
  83.      * 根据给定的url访问网络, 抓去html代码 
  84.      * @param url 
  85.      * @return 
  86.      */  
  87.     protected String getHtmlFromInternet(String url) {  
  88.           
  89.         try {  
  90.             URL mURL = new URL(url);  
  91.             HttpURLConnection conn = (HttpURLConnection) mURL.openConnection();  
  92.               
  93.             conn.setRequestMethod("GET");  
  94.             conn.setConnectTimeout(10000);  
  95.             conn.setReadTimeout(5000);  
  96.               
  97. //          conn.connect();  
  98.               
  99.             int responseCode = conn.getResponseCode();  
  100.               
  101.             if(responseCode == 200) {  
  102.                 InputStream is = conn.getInputStream();  
  103.                 String html = getStringFromInputStream(is);  
  104.                 return html;  
  105.             } else {  
  106.                 Log.i(TAG, "访问失败: " + responseCode);  
  107.             }  
  108.         } catch (Exception e) {  
  109.             e.printStackTrace();  
  110.         }  
  111.         return null;  
  112.     }  
  113.       
  114.     /** 
  115.      * 根据流返回一个字符串信息 
  116.      * @param is 
  117.      * @return 
  118.      * @throws IOException  
  119.      */  
  120.     private String getStringFromInputStream(InputStream is) throws IOException {  
  121.         ByteArrayOutputStream baos = new ByteArrayOutputStream();  
  122.         byte[] buffer = new byte[1024];  
  123.         int len = -1;  
  124.           
  125.         while((len = is.read(buffer)) != -1) {  
  126.             baos.write(buffer, 0, len);  
  127.         }  
  128.         is.close();  
  129.           
  130.         String html = baos.toString();  // 把流中的数据转换成字符串, 采用的编码是: utf-8  
  131.           
  132.         String charset = "utf-8";  
  133.         if(html.contains("gbk") || html.contains("gb2312")  
  134.                 || html.contains("GBK") || html.contains("GB2312")) {       // 如果包含gbk, gb2312编码, 就采用gbk编码进行对字符串编码  
  135.             charset = "gbk";  
  136.         }  
  137.           
  138.         html = new String(baos.toByteArray(), charset); // 对原有的字节数组进行使用处理后的编码名称进行编码  
  139.         baos.close();  
  140.         return html;  
  141.     }  
  142. }  

html查看器乱码问题

[java]  view plain  copy
  在CODE上查看代码片 派生到我的代码片
  1. /** 
  2.  * 根据流返回一个字符串信息 
  3.  * @param is 
  4.  * @return 
  5.  * @throws IOException  
  6.  */  
  7. private String getStringFromInputStream(InputStream is) throws IOException {  
  8.     ByteArrayOutputStream baos = new ByteArrayOutputStream();  
  9.     byte[] buffer = new byte[1024];  
  10.     int len = -1;  
  11.       
  12.     while((len = is.read(buffer)) != -1) {  
  13.         baos.write(buffer, 0, len);  
  14.     }  
  15.     is.close();  
  16.       
  17.     String html = baos.toString();  // 把流中的数据转换成字符串, 采用的编码是: utf-8  
  18.       
  19.     String charset = "utf-8";  
  20.     if(html.contains("gbk") || html.contains("gb2312")  
  21.             || html.contains("GBK") || html.contains("GB2312")) {       // 如果包含gbk, gb2312编码, 就采用gbk编码进行对字符串编码  
  22.         charset = "gbk";  
  23.     }  
  24.       
  25.     html = new String(baos.toByteArray(), charset); // 对原有的字节数组进行使用处理后的编码名称进行编码  
  26.     baos.close();  
  27.     return html;  
  28. }  

使用HttpURLConnection采用Post方式请求数据

Servlet服务器程序

[java]  view plain  copy
  在CODE上查看代码片 派生到我的代码片
  1. package com.itheima28.servlet;  
  2.   
  3. import java.io.IOException;  
  4. import java.io.PrintWriter;  
  5.   
  6. import javax.servlet.ServletException;  
  7. import javax.servlet.http.HttpServlet;  
  8. import javax.servlet.http.HttpServletRequest;  
  9. import javax.servlet.http.HttpServletResponse;  
  10.   
  11. public class LoginServlet extends HttpServlet {  
  12.   
  13.     /** 
  14.      * The doGet method of the servlet. <br> 
  15.      * 
  16.      * This method is called when a form has its tag value method equals to get. 
  17.      *  
  18.      * @param request the request send by the client to the server 
  19.      * @param response the response send by the server to the client 
  20.      * @throws ServletException if an error occurred 
  21.      * @throws IOException if an error occurred 
  22.      */  
  23.     public void doGet(HttpServletRequest request, HttpServletResponse response)  
  24.             throws ServletException, IOException {  
  25.         String username = request.getParameter("username"); // 采用的编码是: iso-8859-1  
  26.         String password = request.getParameter("password");  
  27.           
  28.         // 采用iso8859-1的编码对姓名进行逆转, 转换成字节数组, 再使用utf-8编码对数据进行转换, 字符串  
  29.         username = new String(username.getBytes("iso8859-1"), "utf-8");  
  30.         password = new String(password.getBytes("iso8859-1"), "utf-8");  
  31.           
  32.         System.out.println("姓名: " + username);  
  33.         System.out.println("密码: " + password);  
  34.           
  35.         if("lisi".equals(username) && "123".equals(password)) {  
  36.             /* 
  37.              * getBytes 默认情况下, 使用的iso8859-1的编码, 但如果发现码表中没有当前字符,  
  38.              * 会使用当前系统下的默认编码: GBK 
  39.              */   
  40.             response.getOutputStream().write("登录成功".getBytes("utf-8"));  
  41.         } else {  
  42.             response.getOutputStream().write("登录失败".getBytes("utf-8"));  
  43.         }  
  44.     }  
  45.   
  46.     /** 
  47.      * The doPost method of the servlet. <br> 
  48.      * 
  49.      * This method is called when a form has its tag value method equals to post. 
  50.      *  
  51.      * @param request the request send by the client to the server 
  52.      * @param response the response send by the server to the client 
  53.      * @throws ServletException if an error occurred 
  54.      * @throws IOException if an error occurred 
  55.      */  
  56.     public void doPost(HttpServletRequest request, HttpServletResponse response)  
  57.             throws ServletException, IOException {  
  58.         System.out.println("doPost");  
  59.         doGet(request, response);  
  60.     }  
  61.   
  62. }  

Android客户端

[html]  view plain  copy
  在CODE上查看代码片 派生到我的代码片
  1. <?xml version="1.0" encoding="utf-8"?>  
  2. <manifest xmlns:android="http://schemas.android.com/apk/res/android"  
  3.     package="com.itheim28.submitdata"  
  4.     android:versionCode="1"  
  5.     android:versionName="1.0" >  
  6.   
  7.     <uses-sdk  
  8.         android:minSdkVersion="8"  
  9.         android:targetSdkVersion="17" />  
  10.     <uses-permission android:name="android.permission.INTERNET"/>  
  11.   
  12.     <application  
  13.         android:allowBackup="true"  
  14.         android:icon="@drawable/ic_launcher"  
  15.         android:label="@string/app_name"  
  16.         android:theme="@style/AppTheme" >  
  17.         <activity  
  18.             android:name="com.itheim28.submitdata.MainActivity2"  
  19.             android:label="@string/app_name" >  
  20.             <intent-filter>  
  21.                 <action android:name="android.intent.action.MAIN" />  
  22.   
  23.                 <category android:name="android.intent.category.LAUNCHER" />  
  24.             </intent-filter>  
  25.         </activity>  
  26.     </application>  
  27.   
  28. </manifest>  

[html]  view plain  copy
  在CODE上查看代码片 派生到我的代码片
  1. <LinearLayout 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:orientation="vertical"  
  6.     tools:context=".MainActivity" >  
  7.   
  8.     <EditText  
  9.         android:id="@+id/et_username"  
  10.         android:layout_width="fill_parent"  
  11.         android:layout_height="wrap_content"  
  12.         android:hint="请输入姓名" />  
  13.   
  14.     <EditText  
  15.         android:id="@+id/et_password"  
  16.         android:layout_width="fill_parent"  
  17.         android:layout_height="wrap_content"  
  18.         android:hint="请输入密码" />  
  19.   
  20.     <Button  
  21.         android:layout_width="wrap_content"  
  22.         android:layout_height="wrap_content"  
  23.         android:onClick="doGet"  
  24.         android:text="Get方式提交" />  
  25.   
  26.     <Button  
  27.         android:layout_width="wrap_content"  
  28.         android:layout_height="wrap_content"  
  29.         android:onClick="doPost"  
  30.         android:text="Post方式提交" />  
  31. </LinearLayout>  
[java]  view plain  copy
  在CODE上查看代码片 派生到我的代码片
  1. package com.itheim28.submitdata.utils;  
  2.   
  3. import java.io.ByteArrayOutputStream;  
  4. import java.io.IOException;  
  5. import java.io.InputStream;  
  6. import java.io.OutputStream;  
  7. import java.net.HttpURLConnection;  
  8. import java.net.MalformedURLException;  
  9. import java.net.URL;  
  10. import java.net.URLConnection;  
  11. import java.net.URLEncoder;  
  12.   
  13. import android.util.Log;  
  14.   
  15. public class NetUtils {  
  16.   
  17.     private static final String TAG = "NetUtils";  
  18.       
  19.     /** 
  20.      * 使用post的方式登录 
  21.      * @param userName 
  22.      * @param password 
  23.      * @return 
  24.      */  
  25.     public static String loginOfPost(String userName, String password) {  
  26.         HttpURLConnection conn = null;  
  27.         try {  
  28.             URL url = new URL("http://10.0.2.2:8080/ServerItheima28/servlet/LoginServlet");  
  29.               
  30.             conn = (HttpURLConnection) url.openConnection();  
  31.               
  32.             conn.setRequestMethod("POST");  
  33.             conn.setConnectTimeout(10000); // 连接的超时时间  
  34.             conn.setReadTimeout(5000); // 读数据的超时时间  
  35.             conn.setDoOutput(true); // 必须设置此方法, 允许输出  
  36. //          conn.setRequestProperty("Content-Length", 234);     // 设置请求头消息, 可以设置多个  
  37.               
  38.             // post请求的参数  
  39.             String data = "username=" + userName + "&password=" + password;  
  40.               
  41.             // 获得一个输出流, 用于向服务器写数据, 默认情况下, 系统不允许向服务器输出内容  
  42.             OutputStream out = conn.getOutputStream();    
  43.             out.write(data.getBytes());  
  44.             out.flush();  
  45.             out.close();  
  46.               
  47.             int responseCode = conn.getResponseCode();  
  48.             if(responseCode == 200) {  
  49.                 InputStream is = conn.getInputStream();  
  50.                 String state = getStringFromInputStream(is);  
  51.                 return state;  
  52.             } else {  
  53.                 Log.i(TAG, "访问失败: " + responseCode);  
  54.             }  
  55.         } catch (Exception e) {  
  56.             e.printStackTrace();  
  57.         } finally {  
  58.             if(conn != null) {  
  59.                 conn.disconnect();  
  60.             }  
  61.         }  
  62.         return null;  
  63.     }  
  64.   
  65.     /** 
  66.      * 使用get的方式登录 
  67.      * @param userName 
  68.      * @param password 
  69.      * @return 登录的状态 
  70.      */  
  71.     public static String loginOfGet(String userName, String password) {  
  72.         HttpURLConnection conn = null;  
  73.         try {  
  74.             String data = "username=" + URLEncoder.encode(userName) + "&password=" + URLEncoder.encode(password);  
  75.             URL url = new URL("http://10.0.2.2:8080/ServerItheima28/servlet/LoginServlet?" + data);  
  76.             conn = (HttpURLConnection) url.openConnection();  
  77.               
  78.             conn.setRequestMethod("GET");       // get或者post必须得全大写  
  79.             conn.setConnectTimeout(10000); // 连接的超时时间  
  80.             conn.setReadTimeout(5000); // 读数据的超时时间  
  81.               
  82.             int responseCode = conn.getResponseCode();  
  83.             if(responseCode == 200) {  
  84.                 InputStream is = conn.getInputStream();  
  85.                 String state = getStringFromInputStream(is);  
  86.                 return state;  
  87.             } else {  
  88.                 Log.i(TAG, "访问失败: " + responseCode);  
  89.             }  
  90.         } catch (Exception e) {  
  91.             e.printStackTrace();  
  92.         } finally {  
  93.             if(conn != null) {  
  94.                 conn.disconnect();      // 关闭连接  
  95.             }  
  96.         }  
  97.         return null;  
  98.     }  
  99.       
  100.     /** 
  101.      * 根据流返回一个字符串信息 
  102.      * @param is 
  103.      * @return 
  104.      * @throws IOException  
  105.      */  
  106.     private static String getStringFromInputStream(InputStream is) throws IOException {  
  107.         ByteArrayOutputStream baos = new ByteArrayOutputStream();  
  108.         byte[] buffer = new byte[1024];  
  109.         int len = -1;  
  110.           
  111.         while((len = is.read(buffer)) != -1) {  
  112.             baos.write(buffer, 0, len);  
  113.         }  
  114.         is.close();  
  115.           
  116.         String html = baos.toString();  // 把流中的数据转换成字符串, 采用的编码是: utf-8  
  117.           
  118. //      String html = new String(baos.toByteArray(), "GBK");  
  119.           
  120.         baos.close();  
  121.         return html;  
  122.     }  
  123. }  
[java]  view plain  copy
  在CODE上查看代码片 派生到我的代码片
  1. package com.itheim28.submitdata;  
  2.   
  3. import com.itheim28.submitdata.utils.NetUtils;  
  4.   
  5. import android.os.Bundle;  
  6. import android.app.Activity;  
  7. import android.view.Menu;  
  8. import android.view.View;  
  9. import android.widget.EditText;  
  10. import android.widget.Toast;  
  11.   
  12. public class MainActivity extends Activity {  
  13.   
  14.     private EditText etUserName;  
  15.     private EditText etPassword;  
  16.   
  17.     @Override  
  18.     protected void onCreate(Bundle savedInstanceState) {  
  19.         super.onCreate(savedInstanceState);  
  20.         setContentView(R.layout.activity_main);  
  21.           
  22.         etUserName = (EditText) findViewById(R.id.et_username);  
  23.         etPassword = (EditText) findViewById(R.id.et_password);  
  24.     }  
  25.   
  26.     public void doGet(View v) {  
  27.         final String userName = etUserName.getText().toString();  
  28.         final String password = etPassword.getText().toString();  
  29.           
  30.         new Thread(  
  31.                 new Runnable() {  
  32.                       
  33.                     @Override  
  34.                     public void run() {  
  35.                         // 使用get方式抓去数据  
  36.                         final String state = NetUtils.loginOfGet(userName, password);  
  37.                           
  38.                         // 执行任务在主线程中  
  39.                         runOnUiThread(new Runnable() {  
  40.                             @Override  
  41.                             public void run() {  
  42.                                 // 就是在主线程中操作  
  43.                                 Toast.makeText(MainActivity.this, state, 0).show();  
  44.                             }  
  45.                         });  
  46.                     }  
  47.                 }).start();  
  48.     }  
  49.       
  50.     public void doPost(View v) {  
  51.         final String userName = etUserName.getText().toString();  
  52.         final String password = etPassword.getText().toString();  
  53.           
  54.         new Thread(new Runnable() {  
  55.             @Override  
  56.             public void run() {  
  57.                 final String state = NetUtils.loginOfPost(userName, password);  
  58.                 // 执行任务在主线程中  
  59.                 runOnUiThread(new Runnable() {  
  60.                     @Override  
  61.                     public void run() {  
  62.                         // 就是在主线程中操作  
  63.                         Toast.makeText(MainActivity.this, state, 0).show();  
  64.                     }  
  65.                 });  
  66.             }  
  67.         }).start();  
  68.     }  
  69. }  
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值