
安卓无法打开 word 文件
在 android 应用中,打开 word 文件时程序自动关闭,可能是由于以下原因:
文件 uri 权限问题
确保应用具有访问外部存储的权限。在 android 6.0 及以上版本中,需在运行时请求权限。在 androidmanifest.xml 中添加以下权限:
在代码中请求权限:
if (contextcompat.checkselfpermission(this, manifest.permission.read_external_storage)
!= packagemanager.permission_granted) {
activitycompat.requestpermissions(this, new string[]{manifest.permission.read_external_storage}, 1);
}构建打开 word 文件的 intent
intent 构建不规范或 mime 类型不正确会导致程序崩溃。使用以下代码构建用于打开 word 文档的 intent:
public intent getwordfileintent(string filepath) {
file file = new file(filepath);
uri fileuri;
if (build.version.sdk_int >= build.version_codes.n) {
// android 7.0 及以上使用 fileprovider
fileuri = fileprovider.geturiforfile(this, getpackagename() + ".fileprovider", file);
} else {
fileuri = uri.fromfile(file);
}
intent intent = new intent(intent.action_view);
intent.setdataandtype(fileuri, "application/msword");
intent.addflags(intent.flag_grant_read_uri_permission); // 授予 uri 读取权限
return intent;
}使用 fileprovider(android 7.0 及以上)
如果目标版本是 android 7.0 及以上,需使用 fileprovider 来安全地共享文件 uri。在 androidmanifest.xml 中添加:
创建 res/xml/file_paths.xml 文件,内容如下:
处理异常
将启动活动的代码放入 try-catch 语句中,以处理异常:
try {
Intent intent = getWordFileIntent(path);
startActivity(intent);
} catch (ActivityNotFoundException e) {
Toast.makeText(this, "找不到可以打开此文件的应用", Toast.LENGTH_LONG).show();
}跳转到 looper
至于跳转到 looper,这是主线程的消息队列,不断处理消息和任务。您的跳转任务可能被放入队列中,导致进入 looper。









