Android教程網
  1. 首頁
  2. Android 技術
  3. Android 手機
  4. Android 系統教程
  5. Android 游戲
 Android教程網 >> Android技術 >> 關於Android編程 >> Android核心基礎

Android核心基礎

編輯:關於Android編程

1、聯系人表結構


添加一條聯系人信息

package com.itheima.insertcontact;


import android.app.Activity;

import android.content.ContentValues;

import android.database.Cursor;

import android.net.Uri;

import android.os.Bundle;

import android.view.View;


public class MainActivity extends Activity {


    @Override

    protected void onCreate(Bundle savedInstanceState) {

        super.onCreate(savedInstanceState);

        setContentView(R.layout.activity_main);

    }


    public void click(View view){

     //1.在raw_contact表裡面添加一條聯系人的id

     Uri uri = Uri.parse("content://com.android.contacts/raw_contacts");

     Cursor cursor = getContentResolver().query(uri, new String[]{"_id"}, null, null, null);

     cursor.moveToLast();

     int _id = cursor.getInt(0);

     int newid = _id+1;

     ContentValues values = new ContentValues();

     values.put("contact_id", newid);

     getContentResolver().insert(uri, values);

     //2.根據聯系人的id  在 data表裡面 添加對應的數據

     Uri dataUri = Uri.parse("content://com.android.contacts/data");

    

     //插入電話

     ContentValues phoneValues = new ContentValues();

     phoneValues.put("data1", "999999");

     phoneValues.put("mimetype", "vnd.android.cursor.item/phone_v2");

     phoneValues.put("raw_contact_id", newid);


     getContentResolver().insert(dataUri, phoneValues);

    

     //插入郵箱

     ContentValues emailValues = new ContentValues();

     emailValues.put("data1", "[email protected]");

     emailValues.put("mimetype", "vnd.android.cursor.item/email_v2");

     emailValues.put("raw_contact_id", newid);


     getContentResolver().insert(dataUri, emailValues);

    

    

     //插入姓名

     ContentValues nameValues = new ContentValues();

     nameValues.put("data1", "zhaoqi");

     nameValues.put("mimetype", "vnd.android.cursor.item/name");

     nameValues.put("raw_contact_id", newid);


     getContentResolver().insert(dataUri, nameValues);

    }

   

}


讀取聯系人

package com.itheima.readcontacts.service;


import java.util.ArrayList;

import java.util.List;


import android.content.ContentResolver;

import android.content.Context;

import android.database.Cursor;

import android.net.Uri;


import com.itheima.readcontacts.domain.ContactInfo;


public class ContactInfoService {


/**

 * 獲取手機裡面全部的聯系人信息

 * @return

 */

public static List<ContactInfo> getContactInfos(Context context){


ContentResolver resolver = context.getContentResolver();

Uri uri = Uri.parse("content://com.android.contacts/raw_contacts");

Uri dataUri = Uri.parse("content://com.android.contacts/data");

List<ContactInfo>  contactInfos = new ArrayList<ContactInfo>();

Cursor cursor = resolver.query(uri, new String[]{"contact_id"}, null, null, null);

while(cursor.moveToNext()){

String contact_id = cursor.getString(0);

System.out.println("聯系人id:"+contact_id);

//根據聯系人的id 查詢 data表裡面的數據

Cursor dataCursor = resolver.query(dataUri, new String[]{"data1","mimetype"}, "raw_contact_id=?", new String[]{contact_id}, null);

ContactInfo contactInfo = new ContactInfo();

while(dataCursor.moveToNext()){

String data1 = dataCursor.getString(0);

String mimetype = dataCursor.getString(1);

if("vnd.android.cursor.item/phone_v2".equals(mimetype)){

contactInfo.setPhone(data1);

}else if("vnd.android.cursor.item/email_v2".equals(mimetype)){

contactInfo.setEmail(data1);

}else if("vnd.android.cursor.item/name".equals(mimetype)){

contactInfo.setName(data1);

}

}

dataCursor.close();

contactInfos.add(contactInfo);

}

cursor.close();

return contactInfos;

}

}

 

 

2、從Internet獲取數據

利用HttpURLConnection對象,我們可以從網絡中獲取網頁數據.

URL url = new URL("http://www.sohu.com");

HttpURLConnection conn = (HttpURLConnection) url.openConnection();

conn.setConnectTimeout(5* 1000);//設置連接超時

conn.setRequestMethod(“GET”);//以get方式發起請求

if (conn.getResponseCode() != 200) throw new RuntimeException("請求url失敗");

InputStream is = conn.getInputStream();//得到網絡返回的輸入流

String result = readData(is, "GBK");

conn.disconnect();

//第一個參數為輸入流,第二個參數為字符集編碼

public static String readData(InputStream inSream, String charsetName) throws Exception{

ByteArrayOutputStream outStream = new ByteArrayOutputStream();

byte[] buffer = new byte[1024];

int len = -1;

while( (len = inSream.read(buffer)) != -1 ){

outStream.write(buffer, 0, len);

}

byte[] data = outStream.toByteArray();

outStream.close();

inSream.close();

return new String(data, charsetName);

}

<!-- 訪問internet權限 -->

<uses-permission android:name="android.permission.INTERNET"/>


利用HttpURLConnection對象,我們可以從網絡中獲取文件數據.

URL url = new URL("http://photocdn.sohu.com/20100125/Img269812337.jpg");

HttpURLConnection conn = (HttpURLConnection) url.openConnection();

conn.setConnectTimeout(5* 1000);

conn.setRequestMethod("GET");

if (conn.getResponseCode() != 200) throw new RuntimeException("請求url失敗");

InputStream is = conn.getInputStream();

readAsFile(is, "Img269812337.jpg");

public static void readAsFile(InputStream inSream, File file) throws Exception{

FileOutputStream outStream = new FileOutputStream(file);

byte[] buffer = new byte[1024];

int len = -1;

while( (len = inSream.read(buffer)) != -1 ){

outStream.write(buffer, 0, len);

}

 outStream.close();

inSream.close();

}

3、向Internet發送請求參數

String requestUrl = "http://localhost:8080/itcast/contanctmanage.do";

Map<String, String> requestParams = new HashMap<String, String>();

requestParams.put("age", "12");

requestParams.put("name", "中國");

 StringBuilder params = new StringBuilder();

for(Map.Entry<String, String> entry : requestParams.entrySet()){

params.append(entry.getKey());

params.append("=");

params.append(URLEncoder.encode(entry.getValue(), "UTF-8"));

params.append("&");

}

if (params.length() > 0) params.deleteCharAt(params.length() - 1);

byte[] data = params.toString().getBytes();

URL realUrl = new URL(requestUrl);

HttpURLConnection conn = (HttpURLConnection) realUrl.openConnection();

conn.setDoOutput(true);//發送POST請求必須設置允許輸出

conn.setUseCaches(false);//不使用Cache

conn.setRequestMethod("POST");       

conn.setRequestProperty("Connection", "Keep-Alive");//維持長連接

conn.setRequestProperty("Charset", "UTF-8");

conn.setRequestProperty("Content-Length", String.valueOf(data.length));

conn.setRequestProperty("Content-Type","application/x-www-form-urlencoded");

DataOutputStream outStream = new DataOutputStream(conn.getOutputStream());

outStream.write(data);

outStream.flush();

if( conn.getResponseCode() == 200 ){

        String result = readAsString(conn.getInputStream(), "UTF-8");

        outStream.close();

        System.out.println(result);

}

4、向Internet發送xml數據

利用HttpURLConnection對象,我們可以向網絡發送xml數據.

StringBuilder xml =  new StringBuilder();

xml.append("<?xml version=\"1.0\" encoding=\"utf-8\" ?>");

xml.append("<M1 V=10000>");

xml.append("<U I=1 D=\"N73\">中國</U>");

xml.append("</M1>");

byte[] xmlbyte = xml.toString().getBytes("UTF-8");

URL url = new URL("http://localhost:8080/itcast/contanctmanage.do?method=readxml");

HttpURLConnection conn = (HttpURLConnection) url.openConnection();

conn.setConnectTimeout(5* 1000);

conn.setDoOutput(true);//允許輸出

conn.setUseCaches(false);//不使用Cache

conn.setRequestMethod("POST");       

conn.setRequestProperty("Connection", "Keep-Alive");//維持長連接

conn.setRequestProperty("Charset", "UTF-8");

conn.setRequestProperty("Content-Length", String.valueOf(xmlbyte.length));

conn.setRequestProperty("Content-Type", "text/xml; charset=UTF-8");

DataOutputStream outStream = new DataOutputStream(conn.getOutputStream());

outStream.write(xmlbyte);//發送xml數據

outStream.flush();

if (conn.getResponseCode() != 200) throw new RuntimeException("請求url失敗");

InputStream is = conn.getInputStream();//獲取返回數據

String result = readAsString(is, "UTF-8");

outStream.close();


5、網絡圖片查看器

package com.ithiema.newimageviewer;


import java.io.InputStream;

import java.net.HttpURLConnection;

import java.net.URL;


import android.app.Activity;

import android.graphics.Bitmap;

import android.graphics.BitmapFactory;

import android.os.Bundle;

import android.os.Handler;

import android.os.Message;

import android.text.TextUtils;

import android.view.View;

import android.widget.EditText;

import android.widget.ImageView;

import android.widget.Toast;


public class MainActivity extends Activity {

protected static final int GET_IMAGE_SUCCESS = 1;

protected static final int SERVER_ERROR = 2;

protected static final int LOAD_IMAGE_ERROR = 3;

private ImageView iv_icon;

private EditText et_path;


/**

 * 在主線程創建一個消息處理器

 */

private Handler handler = new Handler(){


//處理消息的 運行在主線程裡面

@Override

public void handleMessage(Message msg) {

super.handleMessage(msg);

switch (msg.what) {

case GET_IMAGE_SUCCESS:

Bitmap bm = (Bitmap) msg.obj;

iv_icon.setImageBitmap(bm);

break;

case SERVER_ERROR:

Toast.makeText(MainActivity.this, "連接服務器錯誤", 0).show();

break;

case LOAD_IMAGE_ERROR:

Toast.makeText(MainActivity.this, "獲取圖片錯誤", 0).show();

break;

}


}

 

};

 

@Override

protected void onCreate(Bundle savedInstanceState) {

super.onCreate(savedInstanceState);

setContentView(R.layout.activity_main);

iv_icon = (ImageView) findViewById(R.id.iv_icon);

et_path = (EditText) findViewById(R.id.et_path);


getMainLooper();

}


public void click(View view) {

final String path = et_path.getText().toString().trim();

if (TextUtils.isEmpty(path)) {

Toast.makeText(this, "路徑不能為空", 0).show();

return;

} else {

new Thread() {

public void run() {

// 以httpget的方式 請求數據.獲取圖片的流

try {

URL url = new URL(path);

HttpURLConnection conn = (HttpURLConnection) url

.openConnection();

// 設置請求方式

conn.setRequestMethod("GET");

// 設置連接超時時間

conn.setConnectTimeout(3000);

conn.setRequestProperty(

"User-Agent",

"Mozilla/4.0 (compatible; MSIE 8.0; Windows NT 5.1; Trident/4.0; .NET4.0C; .NET4.0E; .NET CLR 2.0.50727; .NET CLR 3.0.4506.2152; .NET CLR 3.5.30729; Shuame)Mozilla/4.0 (compatible; MSIE 8.0; Windows NT 5.1; Trident/4.0; .NET4.0C; .NET4.0E; .NET CLR 2.0.50727; .NET CLR 3.0.4506.2152; .NET CLR 3.5.30729; Shuame)");


// 獲取服務器端返回的狀態碼

int code = conn.getResponseCode();

if (code == 200) {

// 獲取服務器端返回的流

InputStream is = conn.getInputStream();

Bitmap bitmap = BitmapFactory.decodeStream(is);

//iv_icon.setImageBitmap(bitmap);

//不可以直接更新界面,發送消息更新界面

Message msg = new Message();

msg.obj = bitmap;

msg.what = GET_IMAGE_SUCCESS;

handler.sendMessage(msg);


} else {

//Toast.makeText(MainActivity.this, "連接服務器錯誤", 0).show();

Message msg = new Message();

msg.what = SERVER_ERROR;

handler.sendMessage(msg);

}


} catch (Exception e) {

e.printStackTrace();

//Toast.makeText(getApplicationContext(), "獲取圖片失敗", 0).show();

Message msg = new Message();

msg.what = LOAD_IMAGE_ERROR;

handler.sendMessage(msg);

}

};

}.start();

}

}

}


6、HTML源代碼查看器

package com.itheima.htmlviewer;


import java.io.ByteArrayOutputStream;

import java.io.InputStream;

import java.net.HttpURLConnection;

import java.net.MalformedURLException;

import java.net.URL;


import android.app.Activity;

import android.os.Bundle;

import android.os.Handler;

import android.os.Message;

import android.text.TextUtils;

import android.view.View;

import android.widget.EditText;

import android.widget.TextView;

import android.widget.Toast;


public class MainActivity extends Activity {

protected static final int GET_HTML_FINISH = 1;

protected static final int LOAD_ERROR = 2;

private TextView tv_html;

private EditText et_path;

private Handler handler = new Handler(){

public void handleMessage(android.os.Message msg) {

switch (msg.what) {

case GET_HTML_FINISH:

String html = (String) msg.obj;

tv_html.setText(html);

break;


case LOAD_ERROR:

Toast.makeText(getApplicationContext(), "獲取html失敗", 0).show();

break;

}

};

};


@Override

protected void onCreate(Bundle savedInstanceState) {

super.onCreate(savedInstanceState);

setContentView(R.layout.activity_main);

tv_html = (TextView) findViewById(R.id.tv_html);

et_path = (EditText) findViewById(R.id.et_path);

}


public void click(View view) {

final String path = et_path.getText().toString().trim();

if (TextUtils.isEmpty(path)) {

Toast.makeText(this, "路徑不能為空", 0).show();

} else {

new Thread(){

public void run() {

try {

URL url = new URL(path);

HttpURLConnection conn = (HttpURLConnection) url.openConnection();

conn.setRequestMethod("GET");

conn.setConnectTimeout(3000);

int code = conn.getResponseCode();

if(code == 200){

InputStream is = conn.getInputStream();

ByteArrayOutputStream bos = new ByteArrayOutputStream();

int len =0;

byte[] buffer = new byte[1024];

while((len = is.read(buffer))!=-1){

bos.write(buffer, 0, len);

}

is.close();

String html = new String(bos.toByteArray(),"gbk");

Message msg = new Message();

msg.what = GET_HTML_FINISH;

msg.obj = html;

handler.sendMessage(msg);


}else{

Message msg = new Message();

msg.what = LOAD_ERROR;

handler.sendMessage(msg);

}


} catch (Exception e) {

Message msg = new Message();

msg.what = LOAD_ERROR;

handler.sendMessage(msg);

e.printStackTrace();

}

};

}.start();

 

}


}


}


7、模擬網絡登錄

package com.itheima.login;


import com.itheima.login.service.LoginService;


import android.os.Bundle;

import android.os.Handler;

import android.os.Message;

import android.app.Activity;

import android.text.TextUtils;

import android.view.Menu;

import android.view.View;

import android.widget.CheckBox;

import android.widget.EditText;

import android.widget.Toast;


/**

 * activity 實際上是上下文的一個子類

 * @author Administrator

 *

 */

public class MainActivity extends Activity {

protected static final int LOGIN = 1;

protected static final int ERROR = 2;

private EditText et_username;

private EditText et_password;

private CheckBox cb_remeber_pwd;


private Handler handler = new Handler(){

public void handleMessage(android.os.Message msg) {

switch (msg.what) {

case LOGIN:

String info = (String) msg.obj;

Toast.makeText(getApplicationContext(),info, 0).show();

break;


case ERROR:

Toast.makeText(getApplicationContext(), "連接網絡失敗...", 0).show();


break;

}

};

};

 

@Override

protected void onCreate(Bundle savedInstanceState) {

super.onCreate(savedInstanceState);

setContentView(R.layout.activity_main);

cb_remeber_pwd = (CheckBox) findViewById(R.id.cb_remeber_pwd);

et_username = (EditText) findViewById(R.id.et_username);

et_password = (EditText) findViewById(R.id.et_password);


try {

String result = LoginService.readUserInfoFromFile(this);

String[] infos = result.split("##");

et_username.setText(infos[0]);

et_password.setText(infos[1]);

} catch (Exception e) {

e.printStackTrace();

}


}

 

/**

 * 登陸按鈕的點擊事件

 * @param view

 */

public void login(View view){

final String username = et_username.getText().toString().trim();

final String password = et_password.getText().toString().trim();

if(TextUtils.isEmpty(username)||TextUtils.isEmpty(password)){

Toast.makeText(getApplicationContext(), "用戶名或者密碼不能為空", 0).show();

return;

}

//檢查是否勾選了cb

if(cb_remeber_pwd.isChecked()){//記住密碼

try {

LoginService.saveUserInfoToFile(this, username, password);

Toast.makeText(this, "保存用戶名密碼成功", 0).show();

} catch (Exception e) {

e.printStackTrace();

Toast.makeText(getApplicationContext(), "保存用戶名密碼失敗", 0).show();

}

}


new Thread(){

public void run() {

//登陸到服務器,發送一個httpget的請求

try {

String result = LoginService.loginByHttpClientPost(username, password);

Message msg = new Message();

msg.what = LOGIN;

msg.obj = result;

handler.sendMessage(msg);

} catch (Exception e) {

e.printStackTrace();

Message msg = new Message();

msg.what = ERROR;

handler.sendMessage(msg);

}

};

}.start();


}

}


package com.itheima.login.service;


import java.io.BufferedReader;

import java.io.File;

import java.io.FileInputStream;

import java.io.FileOutputStream;

import java.io.InputStream;

import java.io.InputStreamReader;

import java.io.OutputStream;

import java.net.HttpURLConnection;

import java.net.URL;

import java.net.URLEncoder;

import java.util.ArrayList;

import java.util.List;


import org.apache.http.HttpResponse;

import org.apache.http.NameValuePair;

import org.apache.http.client.HttpClient;

import org.apache.http.client.entity.UrlEncodedFormEntity;

import org.apache.http.client.methods.HttpGet;

import org.apache.http.client.methods.HttpPost;

import org.apache.http.impl.client.DefaultHttpClient;

import org.apache.http.message.BasicNameValuePair;


import android.content.Context;


import com.itheima.login.utils.StreamUtils;


/**

 * 登陸相關的服務

 *

 * @author Administrator

 *

 */

public class LoginService {

// 上下文 其實提供了應用程序 的一個詳細的環境信息. 包括 包名是什麼 /data/data/目錄在哪裡.

// we do chicken right


/**

 * 保存用戶信息到文件

 *

 * @param username

 *            用戶名

 * @param password

 *            密碼

 */

public static void saveUserInfoToFile(Context context, String username,

String password) throws Exception {

// File file = new File("/data/data/com.itheima.login/info.txt");

// File file = new File(context.getFilesDir(),"info.txt"); //在當前應用程序的目錄下

// 創建一個files目錄 裡面有一個文件 info.txt

// FileOutputStream fos = new FileOutputStream(file);


FileOutputStream fos = context.openFileOutput("info.txt",

Context.MODE_PRIVATE);// 追加模式


// zhangsan##123456

fos.write((username + "##" + password).getBytes());

fos.close();

}


/**

 * 讀取用戶的用戶名和密碼

 *

 * @return // zhangsan##123456

 */

public static String readUserInfoFromFile(Context context) throws Exception {

File file = new File(context.getFilesDir(), "info.txt");

FileInputStream fis = new FileInputStream(file);


BufferedReader br = new BufferedReader(new InputStreamReader(fis));

String line = br.readLine();

fis.close();

br.close();

return line;

}


/**

 * 采用http的get方式提交數據到服務器

 *

 * @return

 */

public static String loginByHttpGet(String username, String password)

throws Exception {

// http://localhost:8080/web/LoginServlet?username=zhangsan&password=123

String path = "http://192.168.1.100:8080/web/LoginServlet?username="

+ URLEncoder.encode(username, "UTF-8") + "&password="

+ URLEncoder.encode(password, "utf-8");

URL url = new URL(path);

HttpURLConnection conn = (HttpURLConnection) url.openConnection();

conn.setRequestMethod("GET");

conn.setConnectTimeout(5000);

int code = conn.getResponseCode();

if (code == 200) {

InputStream is = conn.getInputStream();

// 把is裡面的內容轉化成 string文本.

String result = StreamUtils.readStream(is);

return result;

} else {

return null;

}

}


/**

 * 采用http的post方式提交數據到服務器

 *

 * @return

 */

public static String loginByHttpPost(String username, String password)

throws Exception {

// 1.提交的地址

String path = "http://192.168.1.100:8080/web/LoginServlet";

URL url = new URL(path);

HttpURLConnection conn = (HttpURLConnection) url.openConnection();

// 2.請求方式

conn.setRequestMethod("POST");

// 准備數據

// username=zhangsan&password=123

String data = "username=" + URLEncoder.encode(username, "UTF-8")

+ "&password=" + URLEncoder.encode(password, "UTF-8");


// 3.注意:一定要設置請求頭參數

// 設置數據是一個form表單的類型

conn.setRequestProperty("Content-Type",

"application/x-www-form-urlencoded");

conn.setRequestProperty("Content-Length", data.length() + "");

conn.setConnectTimeout(5000);


// 4.post請求實際上是把數據以流的方式寫給了服務器

// 設置允許通過http請求向服務器寫數據

conn.setDoOutput(true);

// 得到一個向服務寫數據的流

OutputStream os = conn.getOutputStream();

os.write(data.getBytes());

int code = conn.getResponseCode();

if (code == 200) {

InputStream is = conn.getInputStream();

// 把is裡面的內容轉化成 string文本.

String result = StreamUtils.readStream(is);

return result;

} else {

return null;

}


}


public static String loginByHttpClientGet(String username, String password)

throws Exception {

// 1.打開一個浏覽器

HttpClient client = new DefaultHttpClient();

// 2.輸入地址

String path = "http://192.168.1.100:8080/web/LoginServlet?username="

+ URLEncoder.encode(username, "UTF-8") + "&password="

+ URLEncoder.encode(password, "utf-8");

HttpGet httpGet = new HttpGet(path);

// 3.敲回車

HttpResponse response = client.execute(httpGet);

int code = response.getStatusLine().getStatusCode();

if (code == 200) {

InputStream is = response.getEntity().getContent();

// 把is裡面的內容轉化成 string文本.

String result = StreamUtils.readStream(is);

return result;

}else{

return null;

}

}


/**

 * 采用httpclient的post方式提交數據到服務器

 * @param username

 * @param password

 * @return

 * @throws Exception

 */

public static String loginByHttpClientPost(String username, String password)

throws Exception {

// 1.打開一個浏覽器

HttpClient client = new DefaultHttpClient();

// 2.輸入地址

String path = "http://192.168.1.100:8080/web/LoginServlet";

HttpPost httpPost = new  HttpPost(path);

//設置要提交的數據實體

List<NameValuePair> parameters = new ArrayList<NameValuePair>();

parameters.add(new BasicNameValuePair("username", username));

parameters.add(new BasicNameValuePair("password", password));

UrlEncodedFormEntity entity = new UrlEncodedFormEntity(parameters,"UTF-8");

httpPost.setEntity(entity);

// 3.敲回車

HttpResponse response = client.execute(httpPost);

int code = response.getStatusLine().getStatusCode();

if (code == 200) {

InputStream is = response.getEntity().getContent();

// 把is裡面的內容轉化成 string文本.

String result = StreamUtils.readStream(is);

return result;

}else{

return null;

}

}


}


package com.itheima.login.utils;


import java.io.ByteArrayOutputStream;

import java.io.IOException;

import java.io.InputStream;


public class StreamUtils {

/**

 * 用默認碼表轉化一個inputstream裡面的內容 到 字符串

 * @param is 

 * @return

 */

public static String readStream(InputStream is) {

try {

ByteArrayOutputStream bos = new ByteArrayOutputStream();

int len = 0;

byte[] buffer = new byte[1024];

while ((len = is.read(buffer)) != -1) {

bos.write(buffer, 0, len);

}

is.close();

return new String(bos.toByteArray());

} catch (IOException e) {

e.printStackTrace();

return "";

}

}

}

 

8、SmartImageView網絡圖片查看器

package com.ithiema.newimageviewer;


import java.io.InputStream;

import java.net.HttpURLConnection;

import java.net.URL;


import android.app.Activity;

import android.graphics.Bitmap;

import android.graphics.BitmapFactory;

import android.os.Bundle;

import android.os.Handler;

import android.os.Message;

import android.text.TextUtils;

import android.view.View;

import android.widget.EditText;

import android.widget.ImageView;

import android.widget.Toast;


public class MainActivity extends Activity {

protected static final int GET_IMAGE_SUCCESS = 1;

protected static final int SERVER_ERROR = 2;

protected static final int LOAD_IMAGE_ERROR = 3;

private ImageView iv_icon;

private EditText et_path;


/**

 * 在主線程創建一個消息處理器

 */

private Handler handler = new Handler(){


//處理消息的 運行在主線程裡面

@Override

public void handleMessage(Message msg) {

super.handleMessage(msg);

switch (msg.what) {

case GET_IMAGE_SUCCESS:

Bitmap bm = (Bitmap) msg.obj;

iv_icon.setImageBitmap(bm);

break;

case SERVER_ERROR:

Toast.makeText(MainActivity.this, "連接服務器錯誤", 0).show();

break;

case LOAD_IMAGE_ERROR:

Toast.makeText(MainActivity.this, "獲取圖片錯誤", 0).show();

break;

}


}

 

};

 

@Override

protected void onCreate(Bundle savedInstanceState) {

super.onCreate(savedInstanceState);

setContentView(R.layout.activity_main);

iv_icon = (ImageView) findViewById(R.id.iv_icon);

et_path = (EditText) findViewById(R.id.et_path);


getMainLooper();

}


public void click(View view) {

final String path = et_path.getText().toString().trim();

if (TextUtils.isEmpty(path)) {

Toast.makeText(this, "路徑不能為空", 0).show();

return;

} else {

new Thread() {

public void run() {

// 以httpget的方式 請求數據.獲取圖片的流

try {

URL url = new URL(path);

HttpURLConnection conn = (HttpURLConnection) url

.openConnection();

// 設置請求方式

conn.setRequestMethod("GET");

// 設置連接超時時間

conn.setConnectTimeout(3000);

conn.setRequestProperty(

"User-Agent",

"Mozilla/4.0 (compatible; MSIE 8.0; Windows NT 5.1; Trident/4.0; .NET4.0C; .NET4.0E; .NET CLR 2.0.50727; .NET CLR 3.0.4506.2152; .NET CLR 3.5.30729; Shuame)Mozilla/4.0 (compatible; MSIE 8.0; Windows NT 5.1; Trident/4.0; .NET4.0C; .NET4.0E; .NET CLR 2.0.50727; .NET CLR 3.0.4506.2152; .NET CLR 3.5.30729; Shuame)");


// 獲取服務器端返回的狀態碼

int code = conn.getResponseCode();

if (code == 200) {

// 獲取服務器端返回的流

InputStream is = conn.getInputStream();

Bitmap bitmap = BitmapFactory.decodeStream(is);

//iv_icon.setImageBitmap(bitmap);

//不可以直接更新界面,發送消息更新界面

Message msg = new Message();

msg.obj = bitmap;

msg.what = GET_IMAGE_SUCCESS;

handler.sendMessage(msg);


} else {

//Toast.makeText(MainActivity.this, "連接服務器錯誤", 0).show();

Message msg = new Message();

msg.what = SERVER_ERROR;

handler.sendMessage(msg);

}


} catch (Exception e) {

e.printStackTrace();

//Toast.makeText(getApplicationContext(), "獲取圖片失敗", 0).show();

Message msg = new Message();

msg.what = LOAD_IMAGE_ERROR;

handler.sendMessage(msg);

}

};

}.start();

}

}

}


9、AsyncHttp登錄

package com.itheima.login;


import java.net.URLEncoder;


import com.loopj.android.http.AsyncHttpClient;

import com.loopj.android.http.AsyncHttpResponseHandler;

import com.loopj.android.http.RequestParams;


import android.os.Bundle;

import android.os.Handler;

import android.os.Message;

import android.app.Activity;

import android.text.TextUtils;

import android.view.Menu;

import android.view.View;

import android.widget.CheckBox;

import android.widget.EditText;

import android.widget.Toast;


/**

 * activity 實際上是上下文的一個子類

 *

 * @author Administrator

 *

 */

public class MainActivity extends Activity {

private EditText et_username;

private EditText et_password;


@Override

protected void onCreate(Bundle savedInstanceState) {

super.onCreate(savedInstanceState);

setContentView(R.layout.activity_main);

et_username = (EditText) findViewById(R.id.et_username);

et_password = (EditText) findViewById(R.id.et_password);


}


/**

 * GET登陸按鈕的點擊事件

 *

 * @param view

 */

public void login(View view) {

final String username = et_username.getText().toString().trim();

final String password = et_password.getText().toString().trim();

if (TextUtils.isEmpty(username) || TextUtils.isEmpty(password)) {

Toast.makeText(getApplicationContext(), "用戶名或者密碼不能為空", 0).show();

return;

}

String path = "http://192.168.1.100:8080/web/LoginServlet?username="

+ URLEncoder.encode(username) + "&password="

+ URLEncoder.encode(password);

AsyncHttpClient client = new AsyncHttpClient();

client.get(path, new AsyncHttpResponseHandler() {

@Override

public void onSuccess(String response) {

Toast.makeText(getApplicationContext(), response, 0).show();

}

});

}


/**

 * POST登陸按鈕的點擊事件

 *

 * @param view

 */

public void postLogin(View view) {

final String username = et_username.getText().toString().trim();

final String password = et_password.getText().toString().trim();

if (TextUtils.isEmpty(username) || TextUtils.isEmpty(password)) {

Toast.makeText(getApplicationContext(), "用戶名或者密碼不能為空", 0).show();

return;

}

String path = "http://192.168.1.100:8080/web/LoginServlet";

AsyncHttpClient client = new AsyncHttpClient();

RequestParams params = new RequestParams();

params.put("username", username);

params.put("password", password);

client.post(path, params, new AsyncHttpResponseHandler() {

@Override

public void onSuccess(String content) {

super.onSuccess(content);

Toast.makeText(getApplicationContext(), content, 0).show();

 

  1. 上一頁:
  2. 下一頁:
熱門文章
閱讀排行版
Copyright © Android教程網 All Rights Reserved