Android:将文件上传到服务器时性能提升

时间:2016-02-14 21:31:12

标签: java android intentservice

我需要将对象上传到服务器,并在其中一个字段中显示照片。发送对象后,我需要在地图上显示它。如果用户输入对象,他需要在里面看到上传的照片。我遇到了照片发送性能不佳的问题 - 因此用户需要等待很长时间才能转移照片。我有两种方式:

1)直截了当的方法。我尝试使用Base64编码,然后通过Volley库发送文件。速度是不允许的 - 因此用户需要等待最多4秒,同时文件解码为字符串并发送到服务器。

2)我采用了Service方法。因此创建了IntentService上传所需文件的地方:

    public class FileUploaderService extends IntentService{

    private static final String TAG = "FileUploaderService";

    /**
     * Creates an IntentService.  Invoked by your subclass's constructor.
     *
     * @param name Used to name the worker thread, important only for debugging.
     */
    public FileUploaderService(String name) {
        super(name);
    }
    public FileUploaderService() {
        super(TAG);
    }

    @Override
    protected void onHandleIntent(Intent intent) {
        if (intent!=null){
            int id = intent.getIntExtra(Constants.BUNDLE_POST_UPLOAD_ID,0);
            if (id!=0){
                String url = "...";
                File image = new File(String.valueOf(intent.getStringExtra(Constants.BUNDLE_POST_UPLOAD_FILE)));
                BitmapFactory.Options bmOptions = new BitmapFactory.Options();
                Bitmap bitmap = BitmapFactory.decodeFile(image.getAbsolutePath(),bmOptions);
                Map<String,String> params = new HashMap<>();
                params.put("image", Utils.convertBitmapToString(bitmap));
                Utils.sendVolleyRequestWithoutDialog(this, Request.Method.PUT, url, params, new VolleyCallback() {
                    @Override
                    public void onSuccess(String stringObject) {

                    }
                    @Override
                    public void onErrorResponse(String error) {
                        Toast.makeText(FileUploaderService.this, error, Toast.LENGTH_SHORT).show();
                    }
                });
            }
        }
    }
}

这解决了性能问题,但导致问题,就是当用户输入对象时,内部暂时没有照片。

所以我需要找到允许以轻微的方式传输照片的解决方案。

1 个答案:

答案 0 :(得分:0)

此问题与上传无关。它是关于缓存如何工作的全部内容。您只需要一些缓存层,在加载对象的照片时将使用该缓存层。当您要上传照片时,您只需手动将其放入缓存中。