我試圖下載一個apk文件,然後安裝它。
我已經做了一個外部存儲目錄,但是當我在本地目錄中下載文件時,我無法解析它。如何從內部存儲文件安裝應用程序
這裏是onCreate方法
final DownloadTask downloadTask = new DownloadTask(this);
downloadTask.execute("http://file.appsapk.com/wp-content/uploads/apps-2/Gmail.apk","Gmail.apk");
代碼DownloadTask是從的AsyncTask延伸的類。 這裏是後臺任務:
@Override
protected String doInBackground(String... sUrl) {
file_name=sUrl[1];
Boolean isSDPresent = android.os.Environment.getExternalStorageState().equals(android.os.Environment.MEDIA_MOUNTED);
if (isSDPresent) {
directory = new File(Environment.getExternalStorageDirectory()+File.separator+"app_directory");
}
else
{
directory = getFilesDir();
}
if (!directory.exists())
directory.mkdirs();
InputStream input = null;
OutputStream output = null;
HttpURLConnection connection = null;
try {
URL url = new URL(sUrl[0]);
connection = (HttpURLConnection) url.openConnection();
connection.connect();
if (connection.getResponseCode() != HttpURLConnection.HTTP_OK) {
return "Server returned HTTP " + connection.getResponseCode()
+ " " + connection.getResponseMessage();
}
int fileLength = connection.getContentLength();
input = connection.getInputStream();
output = new FileOutputStream(directory+"/"+file_name);
byte[] buffer = new byte[1024];
long total = 0;
int count;
while ((count = input.read(buffer)) != -1) {
if (isCancelled()) {
input.close();
return null;
}
total += count;
if (fileLength > 0) // only if total length is known
publishProgress((int) (total * 100/fileLength));
output.write(buffer, 0, count);
}
} catch (Exception e) {
return e.toString();
} finally {
try {
if (input != null)
input.close();
if (output != null)
output.close();
} catch (IOException ignored) {
}
if (connection != null)
connection.disconnect();
}
return null;
}
這是下載完文件後,第一個運行執行後的方法:
@Override
protected void onPostExecute(String result) {
mWakeLock.release();
mProgressDialog.dismiss();
if (result != null)
{
Toast.makeText(context,"Download error: "+result, Toast.LENGTH_LONG).show();
}
else
{
Toast.makeText(context, "File downloaded", Toast.LENGTH_SHORT).show();
File file = new File(directory, file_name);
Intent promptInstall = new Intent(Intent.ACTION_VIEW)
.setDataAndType(Uri.fromFile(file),
"application/vnd.android.package-archive");
context.startActivity(promptInstall);
finish();
}
它與外部存儲完美運行,但它贏得了」與外部運行。爲什麼不?
你在哪裏測試應用程序?在模擬器中還是在真實的設備中? – chkm8 2014-10-30 11:10:21
在模擬器 – Safouen 2014-10-30 11:12:38
嘗試看到這個http://stackoverflow.com/questions/4967669/android-install-apk-programmatically你有類似的問題 – chkm8 2014-10-30 11:36:51