【问题标题】:Download server images to android memory card将服务器图像下载到安卓内存卡
【发布时间】:2020-01-07 13:38:21
【问题描述】:

我正在做一个安卓应用程序。我需要获取服务器图像并将它们保存在 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;
    }
}

【问题讨论】:

    标签: android image download upload


    【解决方案1】:

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

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

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

    这就是为什么首先引入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 
        }
    });
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2011-10-14
      • 1970-01-01
      • 2017-02-08
      • 1970-01-01
      • 2017-01-27
      相关资源
      最近更新 更多