生活随笔
收集整理的這篇文章主要介紹了
apk下载与安装
小編覺得挺不錯的,現在分享給大家,幫大家做個參考.
public class MainActivity extends Activity {
private File apkFile;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
}
public void downloadAPK(View v) {
//1). 主線程, 顯示提示視圖: ProgressDialog
final ProgressDialog dialog = new ProgressDialog(this);
dialog.setProgressStyle(ProgressDialog.STYLE_HORIZONTAL);
dialog.show();
//準備用于保存APK文件的File對象 : /storage/sdcard/Android/package_name/files/xxx.apk
apkFile = new File(getExternalFilesDir(null), "update.apk");
//2). 啟動分線程, 請求下載APK文件, 下載過程中顯示下載進度
new Thread(new Runnable() {
@Override
public void run() {
try {
//1. 得到連接對象
String path = "http://192.168.10.165:8080/Web_Server/L04_DataStorage.apk";
URL url = new URL(path);
HttpURLConnection connection = (HttpURLConnection) url.openConnection();
//2. 設置
//connection.setRequestMethod("GET");
connection.setConnectTimeout(5000);
connection.setReadTimeout(10000);
//3. 連接
connection.connect();
//4. 請求并得到響應碼200
int responseCode = connection.getResponseCode();
if(responseCode==200) {
//設置dialog的最大進度
dialog.setMax(connection.getContentLength());
//5. 得到包含APK文件數據的InputStream
InputStream is = connection.getInputStream();
//6. 創建指向apkFile的FileOutputStream
FileOutputStream fos = new FileOutputStream(apkFile);
//7. 邊讀邊寫
byte[] buffer = new byte[1024];
int len = -1;
while((len=is.read(buffer))!=-1) {
fos.write(buffer, 0, len);
//8. 顯示下載進度
dialog.incrementProgressBy(len);
//休息一會(模擬網速慢)
//Thread.sleep(50);
SystemClock.sleep(50);
}
fos.close();
is.close();
}
//9. 下載完成, 關閉, 進入3)
connection.disconnect();
//3). 主線程, 移除dialog, 啟動安裝
runOnUiThread(new Runnable() {
@Override
public void run() {
dialog.dismiss();
installAPK();
}
});
} catch (Exception e) {
e.printStackTrace();
}
}
}).start();
//09-05 12:59:20.553: I/ActivityManager(1179): Displayed com.android.packageinstaller/.PackageInstallerActivity: +282ms
}
/**
* 啟動安裝APK
*/
private void installAPK() {
Intent intent = new Intent("android.intent.action.INSTALL_PACKAGE");
intent.setDataAndType(Uri.fromFile(apkFile), "application/vnd.android.package-archive");
startActivity(intent);
}
總結
以上是生活随笔為你收集整理的apk下载与安装的全部內容,希望文章能夠幫你解決所遇到的問題。
如果覺得生活随笔網站內容還不錯,歡迎將生活随笔推薦給好友。