现在的Android项目都有远程更新的功能,下面是HTTP模式的一种更新方式,特此记录;HTTPS模式的请回复我私聊;
public class DownloadAppActivity extends BaseActivity implements View.OnClickListener {
private TextView headerText;
private ImageView backBtn;
private String navTitle;
private CommonProgressDialog pBar;
//Handler handler = new Handler();
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
}
@Override
protected int getLayoutId() {
return R.layout.activity_download_app;
}
@Override
protected void initViews() {
backBtn = (ImageView) findViewById(R.id.header_back);
headerText = (TextView) findViewById(R.id.header_title);
headerText.setText(navTitle);
int vision = 1;//旧版本号
String newversion = “2.1”;//更新新的版本号
String content = “程序要更新了\n” ;//更新内容
String url = “http://******”;//安装包下载地址
ShowDialog(vision, newversion, content, url);
}
@Override
protected void setListeners() {
backBtn.setOnClickListener(this);
}
@Override
protected void loadParam() {
navTitle = getIntent().getStringExtra(EUIParamKeys.NAV_TITLE.toString());
}
@Override
protected void handleMsg(Message msg) {
}
@Override
public void onClick(View view) {
switch (view.getId()) {
case R.id.header_back:
finish();
break;
default:
break;
}
}
/**
* 升级系统
* @param content
* @param url
*/
private void ShowDialog(int vision, String newversion, final String content,
final String url) {
boolean isNetworkConn = NetworkConnectionUtils.isNetworkConnected(DownloadAppActivity.this);
if (!isNetworkConn) {
Toast.makeText(DownloadAppActivity.this, “网络连接失败!”, Toast.LENGTH_SHORT);
Log.d(“zfr-isNetworkConn:==”, “网络连接失败!”);
ActionResult result = new ActionResult(TransResult.ERR_NETWORK_DISCONNET, null);
finish(result);
} else {
Log.d(“zfr-isNetworkConn:==”, “成功连接网络!”);
// handler.postDelayed(new Runnable() {
// @Override
// public void run() {
new android.app.AlertDialog.Builder(DownloadAppActivity.this)
.setTitle(“版本更新”)
.setMessage(content)
.setPositiveButton(“更新”, new DialogInterface.OnClickListener() {
@Override
public void onClick(DialogInterface dialog, int which) {
dialog.dismiss();
pBar = new CommonProgressDialog(DownloadAppActivity.this, R.style.Dialog_Fullscreen);
pBar.setCanceledOnTouchOutside(false);
pBar.setTitle(“正在下载”);
pBar.setCustomTitle(LayoutInflater.from(
DownloadAppActivity.this).inflate(
R.layout.title_dialog, null));
pBar.setMessage(“正在下载”);
pBar.setIndeterminate(true);
pBar.setProgressStyle(ProgressDialog.STYLE_HORIZONTAL);
pBar.setCancelable(false);
// 动态设置自定义Dialog的显示内容的宽和高
WindowManager m = getWindowManager();
Display d = m.getDefaultDisplay(); //为获取屏幕宽、高
android.view.WindowManager.LayoutParams p = pBar.getWindow().getAttributes(); //获取对话框当前的参数值
p.height = (int) (d.getHeight() * 0.7); //高度设置为屏幕的0.3
p.width = d.getWidth(); //宽度设置为全屏
//p.width = (int) (d.getWidth() * 1); //宽度设置为全屏
pBar.getWindow().setAttributes(p); //设置生效
// downFile(URLData.DOWNLOAD_URL);
final DownloadTask downloadTask = new DownloadTask(
DownloadAppActivity.this);
downloadTask.execute(url);
pBar.setOnCancelListener(new DialogInterface.OnCancelListener() {
@Override
public void onCancel(DialogInterface dialog) {
downloadTask.cancel(true);
}
});
}
})
.setNegativeButton(“取消”, new DialogInterface.OnClickListener() {
@Override
public void onClick(DialogInterface dialog, int which) {
dialog.dismiss();
ActionResult result = new ActionResult(TransResult.ERR_USER_CANCLE, null);
finish(result);
}
})
.show();
// }
// }, 1);
}
}
/**
* 下载应用
*
* @author Administrator
*/
// 下载存储的文件名
private static final String DOWNLOAD_NAME = “channelWe”;
class DownloadTask extends AsyncTask<String, Integer, String> {
private Context context;
private PowerManager.WakeLock mWakeLock;
public DownloadTask(Context context) {
this.context = context;
}
@Override
protected String doInBackground(String… sUrl) {
InputStream input = null;
OutputStream output = null;
HttpURLConnection connection = null;
File file = null;
try {
URL url = new URL(sUrl[0]);
connection = (HttpURLConnection) url.openConnection();
connection.connect();
// expect HTTP 200 OK, so we don’t mistakenly save error
// report
// instead of the file
if (connection.getResponseCode() != HttpURLConnection.HTTP_OK) {
return “Server returned HTTP ”
+ connection.getResponseCode() + ” ”
+ connection.getResponseMessage();
}
// this will be useful to display download percentage
// might be -1: server did not report the length
int fileLength = connection.getContentLength();
if (Environment.getExternalStorageState().equals(
Environment.MEDIA_MOUNTED)) {
file = new File(Environment.getExternalStorageDirectory(),
DOWNLOAD_NAME);
if (!file.exists()) {
// 判断父文件夹是否存在
if (!file.getParentFile().exists()) {
file.getParentFile().mkdirs();
}
}
} else {
Toast.makeText(DownloadAppActivity.this, “sd卡未挂载”,
Toast.LENGTH_LONG).show();
}
input = connection.getInputStream();
output = new FileOutputStream(file);
byte data[] = new byte[4096];
long total = 0;
int count;
while ((count = input.read(data)) != -1) {
// allow canceling with back button
if (isCancelled()) {
input.close();
return null;
}
total += count;
// publishing the progress….
if (fileLength > 0) // only if total length is known
publishProgress((int) (total * 100 / fileLength));
output.write(data, 0, count);
}
} catch (Exception e) {
System.out.println(e.toString());
return e.toString();
} finally {
try {
if (output != null)
output.close();
if (input != null)
input.close();
} catch (IOException ignored) {
}
if (connection != null)
connection.disconnect();
}
return null;
}
@Override
protected void onPreExecute() {//执行后台耗时操作前被调用,通常用于进行初始化操作.
super.onPreExecute();
// take CPU lock to prevent CPU from going off if the user
// presses the power button during download
PowerManager pm = (PowerManager) context
.getSystemService(Context.POWER_SERVICE);
mWakeLock = pm.newWakeLock(PowerManager.PARTIAL_WAKE_LOCK,
getClass().getName());
mWakeLock.acquire();
pBar.show();
}
@Override
protected void onProgressUpdate(Integer… progress) {//当在doInBackground方法中调用publishProgress方法更新任务执行进度后,将调用此方法.通过此方法我们可以知晓任务的完成进度.
super.onProgressUpdate(progress);
// if we get here, length is known, now set indeterminate to false
pBar.setIndeterminate(false);
pBar.setMax(100);
pBar.setProgress(progress[0]);
}
@Override
protected void onPostExecute(String result) {//当doInBackground方法完成后,系统将自动调用此方法,并将doInBackground方法返回的值传入此方法.通过此方法进行UI的更新.
mWakeLock.release();
try {
pBar.dismiss();
} catch (Exception e) {
System.out.println(e.toString());
ActionResult result1 = new ActionResult(TransResult.ERR_DOWNLOAD_APP, null);
finish(result1);
}
if (result != null) {
ActionResult result1 = new ActionResult(TransResult.ERR_DOWNLOAD_APP, null);
finish(result1);
// // 申请多个权限。大神的界面
// AndPermission.with(MainActivity.this)
// .requestCode(REQUEST_CODE_PERMISSION_OTHER)
// .permission(Manifest.permission.WRITE_EXTERNAL_STORAGE, Manifest.permission.READ_EXTERNAL_STORAGE)
// // rationale作用是:用户拒绝一次权限,再次申请时先征求用户同意,再打开授权对话框,避免用户勾选不再提示。
// .rationale(new RationaleListener() {
// @Override
// public void showRequestPermissionRationale(int requestCode, Rationale rationale) {
// // 这里的对话框可以自定义,只要调用rationale.resume()就可以继续申请。
// AndPermission.rationaleDialog(MainActivity.this, rationale).show();
// }
// }
// )
// .send();
// 申请多个权限。
// AndPermission.with(DownloadAppActivity.this)
// .requestCode(REQUEST_CODE_PERMISSION_SD)
// .permission(Manifest.permission.WRITE_EXTERNAL_STORAGE, Manifest.permission.READ_EXTERNAL_STORAGE)
// // rationale作用是:用户拒绝一次权限,再次申请时先征求用户同意,再打开授权对话框,避免用户勾选不再提示。
// .rationale(rationaleListener
// )
// .send();
//
//
// Toast.makeText(context, “您未打开SD卡权限” + result, Toast.LENGTH_LONG).show();
} else {
// Toast.makeText(context, “File downloaded”,
// Toast.LENGTH_SHORT)
// .show();
update();
}
}
}
private void update() {
//安装应用
Intent intent = new Intent(Intent.ACTION_VIEW);
intent.setDataAndType(Uri.fromFile(new File(Environment
.getExternalStorageDirectory(), DOWNLOAD_NAME)),
“application/vnd.android.package-archive”);
startActivity(intent);
}
@Override
public boolean onKeyDown(int keyCode, KeyEvent event) {
if (keyCode == KeyEvent.KEYCODE_BACK) {
ActionResult result = new ActionResult(TransResult.ERR_ABORTED, null);
finish(result);
return true;
}
return super.onKeyDown(keyCode, event);
}
}
https模式下载请私聊我
;
注:如有问题可以回复,看到第一时间分析解决,码农不易,感觉对您有用,帮助到您,可否打赏一杯可乐,在此谢过诸位,愿诸君终成大神,前程似锦~~~