项目里想添加几个小功能,拍照、录像、录音。都是调用系统的多媒体,拍摄、录制完毕也不能不管,应该将他们都存储到手机上,方便日后查看、使用。但是开发过程并不是一蹴而就,也是查阅了很多资料,向大佬请教了很多,才成功实现了功能,并且由于是Android 7.0的系统,相比以前的版本对文件的管理更加复杂。下面直接进入正题。
一、准备
创建项目后,还需要做什么准备?不是一顿敲就完事了吗?为了适配7.0的系统,确实需要准备一下:
创建项目,MultiMediaTest,包名com.my.example.multimediatest,其它默认,打开主配置文件,在Application标签下,修改并加入以下代码:
<?xml version="1.0" encoding="utf-8"?>
<manifest xmlns:android="http://schemas.android.com/apk/res/android"
package="com.my.example.multimediatest">
<uses-permission android:name="android.permission.WRITE_EXTERNAL_STORAGE"/>
<application
android:allowBackup="true"
android:icon="@mipmap/ic_launcher"
android:label="@string/app_name"
android:roundIcon="@mipmap/ic_launcher_round"
android:supportsRtl="true"
android:theme="@style/AppTheme">
<provider
android:name="android.support.v4.content.FileProvider"
android:authorities="${applicationId}.provider"
android:exported="false"
android:grantUriPermissions="true">
<meta-data
android:name="android.support.FILE_PROVIDER_PATHS"
android:resource="@xml/provider_paths"/>
</provider>
<activity android:name=".MainActivity">
<intent-filter>
<action android:name="android.intent.action.MAIN" />
<category android:name="android.intent.category.LAUNCHER" />
</intent-filter>
</activity>
</application>
</manifest>
需要读写权限,另外的就是这段代码:
适配7.0的关键,这还不够,因为指定了的资源文件还没有创建,直接对着provider_paths按Alt+Enter,在res下创建资源文件,对创建好的文件作以下修改:
<?xml version="1.0" encoding="utf-8"?>
<paths xmlns:android="http://schemas.android.com/apk/res/android">
<!--"."表示所有路径-->
<external-path name="external_files" path="."/>
</paths>
Ok,准备完成。
二、开始编写
首先理清一下思路:
1、启动系统相机并保存文件涉及到读写权限,Android 6.0以上的系统都需要动态申请。启动相机前,检查权限,没有则申请,有则继续,拒绝权限则程序不能执行。
2、将文件存储到指定位置,需要在SD根目录下创建文件夹,把图片统一存进去。
3、因为我们不能在系统相机使用中的时候去读写文件,所以需要相机在拍摄后,返回一个结果,然后根据拍摄结果去执行读写操作。
4、即使存储了图片,系统图片库也是不会及时更新,所以还需要通知系统更新图库,让我们拍摄