Android

Android 通知相册更新保存的资源

2020-11-11  本文已影响0人  码农修行之路

        项目中需求,应用开通的云存储过期,导致用户之前的报警消息不可预览查看,因此,需求把应用中设备产生的报警图片和视频保存到相册,那么问题来了,用网上的一些方案扫描或者广播方式通知更新相册,对于一些手机(三星、华为mate8等部分8.0系统手机)结果就是失败,看下面一个例子

广播更新:

public void refreshAlbum(String fileAbsolutePath) {

    File imgFile = new File(fileAbsolutePath);

    Uri uri = Uri.fromFile(imgFile);

    Intent mediaScanIntent = new Intent(Intent.ACTION_MEDIA_SCANNER_SCAN_FILE);

    mediaScanIntent.setData(uri);

    mContext.sendBroadcast(mediaScanIntent);

}

不建议使用,会通知图库整个进行更新

扫描更新:

public void refreshAlbum(String fileAbsolutePath) {

    MediaScannerConnection mMediaScanner = new MediaScannerConnection(this, null);

    mMediaScanner.connect();

    if (mMediaScanner.isConnected()) {         

        mMediaScanner.scanFile(fileAbsolutePath, Constants.VIDEO_MIME_TYPE_MP4);

    } else {

        Elog.i(TAG, " 连接失败 ")

    }

}

上面的例子,极有可能会走“连接失败”,因为connect()执行需要时间,不可能立刻就会连接成功,所以扫描不了,也无法刷新,怎么解决呢!需要下面的优化,通过MediaScannerConnectionClient回调监听,确定MediaScannerConnection已经连接上,再进行扫描更新

public void refreshAlbum(String fileAbsolutePath, boolean isVideo) {

        mMediaScanner = new MediaScannerConnection(mContext, new MediaScannerConnection.MediaScannerConnectionClient() {

                @Override

                public void onMediaScannerConnected() {

                        if (mMediaScanner.isConnected()) {

                                Elog.i(TAG, " 连接成功 ")

                                if (isVideo) {

                                        mMediaScanner.scanFile(fileAbsolutePath, "video/mp4");

                                } else {

                                        mMediaScanner.scanFile(fileAbsolutePath, "image/jpeg");

                                }

                        } else {

                                ELog.e(TAG, " refreshAlbum() 无法更新图库,未连接,广播通知更新图库,异常情况下 ");

                        }

                }

                @Override

                public void onScanCompleted(String path, Uri uri) {

                        ELog.i(TAG, " 扫描完成 path: ", path, " uri: ", uri);

                }

        });

        mMediaScanner.connect();

}

使用上面的优化方案就可以很完美的解决保存相册中的数据资源(图片、视频)不显示的问题。

上一篇 下一篇

猜你喜欢

热点阅读