Android實現應用下載並自動安裝apk包

安裝:


1String str = "/CanavaCancel.apk";
2String fileName = Environment.getExternalStorageDirectory() + str;
3Intent intent = newIntent(Intent.ACTION_VIEW);
4intent.setDataAndType(Uri.fromFile(newFile(fileName)), "application/vnd.android.package-archive");
5startActivity(intent);


卸載:


1Uri packageURI = Uri.parse("package:com.demo.CanavaCancel");  
2Intent uninstallIntent = newIntent(Intent.ACTION_DELETE, packageURI);  
3startActivity(uninstallIntent);


Environment擁有一些可以獲取環境變量的方法
package:com.demo.CanavaCancel 這個形式是 package:程序完整的路徑 (包名+程序名).

//下載apk程序代碼


01protectedFile downLoadFile(String httpUrl) {
02// TODO Auto-generated method stub
03finalString fileName = "updata.apk";
04File tmpFile = newFile("/sdcard/update");
05if(!tmpFile.exists()) {
06tmpFile.mkdir();
07}
08finalFile file = newFile("/sdcard/update/"+ fileName);
09
10try{
11URL url = newURL(httpUrl);
12try{
13HttpURLConnection conn = (HttpURLConnection) url
14.openConnection();
15InputStream is = conn.getInputStream();
16FileOutputStream fos = newFileOutputStream(file);
17byte[] buf = newbyte[256];
18conn.connect();
19doublecount = 0;
20if(conn.getResponseCode() >= 400) {
21Toast.makeText(Main.this, "連接超時", Toast.LENGTH_SHORT)
22.show();
23} else{
24while(count <= 100) {
25if(is != null) {
26intnumRead = is.read(buf);
27if(numRead <= 0) {
28break;
29} else{
30fos.write(buf, 0, numRead);
31}
32
33} else{
34break;
35}
36
37}
38}
39
40conn.disconnect();
41fos.close();
42is.close();
43} catch(IOException e) {
44// TODO Auto-generated catch block
45
46e.printStackTrace();
47}
48} catch(MalformedURLException e) {
49// TODO Auto-generated catch block
50
51e.printStackTrace();
52}
53
54returnfile;
55}
56//打開APK程序代碼
57
58privatevoidopenFile(File file) {
59// TODO Auto-generated method stub
60Log.e("OpenFile", file.getName());
61Intent intent = newIntent();
62intent.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
63intent.setAction(android.content.Intent.ACTION_VIEW);
64intent.setDataAndType(Uri.fromFile(file),
65"application/vnd.android.package-archive");
66startActivity(intent);
67}


發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章