如標題所述,哪位大神做過這個需求,求指教怎麼在源碼上實現靜默安裝,感激。。。
public class UpdateService extends Service {
/** 安卓系統下載類 **/
DownloadManager manager;
/** 接收下載完的廣播 **/
DownloadCompleteReceiver receiver;
/** 初始化下載器 **/
private void initDownManager(String url) {
manager = (DownloadManager) getSystemService(DOWNLOAD_SERVICE);
receiver = new DownloadCompleteReceiver();
//設置下載地址
DownloadManager.Request down = new DownloadManager.Request(
Uri.parse(url));
// 設置允許使用的網絡類型,這裡是移動網絡和wifi都可以
down.setAllowedNetworkTypes(DownloadManager.Request.NETWORK_MOBILE
| DownloadManager.Request.NETWORK_WIFI);
// 下載時,通知欄顯示途中
down.setNotificationVisibility(DownloadManager.Request.VISIBILITY_VISIBLE);
// 顯示下載界面
down.setVisibleInDownloadsUi(true);
// 設置下載後文件存放的位置
down.setDestinationInExternalFilesDir(this,
Environment.DIRECTORY_DOWNLOADS, "xiaozhuol.apk");
// 將下載請求放入隊列
manager.enqueue(down);
//注冊下載廣播
registerReceiver(receiver, new IntentFilter(
DownloadManager.ACTION_DOWNLOAD_COMPLETE));
}
@Override
public int onStartCommand(Intent intent, int flags, int startId) {
if (intent.getExtras() != null){
Bundle bundle = intent.getExtras() ;
String url = bundle.getString("url") ;
// 調用下載
initDownManager(url);
}
return super.onStartCommand(intent, flags, startId);
}
@Override
public IBinder onBind(Intent intent) {
return null;
}
@Override
public void onDestroy() {
// 注銷下載廣播
if (receiver != null)
unregisterReceiver(receiver);
super.onDestroy();
}
// 接受下載完成後的intent
class DownloadCompleteReceiver extends BroadcastReceiver {
@Override
public void onReceive(Context context, Intent intent) {
//判斷是否下載完成的廣播
if (intent.getAction().equals(
DownloadManager.ACTION_DOWNLOAD_COMPLETE)) {
//獲取下載的文件id
long downId = intent.getLongExtra(
DownloadManager.EXTRA_DOWNLOAD_ID, -1);
//自動安裝apk
installAPK(manager.getUriForDownloadedFile(downId));
//停止服務並關閉廣播
UpdateService.this.stopSelf();
}
}
/**
* 安裝apk文件
*/
private void installAPK(Uri apk) {
// 通過Intent安裝APK文件
Intent intents = new Intent();
intents.setAction("android.intent.action.VIEW");
intents.addCategory("android.intent.category.DEFAULT");
intents.setDataAndType(apk,"application/vnd.android.package-archive");
intents.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
// 如果不加上這句的話在apk安裝完成之後點擊單開會崩潰
getApplication().startActivity(intents);
android.os.Process.killProcess(android.os.Process.myPid());
}
}
}