1. 程式人生 > >解決從內部儲存裝置安裝apk提示Permission Denied

解決從內部儲存裝置安裝apk提示Permission Denied



做應用商店,下載apk,考慮一種情況,如果沒有sd卡的情況下就將apk下載到 Internal Cache目錄下。


下載都正常,但是在安裝的時候提示Permission Denied


/data/data/mypackage/apps/app.apk': Permission denied 
好像是因為data目錄下的檔案只有r+w許可權,沒有x(執行)許可權,MODE_PRIVATE。


FileOutputStream fos = openFileOutput("app.apk", Context.MODE_PRIVATE);
有一種解決方案是,在下載apk建立輸出流的時候指定讀寫許可權:


[java] view plaincopy
String fileName = "tmp.apk";  
FileOutputStream fos = openFileOutput(fileName,MODE_WORLD_READABLE | MODE_WORLD_WRITEABLE);  
File fileLocation = new File(context.getFilesDir(), fileName);  
Intent intent = new Intent(Intent.ACTION_VIEW);  
intent.setDataAndType(Uri.fromFile(fileLocation),"application/vnd.android.package-archive");  
context.startActivity(intent);  


此方案可行,但是我所做的下載使用的斷點續傳,RandomAccessFile.在構造方法中沒辦法像openFileOutput(fileName,MODE_WORLD_READABLE | MODE_WORLD_WRITEABLE);一樣指定讀寫許可權。所以棄之。

然後在stackoverflow上找到了另外的方案,手動授權:

try {
String[] args2 = { "chmod", "604", apkpath};
Runtime.getRuntime().exec(args2);
} catch (IOException e) {
e.printStackTrace();
}
Intent intent = new Intent(Intent.ACTION_VIEW);
intent.setDataAndType(Uri.parse("file://" +apkpath), "application/vnd.android.package-archive");
mContext.startActivity(intent);