正在做一款軟件,要求是檢測到有更新之後自動下載並且安裝,不彈出安裝界面,網上找了好多都不能實現。求解
PS:不是流氓軟件,類似於銀行叫號機的軟件
import java.io.File;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.net.HttpURLConnection;
import java.net.MalformedURLException;
import java.net.URL;
import org.json.JSONObject;
import android.content.BroadcastReceiver;
import android.content.Context;
import android.content.Intent;
import android.content.IntentFilter;
import android.content.SharedPreferences;
import android.content.SharedPreferences.Editor;
import android.content.pm.PackageInfo;
import android.content.pm.PackageManager;
import android.content.pm.PackageManager.NameNotFoundException;
import android.graphics.AvoidXfermode.Mode;
import android.net.Uri;
import android.os.Environment;
import android.os.Handler;
import android.os.Message;
import android.util.Log;
import android.widget.ProgressBar;
import android.widget.TextView;
import android.widget.Toast;
import com.golfor.api.RequstClient;
import com.golfor.api.UIHelper;
import com.golfor.app.AppContext;
import com.golfor.constants.Iconstants;
import com.golfor.http.AsyncHttpResponseHandler;
import com.golfor.ui.common.DownloadDialog;
import com.golfor.ui.common.DownloadDialog.MyCancelClickListener;
import com.golfor.ui.common.UpdateConfirmDialog;
import com.golfor.ui.common.UpdateConfirmDialog.DialogClickListener;
/**
public class UpdateManager {
/* 下載中 /
private static final int DOWNLOAD = 1;
/ 下載結束 /
private static final int DOWNLOAD_FINISH = 2;
/ 下載保存路徑 /
private String mSavePath;
private String mAppName;
private String versionName;
/ 記錄進度條數量 /
private int progress;
/ 是否取消更新 /
private boolean cancelUpdate = false;
private Context mContext;
/ 更新進度條 /
private ProgressBar mProgress;
private TextView tv_pro;
/*用來保存版本號*/
private SharedPreferences mSaveVersionCode,mSaveName;
private Editor mEt,mSn;
private DownloadDialog downloadProgress;
private final String tag = "_TEST";
private DownloadDialog mDialog;
//上一個版本名
String beforName = "1.0";
private Handler mHandler = new Handler() {
public void handleMessage(Message msg) {
switch (msg.what) {
// 正在下載
case DOWNLOAD:
String pro = msg.obj.toString();
tv_pro.setText("正在下載(" + pro + ")");
// 設置進度條位置
mProgress.setProgress(progress);
break;
case DOWNLOAD_FINISH:
// 安裝文件
installApk();
break;
default:
break;
}
};
};
private String downUrl;
// public UpdateManager(Context context, String appName, String downUrl) {
// this.mContext = context;
// mAppName = appName;
// this.downUrl = downUrl;
// }
public UpdateManager(Context context) {
this.mContext = context;
}
/**
* 從服務器上獲取版本信息
/
public void getVersionDataFromWeb(final String str){
RequstClient.getVersionCode(new AsyncHttpResponseHandler(){
@Override
public void onFailure(Throwable error, String content) {
// TODO Auto-generated method stub
super.onFailure(error, content);
UIHelper.cloesLoadDialog();
}
@Override
public void onSuccess(int statusCode, String content) {
// TODO Auto-generated method stub
super.onSuccess(statusCode, content);
UIHelper.cloesLoadDialog();
Log.e("TEST", " 從服務器上獲取版本信息");
try {
JSONObject obj = new JSONObject(content);
JSONObject data = obj.getJSONObject("data");
String apkUrl = data.getString("apkPath");
String serviceVersion = data.getString("apkVersion");
String apkMessage = data.getString("apkMessage");
String apkName = data.getString("apkName");
versionName = data.getString("apkVersionName");
AppContext.getInstance().setAppVersion(versionName);
mAppName = apkName;
Log.e(tag, apkUrl+">>>"+apkMessage+"//"+Integer.parseInt(serviceVersion)+"/"+apkName+"/"+versionName);
downUrl = apkUrl;
checkUpdate(versionName,apkMessage,str);
} catch (Exception e) {
// TODO Auto-generated catch block
e.printStackTrace();
UIHelper.cloesLoadDialog();
}
}
});
}
/*
* 檢測軟件更新
/
public void checkUpdate(String versionName, String content,String flag) {
if (isUpdate(versionName)) {
// 顯示提示對話框
showNoticeDialog(content);
} else{
if(flag.equals(Iconstants.MINE_FRAGMENT)){
UIHelper.showToasts("處於最新版本");
}
return ;
}
}
/*
* 檢查軟件是否有更新版本
* @return
/
private boolean isUpdate(String versionName) {
mSaveVersionCode = mContext.getSharedPreferences("version", mContext.MODE_PRIVATE);
mSaveName = mContext.getSharedPreferences("beforename", mContext.MODE_PRIVATE);
mEt = mSaveVersionCode.edit();
mSn = mSaveName.edit();
beforName = mSaveName.getString("beforename", "1.0");
// 獲取當前軟件版本
String currentVersionName = getVersionCode(mContext,beforName);
Log.e(tag, "當前軟件版本:"+currentVersionName+""+"下載的版本:"+versionName);
if (versionName.equals(currentVersionName)) {
// mEt.putInt("versionCode", serviceCode);
return false;
}else{
return true;
}
}
/*
* 獲取軟件版本號
*
* @param context
* @return
*/
public String getVersionCode(Context context,String beforeName) {
String version = mSaveVersionCode.getString("versionName",null);
if(version == null){
// String pkg = context.getPackageName();
// 獲取軟件版本號,對應AndroidManifest.xml下android:versionCode
PackageManager manager = context.getPackageManager();
PackageInfo info;
try {
info = manager.getPackageInfo(context.getPackageName(), 0);
version = info.versionName;
Log.e(tag, "上一個版本版本:"+beforeName+""+"保存的版本:"+version);
} catch (NameNotFoundException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}else{
//更新後的版本號
version = mSaveVersionCode.getString("versionName", null);
mSn.putString("name", version);
mSn.commit();
Log.e(tag, "更新後保存的版本:"+beforName);
}
return version;
}
/**
* 顯示軟件更新對話框
*/
public void showNoticeDialog(String content) {
// 構造對話框
UpdateConfirmDialog dialog = new UpdateConfirmDialog(mContext);
dialog.setCustomTitle("發現新版本");
dialog.setUpdateContent(content);
dialog.setConfirm("立即下載");
dialog.setCancel("稍後更新");
dialog.setCanceledOnTouchOutside(false);
dialog.setClickListener(new DialogClickListener() {
@Override
public void onConfirmClickListener() {
mEt.putString("versionName", versionName);
mEt.commit();
// 顯示下載對話框
showDownloadDialog();
}
@Override
public void onCancelClickListener() {
}
});
dialog.show();
}
/**
* 顯示軟件下載對話框
*/
private void showDownloadDialog() {
// 構造軟件下載對話框
mDialog = new DownloadDialog(mContext);
mDialog.setTitle("下載更新");
mProgress = mDialog.getProgressBar();
tv_pro = mDialog.getMessage();
//取消
// dialog.setMyClickListener(new MyCancelClickListener() {
// public void onCancelClickListener() {
// cancelUpdate = true;
// }
// });
mDialog.show();
// 現在文件
downloadApk();
}
/**
* 下載apk文件
*/
private void downloadApk() {
// 啟動新線程下載軟件
new downloadApkThread().start();
}
/**
* 下載文件線程
*
* @author coolszy
* @date 2012-4-26
* @blog http://blog.92coding.com
*/
private class downloadApkThread extends Thread {
@Override
public void run() {
try {
// 判斷SD卡是否存在,並且是否具有讀寫權限
if (Environment.getExternalStorageState().equals(Environment.MEDIA_MOUNTED)) {
// 獲得存儲卡的路徑
String sdpath = Environment.getExternalStorageDirectory() + "/";
mSavePath = sdpath + "download";
URL url = new URL(downUrl);
// 創建連接
HttpURLConnection conn = (HttpURLConnection) url.openConnection();
conn.connect();
// 獲取文件大小
int length = conn.getContentLength();
// 創建輸入流
InputStream is = conn.getInputStream();
File file = new File(mSavePath);
// 判斷文件目錄是否存在
if (!file.exists()) {
file.mkdir();
}
File apkFile = new File(mSavePath, mAppName);
FileOutputStream fos = new FileOutputStream(apkFile);
int count = 0;
// 緩存
byte buf[] = new byte[1024];
// 寫入到文件中
do {
int numread = is.read(buf);
count += numread;
// 計算進度條位置
progress = (int) (((float) count / length) * 100);
Message msg = new Message();
msg.obj = progress + "%";
msg.what = DOWNLOAD;
// 更新進度
mHandler.sendMessage(msg);
if (numread <= 0) {
// 下載完成
mDialog.cancel();
mHandler.sendEmptyMessage(DOWNLOAD_FINISH);
break;
}
// 寫入文件
fos.write(buf, 0, numread);
} while (!cancelUpdate);// 點擊取消就停止下載.
fos.close();
is.close();
}
} catch (MalformedURLException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
// 取消下載對話框顯示
if (downloadProgress != null ) {
downloadProgress.dismiss();
}
}
};
/**
* 安裝APK文件
*/
private void installApk() {
File apkfile = new File(mSavePath, mAppName);
if (!apkfile.exists()) {
return;
}
// 通過Intent安裝APK文件
Intent i = new Intent(Intent.ACTION_VIEW);
i.setDataAndType(Uri.parse("file://" + apkfile.toString()), "application/vnd.android.package-archive");
mContext.startActivity(i);
}
/**
*
*/
}