android api总结(2)

1 网络图片查看器:
1.1 在布局中设置一个EditView和一个buttton用于输入网络图片资源地址和请求资源
1.2 URL url = new URL(path);
   HttpURLConnection conn = (HttpURLConnection)url.openConnection();
1.3 指定一些连接参数
   conn.setRequestMethod("GET");
   conn.setConnectTimeout(5000);
   conn.setRequestProperty("User-Agent", "Mozilla/4.0 (compatible; MSIE 7.0; Windows NT 5.1; .NET CLR 2.0.50727; .NET4.0C)");
1.4 判断conn.getResultCode==200
处理conn.getInputStream();拿到返回的输入流
1.5 BitmapFactory.decodeStream(is)对输入流进行解码,返回BitMap对象
iv_image.setImageBitmap(bitmap);设置图片显示
1.6 对图片进行压缩存储显示
FileOutputStream fos = new FileOutputStream(file);
bitmap.compress(CompressFormat.PNG, 100, fos);
iv_image.setImageURI(Uri.fromFile(file));
1.7 使用图片缓存sd卡
File file = new File(Environment.getExternalStorageDirectory(),getFileName(path));
if(file.exists()&&file.length()>0){
System.out.println("使用sd卡的缓存图片");
iv_image.setImageURI(Uri.fromFile(file));
return;
}
2 网页源码查看器及对乱码的处理
if (conn.getResponseCode() == 200) {
InputStream is = conn.getInputStream();
byte[] data = StreamTools.getBytes(is);
String tempstr = new String(data, "gbk");
if (tempstr.contains("charset=utf-8")){
tv_content.setText(new String(data, "utf-8"));
}else if(tempstr.contains("charset=gbk")){
tv_content.setText(new String(data, "gbk"));
}
}
3.网页新闻客户端
对上面的综合应用;没有什么新的知识点
就是使用到了对xml文件解析使用domain对数据进行封装;
4,以get的方式向服务器提交数据
4.1.在写服务器servlet进行对以get方式提交的数据时
new String(request.getParameter("xxx").getByte("ISO-8859-1"),"UTF-8");
4.2.在客户端中注意的要点:
4.2.1提交中文的信息 必须对数据进行url编码
String newname = URLEncoder.encode(name);
4.2.2获取到服务器返回的数据要手工的转码 知道服务器是以什么编码进行response写出的;
byte[] data = StreamTools.getBytes(is);//StreamTools是将输入流通过baos转字节数组的;
String message = new String(data, "gbk");//gbk是对象response的输出;
4.2.3注意路径的写法(手工组拼路径);
String path = "http://192.168.1.250:8080/web/LoginServlet?name="+ newname + "&password=" + newpassword;
5 以post的方式向服务器提交数据
5.1 在写服务器servlet的post方法中
new String(request.getParameter("xxx").getByte("ISO-8859-1"),"UTF-8");
5.3 在客户端中通过post的方式向服务器提交数据必须要设置 content-type content-length
conn.setRequestProperty("Content-Type","application/x-www-form-urlencoded");
5.4 提交中文的信息 必须对数据进行url编码
String newname = URLEncoder.encode(name);
5.5 组拼出来的要提交的数据
String data = "name=" + newname + "&password=" + newpassword;
5.6 计算出要提交数据的长度
conn.setRequestProperty("Content-Length", data.length() + "");
5.7 设置允许想服务器提交数据
conn.setDoOutput(true);
5.8 拿到想服务器写数据的输出流,写出数据
OutputStream os = conn.getOutputStream();
os.write(data.getBytes());
5.9 处理服务器的响应结果;
byte[] result = StreamTools.getBytes(is);
6 使用HttpClient 是apache提供get和post方式提交数据的封装
6.1 以get方式提交数据
6.1.1 打开一个浏览器
DefaultHttpClient client = new DefaultHttpClient();
6.1.2 准备一个http的get请求并且对参数进行urlencoder得到路径path
HttpGet httpget = new HttpGet(path);
6.1.3  敲回车
HttpResponse response = client.execute(httpGet);
int code = response.getStatusLine().getStatusCode();
对code进行判断服务器的响应信息如 ==200;
完成对响应输入流的处理;
6.2 以post方式提交数据
6.2.1 打开一个浏览器
DefaultHttpClient client = new DefaultHttpClient();
6.2.2 准备一个http的post请求
String path = "http://192.168.1.250:8080/web/LoginServlet";
HttpPost httpPost = new HttpPost(path);
List<NameValuePair> parameters = new ArrayList<NameValuePair>();
parameters.add(new BasicNameValuePair("name", name));
parameters.add(new BasicNameValuePair("password", password));
httpPost.setEntity(new UrlEncodedFormEntity(parameters, "UTF-8"));
6.2.3 敲回车
HttpResponse response = client.execute(httpPost);
int code = response.getStatusLine().getStatusCode();
对code进行判断服务器的响应信息如 ==200;
完成对响应输入流的处理;
7 上传数据到服务器;
客户端:
public static void uploadFile(Context context, File file) {
// 创建一个httppost的请求
PostMethod filePost = new PostMethod(
"http://192.168.1.250:8080/web/UploadFileServlet");
try {
// 组拼上传的数据
Part[] parts = { new StringPart("source", "695132533"),
new StringPart("status", "lisi"),
new FilePart("file", file) };
filePost.setRequestEntity(new MultipartRequestEntity(parts,
filePost.getParams()));
HttpClient client = new HttpClient();
client.getHttpConnectionManager().getParams()
.setConnectionTimeout(5000);
int status = client.executeMethod(filePost);
if (status == 200) {
Toast.makeText(context, "上传文件成功", 0).show();
}
} catch (Exception e) {
Toast.makeText(context, "上传文件失败", 0).show();
}


finally {
filePost.releaseConnection();
}
}
服务器端:
doPost(HttpServletRequest request,HttpServletResponse response) throws ServletException, IOException {
boolean isMultipart = ServletFileUpload.isMultipartContent(request);
if (isMultipart) {
String realpath = request.getSession().getServletContext().getRealPath("/files");
System.out.println(realpath);
File dir = new File(realpath);
if (!dir.exists())
dir.mkdirs();


FileItemFactory factory = new DiskFileItemFactory();
ServletFileUpload upload = new ServletFileUpload(factory);
upload.setHeaderEncoding("UTF-8");
try {
List<FileItem> items = upload.parseRequest(request);
for (FileItem item : items) {
if (item.isFormField()) {
String name1 = item.getFieldName();// 得到请求参数的名称
String value = item.getString("UTF-8");// 得到参数值
System.out.println(name1 + "=" + value);
} else {
item.write(new File(dir, System.currentTimeMillis()+ item.getName().substring(item.getName().lastIndexOf("."))));
}
}
} catch (Exception e) {
e.printStackTrace();
}
} else {
doGet(request, response);
}
}


8 调用webservice获取网络天气信息,手机号归属地:
8.1 获取手机归属地,因为对网络服务器请求这类信息是以json格式返回数据的所以在拿到响应的输入流后要
byte[] data = StreamTools.getBytes(is);
String result = new String(data);
JSONObject obj = new JSONObject(result);
String city = (String) obj.get("City");
String Corp = (String) obj.get("Corp");
tv_address.setText("城市:"+city+"\n"+"运营商"+Corp);
8.2 获取天气的信息;
http://api.showji.com/Locating/20080808.aspx?m=13512345678&output=json


http://www.showji.com/search.htm?m=13812345678


1 ANR application nor response 应用程序无响应
1.1 产生的原因是
在ui线程中进行了耗时的操作;android系统里面所有的activity
都运行在主线程中,系统为了保证所有的控件都可以响应到对应的
事件或者控件可以进行响应的更新.所以不允许主线程阻塞太久
一般超过6秒主线程阻塞,就会弹出anr对话框;
2.1 解决的办法;
将耗时操作放在子线程中去做;子线程处理完成通过消息机制通知ui线程更新;
或者通过asycTask这个异步任务类去处理耗时操作,asycTask是会开启线程池
去操作,所以选择消息机制或asnycTask处理看需求选择;
2 显示意图和隐式意图及使用意图传递数据;
2.1 显式意图
2.1.1 显式意图是通过Intent指定当前类对象和要开启的类对象
通过startActivity(intent)
   startService(intent) 开启就是显式意图;
如:Intent intent = new Intent(this,targerActivity.class);
   startActivity(intent);
2.2 隐式意图
2.2.1 隐式意图是通过在清单文件下的配置的<Intent-filter>节点下增加
<action android:name="xxx">
<category android:name="xxx.xxx"
2.2.2 通过在代码中指定意图,setAction和addCategory使用清单文件的配置名称;
Intent intent = new Intent();
intent.setAction("xxx");
intent.addCategory("xxx.xxx");
startActivity(intent); ----startService(intent);
2.3 传递数据
2.3.1 设置数据类型
intent.setType("text/plain");
2.3.2 设置传递的数据
intent.setData(Uri.parse("lwf://cn.lwf.intent"));
2.3.3 如果要设置传递数据和数据类型,不能分开写,要使用
intent.setDataAndType(Uri.parse("lwf://cn.lwf.intent"),"text/plain");
2.3.4 传递一组数据
intent.putExtra("name","张三");
Bundle extras = new Bundle();
intent.putExtras(extras);
3 激活系统发短信的组件
intent.setAction("android.intent.action.SENDTO");
intent.addCategory("android.intent.category.DEFAULT");
4 开启activity获取返回结果
4.1 指定以获取返回结果的方式开启意图,resultcode指定为0,给请求的activity返回时做判断;
startActivityForResult(intent, 0);
4.2 当请求开启的界面被关闭掉的时候调用的方法
onActivityResult(int requestCode, int resultCode, Intent data);resultCode:请求activity的返回
4.3 在被请求的activity中开启意图; setOnItemClickListener
Intent data = new Intent();
data.putExtra("xxx", map.get("xxx"));
data.putExtra("number", map.get("number"));
if (position == 1) {
setResult(10, data);
}else{
setResult(0, data);
}
finish();

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值