如何安装APK ?以及如何让Android dangbeimarket.apk 直接显示我们所期望的应用程序,供用户下载

Android实现检查并下载APK更新、***APK及获取网络信息的方法
投稿:shichen2014
字体:[ ] 类型:转载 时间:
这篇文章主要介绍了Android实现检查并下载APK更新、***APK及获取网络信息的方法,很实用的功能,需要的朋友可以参考下
本文所述实例为一个天气预报中的android代码,主要包括了下载和***APK、检查Apk更新、显示'已经是最新'或者'无法获取版本信息'对话框、获取当前客户端版本信息、显示版本更新通知对话框、显示下载对话框、判断是否挂载了SD卡、显示文件大小格式:2个小数点显示等。具体实现代码如下:
import java.io.ByteArrayInputS
import java.io.F
import java.io.FileOutputS
import java.io.IOE
import java.io.InputS
import java.net.HttpURLC
import java.net.MalformedURLE
import java.net.URL;
import java.text.DecimalF
import org.apache.http.HttpE
import org.apache.http.HttpR
import org.apache.http.client.methods.HttpG
import org.apache.http.conn.ConnectTimeoutE
import org.apache.http.impl.client.DefaultHttpC
import org.apache.http.params.CoreConnectionPN
import org.apache.http.util.EntityU
import org.lmw.weather.R;
import org.lmw.weather.entity.AppD
import android.app.AlertD
import android.app.D
import android.app.ProgressD
import android.app.AlertDialog.B
import android.content.C
import android.content.DialogI
import android.content.I
import android.content.DialogInterface.OnCancelL
import android.content.DialogInterface.OnClickL
import android.content.pm.PackageI
import android.content.pm.PackageManager.NameNotFoundE
import android.net.U
import android.os.E
import android.os.H
import android.os.M
import android.view.LayoutI
import android.view.V
import android.widget.ProgressB
import android.widget.TextV
import android.widget.T
public class DownloadManager {
private static final int DOWN_NOSDCARD = 0;
private static final int DOWN_UPDATE = 1;
private static final int DOWN_OVER = 2;
private static final int DOWN_ERROR=3;
private static final int DIALOG_TYPE_LATEST = 0;
private static final int DIALOG_TYPE_FAIL = 1;
private static final int DIALOG_TYPE_INTERNETERROR = 2;
private static DownloadManager downloadM
private Context mC
// 通知对话框
private Dialog noticeD
// 下载对话框
private Dialog downloadD
private ProgressBar mP
// 显示下载数值
private TextView mProgressT
// 查询动画
private ProgressDialog mProD
// '已经是最新' 或者 '无法获取最新版本' 的对话框
private Dialog latestOrFailD
// 返回的***包url
private String apkUrl = "";
// 下载线程
private Thread downLoadT
// 终止标记
private boolean interceptF
private String updateMsg = "";
// 下载包保存路径
private String savePath = "";
// apk保存完整路径
private String apkFilePath = "";
// 临时下载文件路径
private String tmpFilePath = "";
// 下载文件大小
private String apkFileS
// 已下载文件大小
private String tmpFileS
private String curVersionName = "";
private int curVersionC
private AppDetail mD
private String checkUrl="http://192.168.0.133:8080/lmw/androidMarket/SimpleWeather-49937/update.xml";
private Handler mHandler = new Handler() {
public void handleMessage(Message msg) {
switch (msg.what) {
case DOWN_UPDATE:
mProgress.setProgress(progress);
mProgressText.setText(tmpFileSize + "/" + apkFileSize);
case DOWN_OVER:
downloadDialog.dismiss();
installApk();
case DOWN_NOSDCARD:
downloadDialog.dismiss();
Toast.makeText(mContext, "无法下载***文件,请检查SD卡是否挂载",Toast.LENGTH_SHORT).show();
case DOWN_ERROR:
downloadDialog.dismiss();
if(msg.arg1==0){
Toast.makeText(mContext, "网络不给力啊", Toast.LENGTH_SHORT).show();
}else if(msg.arg1==1||msg.arg1==2){
Toast.makeText(mContext, "未找到资源",Toast.LENGTH_SHORT).show();
public static DownloadManager getDownloadManager() {
if (downloadManager == null) {
downloadManager = new DownloadManager();
downloadManager.interceptFlag =
return downloadM
public void DownLoader(Context context, AppDetail download) {
this.mContext =
this.mDownload =
showDownloadDialog();
* 检查App更新
* @param context
* @param isShowMsg
* 是否显示提示消息
public void checkAppUpdate(Context context, final boolean isShowMsg,final boolean notmain) {
this.mContext =
getCurrentVersion(mContext);
if (isShowMsg) {
if (mProDialog == null)
mProDialog = ProgressDialog.show(mContext, null, "正在检测,请稍后...",true, true);
else if (mProDialog.isShowing()|| (latestOrFailDialog != null && latestOrFailDialog.isShowing()))
final Handler handler = new Handler() {
public void handleMessage(Message msg) {
// 进度条对话框不显示 - 检测结果也不显示
if (mProDialog != null && !mProDialog.isShowing()) {
// 关闭并释放释放进度条对话框
if (isShowMsg && mProDialog != null) {
mProDialog.dismiss();
mProDialog =
// 显示检测结果
if (msg.what == 1) {
mDownload = (AppDetail) msg.
if (mDownload != null) {
if (curVersionCode & mDownload.getVersionCode()) {
apkUrl = mDownload.getUri()+mDownload.getFileName();
updateMsg = mDownload.getAppHistory();
showNoticeDialog();
} else if (isShowMsg) {
if (notmain) {
showLatestOrFailDialog(DIALOG_TYPE_LATEST);
}else if(msg.what==-1&&isShowMsg){
showLatestOrFailDialog(DIALOG_TYPE_INTERNETERROR);
}else if (isShowMsg) {
showLatestOrFailDialog(DIALOG_TYPE_FAIL);
new Thread() {
public void run() {
Message msg = new Message();
DefaultHttpClient client = new DefaultHttpClient();
client.getParams().setParameter(CoreConnectionPNames.CONNECTION_TIMEOUT, 3000);
HttpGet get = new HttpGet(checkUrl);
HttpResponse response = client.execute(get);
if (response.getStatusLine().getStatusCode() == 200) {
HttpEntity entity = response.getEntity();
InputStream stream = new ByteArrayInputStream( EntityUtils.toString(entity, "gb2312").getBytes());
AppDetail update = AppDetail.parseXML(stream);
msg.what = 1;
msg.what = -1;
} catch (Exception e) {
e.printStackTrace();
msg.what = -1;
handler.sendMessage(msg);
}.start();
/*显示'已经是最新'或者'无法获取版本信息'对话框*/
private void showLatestOrFailDialog(int dialogType) {
String ToastMsg="";
if (latestOrFailDialog != null) {
// 关闭并释放之前的对话框
latestOrFailDialog.dismiss();
latestOrFailDialog =
// AlertDialog.Builder builder = new Builder(mContext);
// builder.setTitle("系统提示");
if (dialogType == DIALOG_TYPE_LATEST) {
builder.setMessage("您当前已经是最新版本");
ToastMsg="您当前已经是最新版本";
} else if (dialogType == DIALOG_TYPE_FAIL) {
builder.setMessage("无法获取版本更新信息");
ToastMsg="无法获取版本更新信息";
}else if(dialogType==DIALOG_TYPE_INTERNETERROR){
// builder.setMessage("网络故障,无法连接服务器");
ToastMsg="网络故障,无法连接服务器";
Toast.makeText(mContext, ToastMsg, Toast.LENGTH_SHORT).show();
/*获取当前客户端版本信息*/
public String getCurrentVersion(Context context) {
PackageInfo info = context.getPackageManager().getPackageInfo(context.getPackageName(), 0);
curVersionName = info.versionN
curVersionCode = info.versionC
} catch (NameNotFoundException e) {
e.printStackTrace(System.err);
return curVersionN
/*显示版本更新通知对话框*/
private void showNoticeDialog() {
AlertDialog.Builder builder = new Builder(mContext);
builder.setTitle("软件版本更新");
builder.setMessage(updateMsg);
builder.setPositiveButton("立即更新", new OnClickListener() {
public void onClick(DialogInterface dialog, int which) {
dialog.dismiss();
showDownloadDialog();
builder.setNegativeButton("以后再说", new OnClickListener() {
public void onClick(DialogInterface dialog, int which) {
dialog.dismiss();
noticeDialog = builder.create();
noticeDialog.show();
/*显示下载对话框*/
private void showDownloadDialog() {
AlertDialog.Builder builder = new Builder(mContext);
builder.setTitle("正在下载***包");
final LayoutInflater inflater = LayoutInflater.from(mContext);
View v = inflater.inflate(R.layout.download_progress, null);
mProgress = (ProgressBar) v.findViewById(R.id.update_progress);
mProgressText = (TextView) v.findViewById(R.id.update_progress_text);
builder.setView(v);
builder.setNegativeButton("取消", new OnClickListener() {
public void onClick(DialogInterface dialog, int which) {
dialog.dismiss();
interceptFlag =
builder.setOnCancelListener(new OnCancelListener() {
public void onCancel(DialogInterface dialog) {
dialog.dismiss();
interceptFlag =
downloadDialog = builder.create();
downloadDialog.setCanceledOnTouchOutside(false);
downloadDialog.show();
downloadApk();
private Runnable mdownApkRunnable = new Runnable() {
Message error_msg=new Message();
public void run(){
String apkName = mDownload.getFileName().replace(".apk","")+".apk";
String tmpApk = mDownload.getFileName().replace(".apk","")+".tmp";
// 判断是否挂载了SD卡
String storageState = Environment.getExternalStorageState();
if (storageState.equals(Environment.MEDIA_MOUNTED)) {
savePath = Environment.getExternalStorageDirectory().getAbsolutePath() + "/QN/QNStore/";
File file = new File(savePath);
if (!file.exists()) {
file.mkdirs();
apkFilePath = savePath + apkN
tmpFilePath = savePath + tmpA
// 没有挂载SD卡,无法下载文件
if (apkFilePath == null || apkFilePath == "") {
mHandler.sendEmptyMessage(DOWN_NOSDCARD);
File ApkFile = new File(apkFilePath);
// 是否已下载更新文件
// if (ApkFile.exists()) {
downloadDialog.dismiss();
installApk();
// 输出临时下载文件
File tmpFile = new File(tmpFilePath);
FileOutputStream fos = new FileOutputStream(tmpFile);
URL url = new URL(mDownload.getUri()+mDownload.getFileName());
HttpURLConnection conn = (HttpURLConnection) url.openConnection();
conn.connect();
} catch (ConnectTimeoutException e) {
error_msg.what=DOWN_ERROR;
error_msg.arg1=0;
mHandler.sendMessage(error_msg);
int length = conn.getContentLength();
InputStream is = conn.getInputStream();
// 显示文件大小格式:2个小数点显示
DecimalFormat df = new DecimalFormat("0.00");
// 进度条下面显示的总文件大小
apkFileSize = df.format((float) length / 1024 / 1024) + "MB";
int count = 0;
byte buf[] = new byte[1024];
int numread = is.read(buf);
// 进度条下面显示的当前下载文件大小
tmpFileSize = df.format((float) count / 1024 / 1024) + "MB";
// 当前进度值
progress = (int) (((float) count / length) * 100);
// 更新进度
mHandler.sendEmptyMessage(DOWN_UPDATE);
if (numread &= 0) {
// 下载完成 - 将临时下载文件转成APK文件
if (tmpFile.renameTo(ApkFile)) {
// 通知***
mHandler.sendEmptyMessage(DOWN_OVER);
fos.write(buf, 0, numread);
} while (!interceptFlag);// 点击取消就停止下载
fos.close();
is.close();
} catch (MalformedURLException e) {
error_msg.what=DOWN_ERROR;
error_msg.arg1=1;
mHandler.sendMessage(error_msg);
e.printStackTrace();
} catch (IOException e) {
error_msg.what=DOWN_ERROR;
error_msg.arg1=2;
mHandler.sendMessage(error_msg);
e.printStackTrace();
* @param url
private void downloadApk() {
downLoadThread = new Thread(mdownApkRunnable);
downLoadThread.start();
* @param url
private void installApk() {
File apkfile = new File(apkFilePath);
if (!apkfile.exists()) {
Intent i = new Intent(Intent.ACTION_VIEW);
i.setDataAndType(Uri.parse("file://" + apkfile.toString()),"application/vnd.android.package-archive");
mContext.startActivity(i);
您可能感兴趣的文章:
大家感兴趣的内容
12345678910
最近更新的内容
常用在线小工具Uri uri = Uri.parse(&market://search?q=名称&);
Intent i = new Intent(&Intent.ACTION_VIEW&, uri);
startActivity(i);
//根据应用程序ID=应用程序的包名
Uri urii = Uri.parse(&market://details?id=com.xiaoqiu.test&);
Intent ii = new Intent(&Intent.ACTION_VIEW&, urii);
startActivity(ii);
参考知识库
* 以上用户言论只代表其个人观点,不代表CSDN网站的观点或立场
访问:321310次
积分:4336
积分:4336
排名:第5504名
原创:107篇
转载:16篇
评论:88条
最新文章请到新站:
(1)(1)(1)(1)(2)(4)(2)(1)(1)(2)(2)(2)(4)(2)(1)(3)(2)(3)(1)(2)(18)(9)(24)(3)(9)(6)(6)(2)(5)(2)(5)

参考资料

 

随机推荐