Android 实现图片保存到本地并调用本地地址显示图片_第1张图片

话不多说上代码

public class MainActivity extends AppCompatActivity {private Button cunn;private Button xian; private ImageView ttt;//private EditText rrr;public static final int EXTERNAL_STORAGE_REQ_CODE = 10 ;@Overrideprotected void onCreate(Bundle savedInstanceState) {    super.onCreate(savedInstanceState);    setContentView(R.layout.activity_main);    cunn =(Button)findViewById(R.id.cun);    xian=(Button)findViewById(R.id.xians);    ttt=(ImageView)findViewById(R.id.tt);   // rrr=(EditText)findViewById(R.id.rr);    //final Intent intent = new Intent(MainActivity.this,Download.class);    final MyDownloadManager myDownloadManager = new MyDownloadManager();    //final String path= rrr.getText().toString();    final String path = "https://dss3.bdstatic.com/70cFv8Sh_Q1YnxGkpoWK1HF6hhy/it/u=2534506313,1688529724&fm=26&gp=0.jpg";    //final String path1 = "https://ss3.bdstatic.com/70cFv8Sh_Q1YnxGkpoWK1HF6hhy/it/u=1328477591,2018436166&fm=26&gp=0.jpg";    //final String dirname ="/sdcard/";    //final String filename ="rr";    //final Download download = new Download();   // final dd d =new dd();    cunn.setOnClickListener(new View.OnClickListener() {        @RequiresApi(api = Build.VERSION_CODES.O)        @Override        public void onClick(View view) {            myDownloadManager.addDownloadTask(path);           // try {           //    d.ddt(path1,dirname,filename);           // } catch (IOException e) {            //   e.printStackTrace();           // }        }    });    xian.setOnClickListener(new View.OnClickListener() {        @Override        public void onClick(View view) {          //File file = new File(String.valueOf(myDownloadManager.getDownloadDir()));            //Bitmap bm = BitmapFactory.decodeFile(myDownloadManager.getDownloadDir()+myDownloadManager.getfileName(path));           // ttt.setImageBitmap(bm);            ttt.setImageURI(Uri.fromFile(new File(myDownloadManager.getDownloadDir() +"/"+ myDownloadManager.getfileName(path))));            //ttt.setImageUri(Uri.fromFile(new File("/sdcard/test.jpg")));        }    });    int permission = ActivityCompat.checkSelfPermission(this,            Manifest.permission.WRITE_EXTERNAL_STORAGE);    if (permission != PackageManager.PERMISSION_GRANTED) {        // 请求权限        ActivityCompat.requestPermissions(this, new String[]{Manifest.permission.WRITE_EXTERNAL_STORAGE},                EXTERNAL_STORAGE_REQ_CODE);    }}public static String MD5(String path)  {   // URL url = new URL(path);    //String url = path;    //String path = Environment.getExternalStorageDirectory().getAbsolutePath();    //final long startTime = System.currentTimeMillis();    //String filename=url.substring(url.lastIndexOf("/") + 1);    String filename ="pp.jpg";    return filename;}

//

 public class MyDownloadManager {public static final int EXTERNAL_STORAGE_REQ_CODE = 10 ;private static final int REQUEST_EXTERNAL_STORAGE = 1;private static String[] PERMISSIONS_STORAGE = {        Manifest.permission.READ_EXTERNAL_STORAGE,        Manifest.permission.WRITE_EXTERNAL_STORAGE };/** * Checks if the app has permission to write to device storage * * If the app does not has permission then the user will be prompted to * grant permissions * * @param activity */public static void verifyStoragePermissions(Activity activity) {    // Check if we have write permission    int permission = ActivityCompat.checkSelfPermission(activity,            Manifest.permission.WRITE_EXTERNAL_STORAGE);    if (permission != PackageManager.PERMISSION_GRANTED) {        // We don't have permission so prompt the user        ActivityCompat.requestPermissions(activity, PERMISSIONS_STORAGE,                REQUEST_EXTERNAL_STORAGE);    }}private static final String TAG = "MyDownloadManager";private File downloadDir; // 文件保存路径private static MyDownloadManager instance; // 单例private String fileName;// 单线程任务队列public static Executor executor;private static final ThreadFactory sThreadFactory = new ThreadFactory() {    private final AtomicInteger mCount = new AtomicInteger(1);    public Thread newThread(Runnable r) {        return new Thread(r, "MyDownloadManager #" + mCount.getAndIncrement());    }};private static final BlockingQueue sPoolWorkQueue = new LinkedBlockingQueue<>(128);public static final Executor THREAD_POOL_EXECUTOR = new ThreadPoolExecutor(1, 1, 1,        TimeUnit.SECONDS, sPoolWorkQueue, sThreadFactory);public MyDownloadManager() {    // 初始化下载路径    downloadDir = new File("/sdcard/");    if (!downloadDir.exists()) {        downloadDir.mkdirs();    }    executor = new SerialExecutor();}/** * 顺序执行下载任务 */private static class SerialExecutor implements Executor {    final ArrayDeque mTasks = new ArrayDeque();    Runnable mActive;    public synchronized void execute(final Runnable r) {        mTasks.offer(new Runnable() {            public void run() {                try {                    r.run();                } finally {                    scheduleNext();                }            }        });        if (mActive == null) {            scheduleNext();        }    }    protected synchronized void scheduleNext() {        if ((mActive = mTasks.poll()) != null) {            THREAD_POOL_EXECUTOR.execute(mActive);        }    }}/** * 获取单例对象 * * @return */public static MyDownloadManager getInstance() {    if (instance == null) {        instance = new MyDownloadManager();    }    return instance;}/** * 添加下载任务 * * @param path */public void addDownloadTask(final String path) {    Log.i(TAG, "进入run00");    executor.execute(new Runnable() {        @Override        public void run() {            Log.i(TAG, "进入run");            download(path);        }    });}/** * 下载文件 * * @param path */private void download(String path)  {    String fileName = MainActivity.MD5(path);    File savePath = new File(downloadDir, fileName); // 下载文件路径   //File finallyPath = new File(downloadDir, fileName + ".png"); // 下载完成后加入    if (savePath.exists()) { // 文件存在则已下载        Log.i(TAG, "file is existed");        return;    }   // 如果是Wifi则开始下载    if (savePath.exists() && savePath.delete()) { // 如果之前存在文件,证明没有下载完成,删掉重新创建            savePath = new File(downloadDir, fileName);            Log.i(TAG, "download 111111");        }        Log.i(TAG, "download start");        try {            byte[] bs = new byte[1024];            int len;            URL url = new URL(path);            InputStream is = url.openStream();            OutputStream os = new FileOutputStream(savePath,true);            Log.i(TAG, "download 22222");            while ((len = is.read(bs)) != -1) {                os.write(bs, 0, len);            }            is.close();            os.close();        } catch (IOException e) {            e.printStackTrace();        }       //if (savePath.renameTo(finallyPath)) { // 下载完成后重命名为          // Log.i(TAG, "download end");     //  }}/** * 添加删除任务 * * @param path */public void addDeleteTask(final String path) {    executor.execute(new Runnable() {        @Override        public void run() {            delete(path);        }    });}/** * 删除本地文件 * * @param path */private void delete(String path) {    String fileName = MainActivity.MD5(path);    File savePath = new File(downloadDir, fileName + ".png");    Log.i(TAG, savePath.getPath());    if (savePath.exists()) {        if (savePath.delete()) {            Log.i(TAG, "file is deleted");        }    }}/** * 返回下载路径 * * @return */public File getDownloadDir() {    return downloadDir;}public String getfileName(String path){    String f =MainActivity.MD5(path);    return f;}}

//

   <?xml version="1.0" encoding="utf-8"?>         

//

 <?xml version="1.0" encoding="utf-8"?>                                                  

代码中我有很多尝试的地方 注释的地方可以忽略 或者可以参考

更多相关文章

  1. Android设置拍照或者上传本地图片
  2. Android通过HttpURLConnection上传多个文件至服务器 - 流传输
  3. Android写文件到SDCard的一般过程和代码
  4. Android 获取本地音乐文件
  5. Android播放在线音乐文件
  6. 文件读写
  7. Android读取Txt文件

随机推荐

  1. Android之TextView------文字底部或者中
  2. 使用意图在Activity之间传递数据小插曲__
  3. Android文件图片上传的详细讲解(四)---服务
  4. Android 6.0 动态权限申请实例
  5. Caused by: java.lang.NoSuchMethodExcep
  6. Android点击事件隐藏软键盘
  7. Android Studio:常见使用问题处理
  8. MediaScanner与音乐信息扫描==
  9. 打开app弹出欢迎界面,然后自动跳转到主界
  10. 清除手机图案解锁(执行adb命令工具类)