更新软件时要用到将软件下载到SD卡并主动弹出安装界面,就想安卓市场一样,下面总结一个简单的实训过程:
1、检测某个应用是否已经安装了:
只需要一个包名就可以了。如果是更新软件本身就没必要检测安装,只检测版本号就可以了。
2、判断sd卡是否存在:
如果不存在就没必要下载了。
3、下载并保存到sd卡:
4、等下载完成了就要启动安装界面:
其中的sendMsg()方法是用于更新handler的。
1、检测某个应用是否已经安装了:
public boolean isPkgInstalled(String packageName) {
PackageManager pm = getPackageManager();
try {
pm.getPackageInfo(packageName, 0);
} catch (Exception e) {
return false;
}
return true;
}
只需要一个包名就可以了。如果是更新软件本身就没必要检测安装,只检测版本号就可以了。
2、判断sd卡是否存在:
private boolean isSDcard() {
if (android.os.Environment.getExternalStorageState().equals(
android.os.Environment.MEDIA_MOUNTED)) {
return true;
} else {
return false;
}
}
如果不存在就没必要下载了。
3、下载并保存到sd卡:
public void down_file(String url) {
try {
String path = "/sdcard/download/";
filename = url.substring(url.lastIndexOf("/") + 1);
URL myURL = new URL(url);
URLConnection conn = myURL.openConnection();
conn.connect();
InputStream is = conn.getInputStream();
fileSize = conn.getContentLength();
if (fileSize <= 0)
throw new RuntimeException(getString(R.string.download_unknow_size));
if (is == null)
throw new RuntimeException("stream is null");
FileOutputStream fos = new FileOutputStream(path + filename);
byte buf[] = new byte[1024];
downLoadFileSize = 0;
sendMsg(0);
do {
int numread = is.read(buf);
if (numread == -1) {
break;
}
fos.write(buf, 0, numread);
downLoadFileSize += numread;
sendMsg(1);
} while (true);
sendMsg(2);
is.close();
} catch (Exception ex) {
Log.e("tag", "error: " + ex.getMessage(), ex);
}
}
4、等下载完成了就要启动安装界面:
private void installAPK() {
String fileName = getSDPath() +"/download/"+filename;
Intent intent = new Intent(Intent.ACTION_VIEW);
intent.setDataAndType(Uri.fromFile(new File(fileName)), "application/vnd.android.package-archive");
startActivity(intent);
}
其中的sendMsg()方法是用于更新handler的。