-
在App A中创建一个文件abc.txt,并写入 测试文本
private fun saveText() { var fos = FileOutputStream(filesDir.path+"/abc.txt") var text = "cc" fos.write(text.toByteArray()) fos.flush() fos.close() }
上面代码文件存储在/data/user/0/com.example.myapplication/files下,根据需要可自行修改
-
自定义一个ContentProvider,并重写openFile方法,注意和openAssetFile方法区分,二者可根据需要选择
class ContentProviderDemo : ContentProvider() { override fun openFile(uri: Uri, mode: String): ParcelFileDescriptor? { var path = context?.filesDir?.path var file = File(path, uri.path?.substring(1)) return ParcelFileDescriptor.open(file, ParcelFileDescriptor.MODE_READ_ONLY) } override fun onCreate(): Boolean { return false } override fun query( uri: Uri, projection: Array<out String>?, selection: String?, selectionArgs: Array<out String>?, sortOrder: String? ): Cursor? { return null } override fun getType(uri: Uri): String? { return null } override fun insert(uri: Uri, values: ContentValues?): Uri? { return null } override fun delete(uri: Uri, selection: String?, selectionArgs: Array<out String>?): Int { return 0 } override fun update( uri: Uri, values: ContentValues?, selection: String?, selectionArgs: Array<out String>? ): Int { return 0 } }
-
在AndroidManifest.xml文件中注册我们写的ContentProvider
<!--自定义provider 权限申请--> <permission android:name="com.hxq.provider.READ" android:label="provider pomission" android:protectionLevel="normal" /> <permission android:name="com.hxq.provider." android:label="provider pomission" android:protectionLevel="normal" /> <!--自定义provider 权限申请--> <application ------------- <provider android:name=".provider.ContentProviderDemo" android:authorities="testProviderDemo" android:exported="true" android:permission="com.hxq.provider" android:readPermission="com.hxq.provider.READ" android:writePermission="com.hxq.provider.WRITE" /> </application>
注意:
android:authorities="testProviderDemo" //用于唯一标识这个 ContentProvider ,外部调用者可以根据这个标识找到它
android:exported="true" //这个属性用于指示该服务是否能被其他程序应用组件调用或跟他交互
android:permission="com.hxq.provider"
android:readPermission="com.hxq.provider.READ"
android:writePermission="com.hxq.provider.WRITE"
后面是访问权限,这里读写都写上了,另外还要申请一下自定义的权限,在使用中发现只写 android:permission="com.hxq.provider"是不管用的,单独写readPermission或者writePermission是可以的,当然配合写也是可以的 -
这样就可以在App B中访问上面的文件,
首先申请权限<uses-permission android:name="com.hxq.provider.READ" />
然后直接访问
var uri= Uri.parse("content://testProviderDemo/abc.txt") Log.i("MainActivity", "onCreate: " + uri.path) var inputStream= contentResolver.openInputStream(uri) var buffer= BufferedReader(InputStreamReader(inputStream)) var line =buffer.readLine() while (line != null) { Log.i("MainActivity", "line: " +line) line=buffer.readLine() } buffer.close()
打印出日志:
com.example.myapplication1 I/MainActivity: onCreate: /abc.txt com.example.myapplication1 I/MainActivity: line: cc
完!
05-08
1283
04-01
2300