将手机上应用版本号等相关信息发送到服务器,服务器检测是否有新版本。如果有新版本,将返回客户端版本号、版本名称、下载地址、版本更新说明等信息。客户端获取到此信息后,将询问用户是否下载,确定后,开始下载。下载完成后开始提示安装。
调用系统DownloadManager实现下载:
DownloadManager downloadManager = (DownloadManager) getSystemService(DOWNLOAD_SERVICE);
DownloadManager.Request request = new DownloadManager.Request( 版本下载地址);
request.setDestinationInExternalPublicDir(Environment.DIRECTORY_DOWNLOADS, "xxx.apk");//将apk下载到download默认目录
request.allowScanningByMediaScanner();
request.setMimeType("application/cn.trinea.download.file");
long downloadId = downloadManager.enqueue(request);//每个下载请求对应一个downloadId
PrefUtils.setLong(PrefUtils.DOWNLOAD_ID, downloadId);//暂存到Preference中
下载完成后,将发送DownloadManager.ACTION_DOWNLOAD_COMPLETE广播。因此需要建立一个Broadcast Receiver来接收广播,确认下载成功后进行安装提示。
public class DownloadCompleteReceiver extends BroadcastReceiver {
@Override
public void onReceive(Context context, Intent intent) {
long completeDownloadId = intent.getLongExtra(DownloadManager.EXTRA_DOWNLOAD_ID, -1);
if (completeDownloadId != -1 && completeDownloadId == PrefUtils.getLong(PrefUtils.DOWNLOAD_ID, -1)) {
DownloadManager downloadManager = (DownloadManager) context.getSystemService(Context.DOWNLOAD_SERVICE);
DownloadManager.Query query = new DownloadManager.Query().setFilterById(completeDownloadId);
Cursor cursor = null;
String filename = null;
try {
cursor = downloadManager.query(query);
if (cursor != null && cursor.moveToFirst()) {
filename = cursor.getString(cursor.getColumnIndexOrThrow(DownloadManager.COLUMN_LOCAL_FILENAME));
}
} finally {
if (cursor != null) {
cursor.close();
}
}
if (!TextUtils.isEmpty(filename)) {
Intent installIntent = new Intent(Intent.ACTION_VIEW);
installIntent.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
installIntent.setDataAndType(Uri.fromFile(new File(filename)),"application/vnd.android.package-archive");
context.startActivity(installIntent);
}
}
}
}