使用场景
调用手机自带的文件管理 选择文件
/*
* @Author: Park
* @QQ:7323650
* @Date: 2021-08-09
* @content: 调用Android原生API选择文件并返回路径
*/
"ui";
ui.layout(
<vertical>
<button text="选择文件" id="选择" />
</vertical>
)
ui.选择.on("click", function () {
var fileType = "text/plain" //选择txt文件 文件类型参考:https://www.w3school.com.cn/media/media_mimeref.asp
var intent = new Intent();
intent.setType(fileType);
intent.setAction(Intent.ACTION_GET_CONTENT);
activity.startActivityForResult(intent, 5);
})
//监听选择文件回调
activity.getEventEmitter().on("activity_result", (requestCode, resultCode, data) => {
if (resultCode != -1) {
toastLog("没有选择文件!");
文件路径 = ""
return false;
} else {
var uri = data.getData();
// log("uri: %s", uri.toString());
let filepath = URIUtils_uriToFile(uri);
文件路径 = filepath
toastLog(文件路径);
}
});
//获取选择的文件路径 >> uri转文件路径
function URIUtils_uriToFile (uri) {
//Source : https://www.cnblogs.com/panhouye/archive/2017/04/23/6751710.html
var r = null,
cursor,
column_index,
selection = null,
selectionArgs = null,
isKitKat = android.os.Build.VERSION.SDK_INT >= 19,
docs;
if (uri.getScheme().equalsIgnoreCase("content")) {
if (isKitKat && android.provider.DocumentsContract.isDocumentUri(activity, uri)) {
if (String(uri.getAuthority()) == "com.android.externalstorage.documents") {
docs = String(android.provider.DocumentsContract.getDocumentId(uri)).split(":");
if (docs[0] == "primary") {
return android.os.Environment.getExternalStorageDirectory() + "/" + docs[1];
}
} else if (String(uri.getAuthority()) == "com.android.providers.downloads.documents") {
uri = android.content.ContentUris.withAppendedId(
android.net.Uri.parse("content://downloads/public_downloads"),
parseInt(android.provider.DocumentsContract.getDocumentId(uri))
);
} else if (String(uri.getAuthority()) == "com.android.providers.media.documents") {
docs = String(android.provider.DocumentsContract.getDocumentId(uri)).split(":");
if (docs[0] == "image") {
uri = android.provider.MediaStore.Images.Media.EXTERNAL_CONTENT_URI;
} else if (docs[0] == "video") {
uri = android.provider.MediaStore.Video.Media.EXTERNAL_CONTENT_URI;
} else if (docs[0] == "audio") {
uri = android.provider.MediaStore.Audio.Media.EXTERNAL_CONTENT_URI;
}
selection = "_id=?";
selectionArgs = [docs[1]];
}
}
try {
cursor = activity.getContentResolver().query(uri, ["_data"], selection, selectionArgs, null);
if (cursor && cursor.moveToFirst()) {
r = String(cursor.getString(cursor.getColumnIndexOrThrow("_data")));
}
} catch (e) {
log(e);
}
if (cursor) cursor.close();
return r;
} else if (uri.getScheme().equalsIgnoreCase("file")) {
return String(uri.getPath());
}
return null;
}