Android Studio - 通过图库选择图片时出现长时间延迟

时间:2016-02-18 14:09:12

标签: android android-studio

Android Studio的新功能,只是想知道当我发送从图库中拍摄的图像时是否有人可以帮助解决此延迟问题。一旦选择了图像,在实际发送之前会有很长的延迟,并且屏幕也会变黑。

这是代码 - 谢谢

public boolean onOptionsItemSelected(MenuItem item) {
    if (item.getItemId() == R.id.launch_voip_call) {
        Utils.startCall(this, contact);
        return true;
    } else if (item.getItemId() == R.id.launch_camera) {
        AlertDialog.Builder builder = new AlertDialog.Builder(this);
        builder.setMessage("Pick Image from")
                .setCancelable(false)
                .setPositiveButton("Camera", new DialogInterface.OnClickListener() {
                    public void onClick(DialogInterface dialog, int id) {
                        //camera intent
                        Intent cameraIntent = new Intent(ConversationActivity.this, CameraActivity.class);
                        cameraIntent.putExtra("EXTRA_CONTACT_JID", contact.getJid());
                        startActivity(cameraIntent);
                    }
                })
                .setNegativeButton("Gallery", new DialogInterface.OnClickListener() {
                    public void onClick(DialogInterface dialog, int id) {
                        Intent intent = new Intent();
                        // Show only images, no videos or anything else
                        intent.setType("image/*");
                        intent.setAction(Intent.ACTION_GET_CONTENT);
                        // Always show the chooser (if there are multiple options available)
                        startActivityForResult(Intent.createChooser(intent, "Select Picture"), PICK_IMAGE_REQUEST);

                    }
                });
        AlertDialog alert = builder.create();
        alert.show();


    }
    return false;
}
@Override
protected void onActivityResult(int requestCode, int resultCode, Intent data) {
    super.onActivityResult(requestCode, resultCode, data);

    if (requestCode == PICK_IMAGE_REQUEST && resultCode == RESULT_OK && data != null && data.getData() != null) {

        Uri uri = data.getData();

        try {
            Bitmap bitmap = MediaStore.Images.Media.getBitmap(getContentResolver(), uri);
            ByteArrayOutputStream stream = new ByteArrayOutputStream();
            bitmap.compress(Bitmap.CompressFormat.WEBP, 5, stream);
            byte[] byteArray = stream.toByteArray();
            // Log.d(TAG, String.valueOf(bitmap));
            EventBus.getDefault().post(new MessageEvent.SendMessage(contact.getJid(), byteArray, ""));
        } catch (IOException e) {
            e.printStackTrace();
        }
    }
}

@OnTextChanged(R.id.compose)
public void onMessageChanged(CharSequence s) {
    sendButton.setVisibility(s.length() > 0 ? View.VISIBLE : View.INVISIBLE);
}

@OnClick(R.id.send)
public void onSend(final View view) {
    String message = composeText.getText().toString().trim();
    if (!message.isEmpty()) {
        if (!amIOffline()) {
            EventBus.getDefault().post(new MessageEvent.SendMessage(contact.getJid(), message));
            composeText.setText("");
        } else {
            SimpleSnackbar.offlineGroupChat(view).show();
        }
    }
}

2 个答案:

答案 0 :(得分:0)

On Activity结果在主线程上..压缩图像需要时间..尝试使用AsyncTask在后台实现压缩,然后在后台发送图像..不要在MainThread上执行压缩这就是为什么你得到长时间的延迟..

如果您需要代码,请告诉我?

 public class ImageSendingAsync extends AsyncTask<Bitmap,Void,Void> {
    @Override
    protected Void doInBackground(Bitmap... params) {
        try {
            Bitmap bitmap = params[0];
            ByteArrayOutputStream stream = new ByteArrayOutputStream();
            bitmap.compress(Bitmap.CompressFormat.WEBP, 5, stream);
            byte[] byteArray = stream.toByteArray();
            // Log.d(TAG, String.valueOf(bitmap));
            EventBus.getDefault().post(new MessageEvent.SendMessage(contact.getJid(), byteArray, ""));
        } catch (IOException e) {
            e.printStackTrace();
        }
        return null;
    }
}


//This will go in Activity Result
    if (requestCode == PICK_IMAGE_REQUEST && resultCode == RESULT_OK && data != null && data.getData() != null) {

            Uri uri = data.getData();
               Bitmap bitmap = MediaStore.Images.Media.getBitmap(getContentResolver(), uri);
         new ImageSendingAsync().execute(bitmap);
        }

答案 1 :(得分:0)

我认为压缩需要一段时间,这就是为什么你的MainThread无法绘制布局 - &gt;黑屏。

可能会测试压缩pic所需的时间。

如果时间很长,请使用ASyncTask。

[...]
long timeStart = System.currentTimeMillis();
bitmap.compress(Bitmap.CompressFormat.WEBP, 5, stream);
long timeEnd = System.currentTimeMillis();
Log.e("resizePicture Timer", "resize took " + (timeEnd - timeStart) + "ms");
[...]