Android调用摄像头后系统回收activity造成数据丢失

来源:互联网 发布:php 压缩图片 编辑:程序博客网 时间:2024/06/06 07:09

在做聊天模块时,有发送拍照的功能,奇葩的是别的手机都没问题,唯独红米note调用摄像头后返回页面没有任何响应,调试中发现返回的图片路径为空,返回的路径怎么能为空呢?后来发现是系统把activity回收掉了,返回来的时候,activity重新加载了,所有返回的图片路径已经不存在了,所以只能想办法恢复图片路径的数据,如下代码是开启摄像头和返回的信息:

<span style="white-space:pre"></span>Intent intent = new Intent(MediaStore.ACTION_IMAGE_CAPTURE);                            // 指定调用相机拍照后照片的储存路径                            intent.putExtra(MediaStore.EXTRA_OUTPUT, Uri.fromFile(getCacheFile                                                                                          (mImageName)));                            startActivityForResult(intent, PHOTO_REQUEST_TAKE_PHOTO);
<span style="white-space:pre"></span>if (requestCode == REQUEST_CODE_CAMERA) { // 发送照片                if (cameraFile != null && cameraFile.exists()) {                    sendPicture(cameraFile.getAbsolutePath());                }            }

根据上面的分析,我们自然会想怎么让系统恢复我们原来的图片路径,在activity的生命周期中有两个相关的方法,即:onSaveInstanceState(Bundle outState)和onRestoreInstanceState(Bundle savedInstanceState),在这连个方法中我们可以在系统把activity回收时把相关的数据保存到Bundle里,在重新创建activity时我们就可以从Bundle中拿到我们保存的数据,同时onRestoreInstanceState(Bundle savedInstanceState)会把获取到的Bundle传到onCreate(Bundle savedInstanceState)中,所以我们可以不复写onRestoreInstanceState(Bundle savedInstanceState)方法,直接在onCreate中获取我们保存的值就可,下面是我的代码:

@Override    protected void onCreate(Bundle savedInstanceState) {        if (null != savedInstanceState) {            cameraFile = (File) savedInstanceState.getSerializable("FilePath");            mChatType = savedInstanceState.getInt("ChatType");            mToChatHXId = savedInstanceState.getLong("HXId");        }        super.onCreate(savedInstanceState);        setDisplayHomeAsUpEnable(true);        initView();        initData();        initClick();    }    @Override    protected void onSaveInstanceState(Bundle outState) {        outState.putSerializable("FilePath", cameraFile);        outState.putInt("ChatType", mChatType);        outState.putLong("HXId", mToChatHXId);        super.onSaveInstanceState(outState);    }
这样便可保证我们的数据不丢失成功获取拍到的照片!




0 0