zoukankan      html  css  js  c++  java
  • 安卓图片显示与网络访问

    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);

    封装函数

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

    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);
        }
    });

    网络访问类封装

      1 package com.example.testdelete;
      2 import android.os.Environment;
      3 import android.os.Handler;
      4 import java.io.File;
      5 import java.io.IOException;
      6 import java.util.Map;
      7 import okhttp3.Call;
      8 import okhttp3.Callback;
      9 import okhttp3.FormBody;
     10 import okhttp3.MediaType;
     11 import okhttp3.MultipartBody;
     12 import okhttp3.OkHttpClient;
     13 import okhttp3.Request;
     14 import okhttp3.RequestBody;
     15 import okhttp3.Response;
     16 /**
     17  * Created by 东东 on 2018/3/29.
     18  */
     19 public class OKhttp {
     20     private OKhttp(){};
     21     private static final OKhttp ohttp=new OKhttp();
     22     public static OKhttp getOhttp(){
     23         return ohttp;
     24     }
     25     private OkHttpClient client=new OkHttpClient();
     26     private Handler handlerx=new Handler();
     27     public static final String UR="http://193.110.8.6/testdelete/";
     28     File sd= Environment.getExternalStorageDirectory();//得到SD卡的路径
     29     //文件上传
     30     //参数(上传的url,文件地址,文件名,回调函数)
     31     public void okpostfile(String url,String path,String filenaem,final Jkstr callbackfile) {//get和post数据同时上传
     32         File file = new File(sd,path);
     33         RequestBody fileBody = RequestBody.create(MediaType.parse("application/octet-stream"), file);
     34         RequestBody requestBody = new MultipartBody.Builder()
     35                 .setType(MultipartBody.FORM)
     36                 .addFormDataPart("mfile",filenaem, fileBody)//Post参数
     37                 .build();
     38         Request request = new Request.Builder()
     39                 .url(UR+url)
     40                 .post(requestBody)
     41                 .build();
     42         client.newCall(request).enqueue(new Callback() {
     43             @Override
     44             public void onFailure(Call call, IOException e) {//请求失败
     45                 ohttpstr("0",callbackfile);
     46             }
     47             @Override
     48             public void onResponse(Call call, Response response) throws IOException {//请求成功
     49                 ohttpstr(response.body().string(),callbackfile);
     50             }
     51         });
     52     }
     53     //Get请求
     54     //参数(url,回调函数)
     55     public void okget(String url,final Jkstr callbakestr){
     56         final Request res=new Request.Builder().url(UR+url).build();
     57         client.newCall(res).enqueue(new Callback() {
     58             @Override
     59             public void onFailure(Call call, IOException e) {//请求失败
     60                 ohttpstr("0",callbakestr);
     61                 e.printStackTrace();
     62             }
     63             @Override
     64             public void onResponse(Call call, Response response) throws IOException {//请求成功
     65                if(response.isSuccessful()){
     66                    ohttpstr(response.body().string(),callbakestr);
     67                }
     68             }
     69         });
     70     }
     71     //Post请求
     72     //参数(url,Map集合,回调函数)
     73     public void okpost(String ur, Map<String,String> mapx,final Jkstr callbackform){
     74         FormBody.Builder formx=new FormBody.Builder();
     75         if(mapx!=null&&!mapx.isEmpty()){
     76             for(Map.Entry<String,String>xx:mapx.entrySet()){
     77                 formx.add(xx.getKey(),xx.getValue());
     78             }
     79             RequestBody resbody=formx.build();
     80             Request req=new Request.Builder().url(UR+ur).post(resbody).build();
     81             client.newCall(req).enqueue(new Callback() {//请求失败
     82                 @Override
     83                 public void onFailure(Call call, IOException e) {
     84                     ohttpstr("0",callbackform);
     85                 }
     86 
     87                 @Override
     88                 public void onResponse(Call call, Response response) throws IOException {//请求成功
     89                   if(response.isSuccessful()){
     90                       ohttpstr(response.body().string(),callbackform);
     91                   }
     92                 }
     93             });
     94         }
     95     }
     96     //请求返回为byte数组
     97     private void ohttpbyt(final byte[] bytx,final Jkbyt callbackx){
     98         handlerx.post(new Runnable() {
     99             @Override
    100             public void run() {
    101                 if(callbackx!=null){
    102                     try{
    103                      callbackx.jkbyt(bytx);
    104                     }catch (Exception e){
    105                      e.printStackTrace();
    106                     }
    107                 }
    108             }
    109         });
    110     }
    111     //处理返回为string类型数据
    112     private void ohttpstr(final String strx, final Jkstr callback){
    113         handlerx.post(new Runnable() {
    114             @Override
    115             public void run() {
    116                 if(callback!=null){
    117                     try{
    118                         callback.jkstr(strx.trim());
    119                     }catch (Exception e){
    120                         e.printStackTrace();
    121                     }
    122                 }
    123             }
    124         });
    125     }
    126     public interface Jkstr{ void jkstr(String str); }
    127     public interface Jkbyt{void jkbyt(byte [] bytexx);}
    128 }

    参考:育知同创

  • 相关阅读:
    在 Ubuntu 14.04 Chrome中安装Flash Player(转)
    Tomcat 域名绑定多个Host配置要点
    IIS7.5 与 Tomcat 8整合
    笔记本外接显示器闪屏
    NetworkManager 命令配置nmcli注意
    CentOS 7 目录布局变化
    CentOS 7 Crontab
    jquery的ajax post 方法传值到后台,无法通过HttpServletRequest得到
    没有添加spring mvc 默认依赖包产生的错误
    tcp总结
  • 原文地址:https://www.cnblogs.com/dongxiaodong/p/11314240.html
Copyright © 2011-2022 走看看