1

我正在创建一个仅自动返回随机图像的假相机/图库应用程序。我将它绑定到 ACTION_PICK 和 IMAGE_CAPTURE 意图过滤器。

但是对于图库(PICK)代码,在调用完成后,它似乎没有返回到调用应用程序。

这是我的代码:

public class MainActivity extends Activity {

final static int[] photos = { R.drawable.android_1, R.drawable.android_2,
        R.drawable.android_3 };
static int lastPhotoIndex = -1;

private final static String TAG = "FakeCameraGallery";

@Override
protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);

    String action = getIntent().getAction();

    if (action.contains("PICK")) {

                    //Act as Gallery

        InputStream in = getResources().openRawResource(getNextPhoto());
        Bitmap bm = BitmapFactory.decodeStream(in);

        Bundle extras = new Bundle();
        extras.putParcelable("data", bm);

        Intent result = getIntent().putExtras(extras);

        if (getParent() == null) {
            setResult(Activity.RESULT_OK, result);
        } else {
            getParent().setResult(Activity.RESULT_OK, result);
        }

    } else {
                    //act as Camera
        prepareToSnapPicture();
    }

    finish();
}

private void prepareToSnapPicture() {
    checkSdCard();
    Intent intent = getIntent();

    if (intent.getExtras() != null) {
        snapPicture(intent);
        setResult(RESULT_OK);
    } else {
        Log.i(TAG, "Unable to capture photo. Missing Intent Extras.");
        setResult(RESULT_CANCELED);
    }
}

private void checkSdCard() {
    if (!Environment.MEDIA_MOUNTED.equals(Environment
            .getExternalStorageState())) {
        Toast.makeText(this, "External SD card not mounted",
                Toast.LENGTH_LONG).show();
        Log.i(TAG, "External SD card not mounted");
    }
}

private void snapPicture(Intent intent) {
    try {
        this.copyFile(getPicturePath(intent));
        Toast.makeText(this, "Click!", Toast.LENGTH_SHORT).show();
    } catch (IOException e) {
        Log.i(TAG, "Can't copy photo");
        e.printStackTrace();
    }
}

private File getPicturePath(Intent intent) {
    Uri uri = (Uri) intent.getExtras().get(MediaStore.EXTRA_OUTPUT);
    return new File(uri.getPath());
}

private void copyFile(File destination) throws IOException {
    InputStream in = getResources().openRawResource(getNextPhoto());
    OutputStream out = new FileOutputStream(destination);
    byte[] buffer = new byte[1024];
    int length;

    if (in != null) {
        Log.i(TAG, "Input photo stream is null");

        while ((length = in.read(buffer)) > 0) {
            out.write(buffer, 0, length);
        }

        in.close();
    }

    out.close();
}

private int getNextPhoto() {
    if (lastPhotoIndex == photos.length - 1) {
        lastPhotoIndex = -1;
    }

    return photos[++lastPhotoIndex];
}
}
4

1 回答 1

0

您的代码看起来不错:您是在使用它来调用它startActivityForResult吗?

于 2013-05-07T00:05:15.993 回答