【问题标题】:File or Folder Doesn't exist while opening PDF from assets从资产打开 PDF 时文件或文件夹不存在
【发布时间】:2014-08-25 08:57:36
【问题描述】:
try {
Intent intent = new Intent(Intent.ACTION_VIEW);
intent.setDataAndType(Uri.parse("file:///android_assets"+"/abc.pdf"),
"application/pdf");
startActivity(intent);
} catch (Exception e) {
WriteLogToFile.appendLog(Dashboard.this, "File", "file.txt", ActivityUtil.writeException(e));
Intent i = new Intent(Intent.ACTION_VIEW);
i.setData(Uri.parse("market://details?id=com.adobe.reader&hl=en"));
startActivity(i);
}
在某些设备中,这工作正常。但在少数设备中,它会给出错误,例如找不到文件或文件夹,请帮助我解决问题
【问题讨论】:
标签:
android
android-intent
android-assets
【解决方案1】:
试试这个
public class SampleActivity extends Activity
{
@Override
protected void onCreate(Bundle savedInstanceState)
{
super.onCreate(savedInstanceState);
setContentView(R.layout.main);
CopyReadAssets();
}
private void CopyReadAssets()
{
AssetManager assetManager = getAssets();
InputStream in = null;
OutputStream out = null;
File file = new File(getFilesDir(), "abc.pdf");
try
{
in = assetManager.open("abc.pdf");
out = openFileOutput(file.getName(), Context.MODE_WORLD_READABLE);
copyFile(in, out);
in.close();
in = null;
out.flush();
out.close();
out = null;
} catch (Exception e)
{
Log.e("tag", e.getMessage());
}
Intent intent = new Intent(Intent.ACTION_VIEW);
intent.setDataAndType(
Uri.parse("file://" + getFilesDir() + "/abc.pdf"),
"application/pdf");
startActivity(intent);
}
private void copyFile(InputStream in, OutputStream out) throws IOException
{
byte[] buffer = new byte[1024];
int read;
while ((read = in.read(buffer)) != -1)
{
out.write(buffer, 0, read);
}
}
}
【解决方案2】:
尝试将 uri 从 file:///android_assets/ 重命名为 file:///android_asset/
assets 文件夹中存储的文件的正确路径是file:///android_asset/xxx,没有“s”
例如:
Intent intent = new Intent(Intent.ACTION_VIEW);
intent.addFlags (Intent.FLAG_ACTIVITY_NEW_TASK);
Uri uri = Uri.fromFile(new File("file:///android_asset/abc.pdf"));
intent.setDataAndType (uri, "application/pdf");
this.startActivity(intent);