How to send large byte arrays between activities in Android?

后端 未结 3 1193
我在风中等你
我在风中等你 2020-12-11 03:36

I need to send byte[] data from Activity1 to Activity2, in order to writedata(\"FileOutputStream.write(data)\") in a jpg

3条回答
  •  情话喂你
    2020-12-11 04:13

    I had the same problem. In short: subclass the Application (or create a helper singleton), use it ( in manifest.xml) and store the image data there.

    App.java snippet:

    public final class App extends Application {
        private static App sInstance;
        private byte[] mCapturedPhotoData;
    
        // Getters & Setters
        public byte[] getCapturedPhotoData() {
            return mCapturedPhotoData;
        }
    
        public void setCapturedPhotoData(byte[] capturedPhotoData) {
            mCapturedPhotoData = capturedPhotoData;
        }
    
        // Singleton code
        public static App getInstance() { return sInstance; }
    
        @Override
        public void onCreate() {
            super.onCreate();
            sInstance = this;
        }
    }
    

    Camera Activity saves the data:

    private Camera.PictureCallback mJpegCaptureCallback = new Camera.PictureCallback() {
        @Override
        public void onPictureTaken(byte[] data, Camera camera) {
            // We cannot pass the large buffer via intent's data. Use App instance.
            App.getInstance().setCapturedPhotoData(data);
            setResult(RESULT_OK, new Intent());
            finish();
        }
    };
    

    Parent Activity reads the data:

    @Override
    public void onActivityResult(int requestCode, int resultCode, Intent data) {
        super.onActivityResult(requestCode, resultCode, data);
    
        if (requestCode == RequestCode.CAPTURE && resultCode == RESULT_OK) {
            // Read the jpeg data
            byte[] jpegData = App.getInstance().getCapturedPhotoData();
            App.log("" + jpegData.length);
    
            // Do stuff
    
            // Don't forget to release it
            App.getInstance().setCapturedPhotoData(null);
        }
    }
    

提交回复
热议问题