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", "zhaoqi@itheima.com");
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();
}
});
}
}
Android核心基础(四)的更多相关文章
- Android核心基础(手机卫士的一个知识点总结)
注意:有些功能是需要权限的,在这里并没有写出来,在程序运行中,根据程序报的错误,添加相应的权限即可,里面的具体里面可能有一些小细节,没有明确的写出来,具体的需要在程序中自己调试,解决. 这个总结涵盖了 ...
- Android核心基础(二)
1.对应用进行单元测试 在实际开发中,开发android软件的过程需要不断地进行测试.而使用Junit测试框架,侧是正规Android开发的必用技术,在Junit中可以得到组件,可以模拟发送事件和检测 ...
- Android核心基础(十一)
1.Android的状态栏通知(Notification) 通知用于在状态栏显示消息,消息到来时以图标方式表示,如下: //获取通知管理器 NotificationManager mNotificat ...
- Android核心基础(十)
1.音频采集 你可以使用手机进行现场录音,实现步骤如下: 第一步:在功能清单文件AndroidManifest.xml中添加音频刻录权限: <uses-permission android:na ...
- Android核心基础(五)
1.仿网易新闻客户端 <LinearLayout xmlns:android="http://schemas.android.com/apk/res/android" xml ...
- Android核心基础
第三代移动通讯技术(3rd Generation) ,支持高速数据传输的蜂窝移动通讯技术.3G与2G的主要区别是传输数据的速度. 1987年,第一台模拟制式手机(1G)问世,只能进行语音通话,型号:摩 ...
- 四、Android学习第四天——JAVA基础回顾(转)
(转自:http://wenku.baidu.com/view/af39b3164431b90d6c85c72f.html) 四.Android学习第四天——JAVA基础回顾 这才学习Android的 ...
- 20145213 《Java程序设计》实验四 Android开发基础
20145213 <Java程序设计>实验四 Android开发基础 说在前面的话 不同以往实验,对于这次实验具体内容我是比较茫然的.因为点我,打开实验四的链接居然能飘出一股熟悉的味道,这 ...
- 20145206实验四《Android开发基础》
20145206 实验四<Android开发基础> 实验内容 ·安装Android Studio ·运行安卓AVD模拟器 ·使用安卓运行出虚拟手机并显示HelloWorld以及自己的学号 ...
随机推荐
- hdu 1754 I Hate It (模板线段树)
http://acm.hdu.edu.cn/showproblem.php?pid=1754 I Hate It Time Limit: 9000/3000 MS (Java/Others) M ...
- java单例模式使用及注意事项
1. 说明 1)单例模式:确保一个类只有一个实例,自行实例化并向系统提供这个实例 2)单例模式分类:饿单例模式(类加载时实例化一个对象给自己的引用),懒单例模式(调用取得实例的方法如getInstan ...
- Java编程思想(2)之一切皆对象
- Linux下 config/configure/Configure、make 、make test/make check、sudo make install 的作用
转自Linux下 config/configure/Configure.make .make test/make check.sudo make install 的作用 这些都是典型的使用GNU的AU ...
- eclipse查看.project .class隐藏文件
fileter ->*.resource勾选:
- Spring 配置XML文件头部文件格式
普通格式: <?xml version="1.0" encoding="UTF-8" ?> <beans xmlns:xsi="ht ...
- strspn和strcspn妙用
http://blog.csdn.net/aidenliu/article/details/5460201
- SPRING IN ACTION 第4版笔记-第四章ASPECT-ORIENTED SPRING-002-AOP术语解析
一. 1.Advice Advice是切面的要做的操作,它定义了what.when(什么时候要做什么事) aspects have a purpose—a job they’re meant to d ...
- ANDROID_MARS学习笔记_S01原始版_023_MP3PLAYER004_同步显示歌词
一.流程分析 1.点击播放按钮,会根据lrc名调用LrcProcessor的process()分析歌词文件,得到时间队列和歌词队列 2.new一个hander,把时间队列和歌词队列传给自定义的线程类U ...
- 酷盘kanbox获得B轮2000万美元融资
和阿里近期收购以穷游.虾米为代表的一批小网站相似,酷盘也属于个人用户数量级别庞大,但商业模式并不明晰的企业.目前阿里巴巴集团旗下的阿里云公司拥有自己的云存储业务,其本身既有面向个人用户的产品,也有面向 ...