您的位置:首页 > 理论基础 > 计算机网络

安卓图片显示与网络访问

2019-08-07 11:24 45 查看

Picasso图片显示

Square公司开源的一个Android图形缓存库
Picasso实现了图片的异步加载,并解决了Android中加载图片时常见的一些问题,它有以下特点:
     1.在Adapter中取消了不在视图范围内的ImageView的资源加载,因为可能会产生图片错位;
     2.使用复杂的图片转换技术降低内存的使用
     3.自带内存和硬盘的二级缓存机制

引用库
Android Studio 3

implementation 'com.squareup.picasso:picasso:2.5.2'

Android Studio 2

compile 'com.squareup.picasso:picasso:2.5.2'

权限获取

<!--网络权限-->
<uses-permission android:name="android.permission.INTERNET" />
<!--文件读写权限-->
<uses-permission android:name="android.permission.READ_EXTERNAL_STORAGE" />

函数调用

private ImageView im;
im=findViewById(R.id.imageView2);
//picben("https://pic.cnblogs.com/face/1485202/20180908195218.png",im);
picben("/dongxiaodong/ww.jpg",im);

封装函数

//参数(地址,显示的控件)
public void  picben(String panx, ImageView imgviewx){
File sd= Environment.getExternalStorageDirectory();//得到SD卡的路径
Picasso.with(MainActivity.this)
.load(new File(sd,panx))//文件路径,必须打开文件读写权限
//.load(urlx)//URL,必须添加网络权限
//.memoryPolicy(MemoryPolicy.NO_CACHE,MemoryPolicy.NO_STORE)//待测试,图片加载跳过内存缓存中查找,图片不缓存到内存缓存中
.memoryPolicy(MemoryPolicy.NO_CACHE)//无缓存,加下面一句可实现
.networkPolicy(NetworkPolicy.NO_CACHE)
.placeholder(R.mipmap.mainon)//正在加载图片
.error(R.mipmap.mainoff)//尝试三次失败后 加载错误显示图片
.fit()//填充控件与resize不可共用
//.noFade()//无淡入淡出效果
//.resize(100,100)//图片要调整后的大小,必须配合下面两个之一
//.centerCrop()//配合resize使用,仅显示被框占位
//.centerInside()//配合resize使用,裁剪后填充满控件
//.rotate(30)//旋转30度
// .transform(new tCircle())可变为圆形状,但有黑底
.config(Bitmap.Config.RGB_565)//比ARGB_8888 质量稍差,但看基本不出
.into(imgviewx);//控件位置
}

OKHttp网络访问

okhttp是Square公司开源的一个非常便捷的轻量级第三方网络访问框架。它支持同步请求和异步请求。
HTTP是现代应用网络的方式。这就是我们交换数据和媒体的方式。有效地执行HTTP可以加快您的负载并节省带宽。

OkHttp是一个默认有效的HTTP客户端:
   1.HTTP / 2支持允许对同一主机的所有请求共享套接字。
   2.连接池减少了请求延迟(如果HTTP / 2不可用)。
   3.透明GZIP缩小了下载大小。
   4.响应缓存可以完全避免网络重复请求。

当网络很麻烦时,OkHttp坚持不懈:它将从常见的连接问题中无声地恢复。如果您的服务有多个IP地址,如果第一次连接失败,OkHttp将尝试备用地址。这对于IPv4 + IPv6和冗余数据中心中托管的服务是必需的。OkHttp支持现代TLS功能(TLS 1.3,ALPN,证书固定)。它可以配置为回退以实现广泛的连接。

使用OkHttp很容易。它的请求/响应API采用流畅的构建器和不变性设计。它支持同步阻塞调用和带回调的异步调用。

引用库

implementation 'com.squareup.okhttp3:okhttp:3.2.0'

权限

<!--网络权限-->
<uses-permission android:name="android.permission.INTERNET" />
<!--文件读写权限-->
<uses-permission android:name="android.permission.READ_EXTERNAL_STORAGE" />

Post请求调用

HashMap<String,String> mapx=new HashMap<String, String>();
mapx.put("yh","dongdong");
mapx.put("mm","xxxxxxx");
OKhttp.getOhttp().okpost("post.php", mapx, new OKhttp.Jkstr() {
@Override
public void jkstr(String str) {
Toast.makeText(MainActivity.this,str,Toast.LENGTH_SHORT).show();
//System.out.println(str);
}
});

Get请求调用

OKhttp.getOhttp().okget("post.php?dong=dongxiaodong&dong2=dongdongx", new OKhttp.Jkstr() {
@Override
public void jkstr(String str) {
Toast.makeText(MainActivity.this,str,Toast.LENGTH_SHORT).show();
//System.out.println(str);
}
});

网络访问类封装

package com.example.testdelete;
import android.os.Environment;
import android.os.Handler;
import java.io.File;
import java.io.IOException;
import java.util.Map;
import okhttp3.Call;
import okhttp3.Callback;
import okhttp3.FormBody;
import okhttp3.MediaType;
import okhttp3.MultipartBody;
import okhttp3.OkHttpClient;
import okhttp3.Request;
import okhttp3.RequestBody;
import okhttp3.Response;
/**
* Created by 东东 on 2018/3/29.
*/
public class OKhttp {
private OKhttp(){};
private static final OKhttp ohttp=new OKhttp();
public static OKhttp getOhttp(){
return ohttp;
}
private OkHttpClient client=new OkHttpClient();
private Handler handlerx=new Handler();
public static final String UR="http://193.110.8.6/testdelete/";
File sd= Environment.getExternalStorageDirectory();//得到SD卡的路径
//文件上传
//参数(上传的url,文件地址,文件名,回调函数)
public void okpostfile(String url,String path,String filenaem,final Jkstr callbackfile) {//get和post数据同时上传
File file = new File(sd,path);
RequestBody fileBody = RequestBody.create(MediaType.parse("application/octet-stream"), file);
RequestBody requestBody = new MultipartBody.Builder()
.setType(MultipartBody.FORM)
.addFormDataPart("mfile",filenaem, fileBody)//Post参数
.build();
Request request = new Request.Builder()
.url(UR+url)
.post(requestBody)
.build();
client.newCall(request).enqueue(new Callback() {
@Override
public void onFailure(Call call, IOException e) {//请求失败
ohttpstr("0",callbackfile);
}
@Override
public void onResponse(Call call, Response response) throws IOException {//请求成功
ohttpstr(response.body().string(),callbackfile);
}
});
}
//Get请求
//参数(url,回调函数)
public void okget(String url,final Jkstr callbakestr){
final Request res=new Request.Builder().url(UR+url).build();
client.newCall(res).enqueue(new Callback() {
@Override
public void onFailure(Call call, IOException e) {//请求失败
ohttpstr("0",callbakestr);
e.printStackTrace();
}
@Override
public void onResponse(Call call, Response response) throws IOException {//请求成功
if(response.isSuccessful()){
ohttpstr(response.body().string(),callbakestr);
}
}
});
}
//Post请求
//参数(url,Map集合,回调函数)
public void okpost(String ur, Map<String,String> mapx,final Jkstr callbackform){
FormBody.Builder formx=new FormBody.Builder();
if(mapx!=null&&!mapx.isEmpty()){
for(Map.Entry<String,String>xx:mapx.entrySet()){
formx.add(xx.getKey(),xx.getValue());
}
RequestBody resbody=formx.build();
Request req=new Request.Builder().url(UR+ur).post(resbody).build();
client.newCall(req).enqueue(new Callback() {//请求失败
@Override
public void onFailure(Call call, IOException e) {
ohttpstr("0",callbackform);
}

@Override
public void onResponse(Call call, Response response) throws IOException {//请求成功
if(response.isSuccessful()){
ohttpstr(response.body().string(),callbackform);
}
}
});
}
}
//请求返回为byte数组
private void ohttpbyt(final byte[] bytx,final Jkbyt callbackx){
handlerx.post(new Runnable() {
@Override
public void run() {
if(callbackx!=null){
try{
callbackx.jkbyt(bytx);
}catch (Exception e){
e.printStackTrace();
}
}
}
});
}
//处理返回为string类型数据
private void ohttpstr(final String strx, final Jkstr callback){
handlerx.post(new Runnable() {
@Override
public void run() {
if(callback!=null){
try{
callback.jkstr(strx.trim());
}catch (Exception e){
e.printStackTrace();
}
}
}
});
}
public interface Jkstr{ void jkstr(String str); }
public interface Jkbyt{void jkbyt(byte [] bytexx);}
}

参考:育知同创

内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: