将服务器图像下载到 android 存储卡

Download server images to android memory card

我正在做 android 申请。我需要获取服务器图像并将它们保存在 android 存储卡上的一个文件夹中,但它不起作用。并且不要给出任何错误。谁能帮我? 有谁知道我如何在服务器上一张一张地浏览图像文件夹以将图像保存在存储卡文件夹中。 谢谢

Here is my code:

//link to access server images http://IP:8080/teste/imagens/

public class MainActivity extends AppCompatActivity {

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);

    new GetImages(Resources.getSystem().getString(R.string.link), "1.jpg").execute();

    }
}


public class GetImages extends AsyncTask<Object, Object, Object> {

    private String requestUrl, imagename_;
    private Bitmap bitmap ;
    private FileOutputStream fos;

    protected GetImages(String requestUrl, String _imagename_) {
        this.requestUrl = requestUrl;
        this.imagename_ = _imagename_ ;
    }

    @Override
    protected Object doInBackground(Object... objects) {
        try {
            URL url = new URL(requestUrl);
            URLConnection conn = url.openConnection();
            bitmap = BitmapFactory.decodeStream(conn.getInputStream());
        } catch (Exception ex) {
        }
        return null;
    }

    @Override
    protected void onPostExecute(Object o) {
        if(!ImageStorage.checkifImageExists(imagename_))
        {

            ImageStorage.saveToSdCard(bitmap, imagename_);
        }
    }
}


public class ImageStorage {
    public static String saveToSdCard(Bitmap bitmap, String filename) {
        String stored = null;
        File sdcard = Environment.getExternalStorageDirectory();
        File folder = new File(sdcard.getAbsoluteFile(), "/imagens");
        folder.mkdir();
        File file = new File(folder.getAbsoluteFile(), filename + ".jpg");
        if (file.exists())
            return stored;
        try {
            FileOutputStream out = new FileOutputStream(file);
            bitmap.compress(Bitmap.CompressFormat.JPEG, 90, out);
            out.flush();
            out.close();
            stored = "success";
        } catch (Exception e) {
            e.printStackTrace();
        }
        return stored;
    }

    public static File getImage(String imagename) {
        File mediaImage = null;
        try {
            String root = Environment.getExternalStorageDirectory().toString();
            File myDir = new File(root);
            if (!myDir.exists())
                return null;
            mediaImage = new File(myDir.getPath() + "/imagens/" + imagename);
        } catch (Exception e) {
            e.printStackTrace();
        }
        return mediaImage;
    }

    public static boolean checkifImageExists(String imagename) {
        Bitmap b = null;
        File file = ImageStorage.getImage("/" + imagename + ".jpg");
        String path = file.getAbsolutePath();
        if (path != null)
            b = BitmapFactory.decodeFile(path);
        if (b == null || b.equals("")) {
            return false;
        }
        return true;
    }
}

首先避免使用AsyncTask进行网络调用。 AsyncTask 存在漏洞,可能会影响应用的性能和稳定性。

最著名的情况之一是发生屏幕旋转并启动 AsyncTask。 考虑到 AsyncTask 是一个内部 class,如果发生旋转,它会保持对父 class 的引用 Activity 将是 re-created 但你的 AsyncTask 仍然保留对第一个创建的 Activity 的引用并且不允许它是 garbage collected

这导致了称为 zombie 的场景。如果结果返回到不再存在的 Acitivity,则可能导致 leakscrashesAsyncTask 应用于内部操作,例如从 phone 获取联系人或在后台执行类似任务。

这就是为什么首先引入 RetrofitVolley 但在这种情况下 OkHttp 是更好的选择所以:

使用OkHttp下载图片:

implementation("com.squareup.okhttp3:okhttp:4.1.0")

 OkHttpClient client = new OkHttpClient();
 Request request = new Request.Builder()
        .url("put your url of image here")
        .build();

client.newCall(request).enqueue(new Callback() {
    @Override
    public void onFailure(Request request, IOException e) {
        Log.d("Failed: " + e.getMessage());
    }

    @Override
    public void onResponse(Response response) throws IOException {
         InputStream inputStream = response.body().byteStream(); // convert to inputstream
         Bitmap bitmap = BitmapFactory.decodeStream(inputStream); // get bitmap from inputstream 
    }
});