下载Demo地址在这里:点击这里!!!!!
干货
//Activity调用
new UpdataAppHelper(this, APP_UPDATA_TYPE.APPMOBILE).checkUpdate();
UpdataAppHelper .class
package com.app.sample.chatting.service.update;
import android.app.Activity;
import android.app.Dialog;
import android.content.Context;
import android.content.DialogInterface;
import android.support.v7.app.AlertDialog;
import android.util.Log;
import android.widget.Toast;
import com.app.sample.chatting.MyApplication;
import com.app.sample.chatting.api.APi;
import com.app.sample.chatting.api.Network;
import com.app.sample.chatting.api.bean.ResultAppInfo;
import com.app.sample.chatting.service.service.DownLoadAppService;
import com.app.sample.chatting.util.DeviceUtils;
import com.app.sample.chatting.util.GsonUtil;
import retrofit2.Call;
import retrofit2.Callback;
import retrofit2.Response;
/**
* author: Yangbin
* time : 2016/11/3 15:41
* desc :更新APP
*/
public class UpdataAppHelper {
private static final String TAG = "UpdataAppHelper";
private Context mContext;
private APP_UPDATA_TYPE type;
public enum APP_UPDATA_TYPE {
APPMOBILE, APPTV
}
public UpdataAppHelper(Activity mContext, APP_UPDATA_TYPE type) {
this.mContext = mContext;
this.type = type;
}
/**
* 获取服务器最新APP版本信息
*/
public void checkUpdate() {
APi api = Network.getInstance().getApi();//获取单例
Call loginCall = null;
switch (type) {//根据参数,判断是哪种app更新
case APPMOBILE:
loginCall = api.getappupdateinfo();//
break;
case APPTV:
loginCall = api.gettvappupdateinfo();//登录数据服务器接口
break;
}
loginCall.enqueue(new Callback() {
@Override
public void onResponse(Call call, Response response) {
if (response.isSuccessful() && response.body().getResultCode() == 100) {
Log.d(TAG, GsonUtil.GsonString(response.body()));
ResultAppInfo.DataBean dataBean = response.body().getData();
// 版本的更新信息
String version_info = dataBean.getUpdateMessage();
int mVersion_code = DeviceUtils.getVersionCode(MyApplication.getmContext());// 当前的版本号
int nVersion_code = (int) Float.parseFloat(dataBean.getVersionCode());
if (mVersion_code < nVersion_code) {
// 显示提示对话
showNoticeDialog(version_info, nVersion_code, dataBean.getApkUrl());
} else {
Toast.makeText(mContext, "已经是最新版本", Toast.LENGTH_SHORT).show();
}
} else {
MyApplication.showToast("检查更新失败");
}
}
@Override
public void onFailure(Call call, Throwable t) {
MyApplication.showToast("检查更新失败");
}
});//执行登录接口回调
}
/**
* 显示更新对话框
*
* @param versionInfo
* @param apkUrl
* @param nVersion_code
*/
private void showNoticeDialog(String versionInfo, final int nVersion_code, final String apkUrl) {
AlertDialog.Builder builder = new AlertDialog.Builder(mContext);
builder.setTitle("更新提示");
builder.setMessage(versionInfo);
builder.setPositiveButton("立即更新", new DialogInterface.OnClickListener() {
@Override
public void onClick(DialogInterface dialog, int which) {
String apkName = "neolife" + nVersion_code + ".apk";
DownLoadAppService.startDownLoadAppService(mContext, apkName, apkUrl);
}
});
builder.setNegativeButton("以后更新", new DialogInterface.OnClickListener() {
@Override
public void onClick(DialogInterface dialog, int which) {
dialog.dismiss();
}
});
Dialog noticeDialog = builder.create();
noticeDialog.show();
}
}
DeviceUtils.class
package com.app.sample.chatting.util;
import android.content.Context;
import android.content.pm.PackageInfo;
import android.content.pm.PackageManager;
/**
* Created by zs on 2016/7/7.
*/
public class DeviceUtils {
/*
* 获取应用名
*/
public static String getVersionName(Context context) {
String versionName = null;
try {
//获取包管理者
PackageManager pm = context.getPackageManager();
//获取packageInfo
PackageInfo info = pm.getPackageInfo(context.getPackageName(), 0);
//获取versionName
versionName = info.versionName;
} catch (PackageManager.NameNotFoundException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
return versionName;
}
/*
* 获取应用版本
*/
public static int getVersionCode(Context context) {
int versionCode = 0;
try {
//获取包管理者
PackageManager pm = context.getPackageManager();
//获取packageInfo
PackageInfo info = pm.getPackageInfo(context.getPackageName(), 0);
//获取versionCode
versionCode = info.versionCode;
} catch (PackageManager.NameNotFoundException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
return versionCode;
}
}
DownLoadAppService.class
package com.app.sample.chatting.service.service;
import android.app.ActivityManager;
import android.app.IntentService;
import android.app.Notification;
import android.app.NotificationManager;
import android.content.Context;
import android.content.Intent;
import android.net.Uri;
import android.os.Bundle;
import android.os.Handler;
import android.os.IBinder;
import android.os.Looper;
import android.support.annotation.Nullable;
import android.util.Log;
import android.widget.RemoteViews;
import android.widget.Toast;
import com.app.sample.chatting.R;
import com.app.sample.chatting.api.Network;
import java.io.File;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
import java.util.HashMap;
import java.util.Map;
import okhttp3.ResponseBody;
import retrofit2.Call;
import retrofit2.Response;
/**
* author: Yangbin
* time : 2016/11/10 18:02
* desc : 下载app
*/
public class DownLoadAppService extends IntentService {
private String TAG = "UpdataAppHelper";
// NotificationManager : 是状态栏通知的管理类,负责发通知、清楚通知等。
private NotificationManager manager;
private int notifiId = 789;
private int progress = 0;
private String apkName;
// 定义Map来保存Notification对象
private Map map = null;
public DownLoadAppService() {
super("DownLoadAppService");
}
public static void startDownLoadAppService(Context cxt, String apkName, String url) {
ActivityManager manager = (ActivityManager) cxt.getSystemService(ACTIVITY_SERVICE);
for (ActivityManager.RunningServiceInfo service : manager.getRunningServices(Integer.MAX_VALUE)) {
if (DownLoadAppService.class.getName().equals(service.service.getClassName())) {
Toast.makeText(cxt, "已经在下载更新了", Toast.LENGTH_SHORT).show();
return;//退出不再继续执行
}
}
Intent startServiceIntent = new Intent(cxt, DownLoadAppService.class);
Bundle bundle2 = new Bundle();
bundle2.putString("apkName", apkName);
bundle2.putString("url", url);
startServiceIntent.putExtras(bundle2);
cxt.startService(startServiceIntent);
}
@Nullable
@Override
public IBinder onBind(Intent intent) {
return null;
}
@Override
protected void onHandleIntent(Intent intent) {
//NotificationManager 是一个系统Service,必须通过 getSystemService()方法来获取。
manager = (NotificationManager) getSystemService(Context.NOTIFICATION_SERVICE);
map = new HashMap<>();
this.apkName = intent.getExtras().getString("apkName");
String url = intent.getExtras().getString("url");
showNotification(notifiId);
Log.d(TAG, "-->同步下载");
progress = 0;
// 启动后台服务下载apk
Call call = Network.getInstance().getApi().downloadFileWithDynamicUrlSync(url);
try {
Response response = call.execute();
if (response.isSuccessful()) {
Log.d(TAG, "server contacted and has file");
boolean writtenToDisk = writeResponseBodyToDisk(response.body());
Log.d(TAG, "file download was a success? " + writtenToDisk);
cancel(notifiId);
if (writtenToDisk) {
installApk();
} else {
new Handler(Looper.getMainLooper()).post(new Runnable() {
@Override
public void run() {
Toast.makeText(DownLoadAppService.this, "下载更新失败", Toast.LENGTH_LONG).show();
}
});
}
} else {
Log.d(TAG, "server contact failed");
cancel(notifiId);
new Handler(Looper.getMainLooper()).post(new Runnable() {
@Override
public void run() {
Toast.makeText(DownLoadAppService.this, "下载更新失败", Toast.LENGTH_LONG).show();
}
});
}
} catch (IOException e) {
e.printStackTrace();
}
Log.d(TAG, "-->同步下载结束");
}
/**
* 写入
*
* @param body
* @return
*/
private boolean writeResponseBodyToDisk(ResponseBody body) {
try {
// todo change the file location/name according to your needs
File futureStudioIconFile = new File(getExternalFilesDir(null) + File.separator + apkName);
InputStream inputStream = null;
OutputStream outputStream = null;
try {
byte[] fileReader = new byte[4096];
long fileSize = body.contentLength();
long fileSizeDownloaded = 0;
inputStream = body.byteStream();
outputStream = new FileOutputStream(futureStudioIconFile);
while (true) {
int read = inputStream.read(fileReader);
if (read == -1) {
break;
}
outputStream.write(fileReader, 0, read);
fileSizeDownloaded += read;
int pro = (int) (fileSizeDownloaded * 100 / fileSize);
if (pro > progress) {
progress = pro;
updateProgress(notifiId, pro);
}
}
outputStream.flush();
return true;
} catch (IOException e) {
return false;
} finally {
if (inputStream != null) {
inputStream.close();
}
}
} catch (IOException e) {
return false;
}
}
/**
* 安装APK文件
*/
private void installApk() {
File apkfile = new File(getExternalFilesDir(null) + File.separator, apkName);
if (!apkfile.exists()) {
return;
}
// 通过Intent安装APK文件
Intent intent = new Intent(Intent.ACTION_VIEW);
intent.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
intent.setDataAndType(Uri.parse("file://" + apkfile.toString()), "application/vnd.android.package-archive");
startActivity(intent);
}
/**
* 显示通知
*/
public void showNotification(int notificationId) {
if (!map.containsKey(notificationId)) {
Notification notification = new Notification();
notification.tickerText = "正在开始下载文件...";
notification.when = System.currentTimeMillis();
notification.icon = R.mipmap.ic_launcher;
// 设置通知的特性: 通知被点击后,自动消失
notification.flags = Notification.FLAG_AUTO_CANCEL;
// 设置通知的显示视图
RemoteViews remoteViews = new RemoteViews(getPackageName(), R.layout.notification_contentview);
notification.contentView = remoteViews;
// 发出通知
manager.notify(notificationId, notification);
map.put(notificationId, notification);// 存入Map中
}
}
/**
* 取消通知操作
*
* @param notificationId
*/
public void cancel(int notificationId) {
manager.cancel(notificationId);
map.remove(notificationId);
}
/**
* 显示进度
*
* @param notificationId
* @param progress
*/
public void updateProgress(int notificationId, int progress) {
this.progress = progress;
Notification notify = map.get(notificationId);
if (null != notify) {
// 修改进度条
notify.contentView.setProgressBar(R.id.pBar, 100, progress, false);
manager.notify(notificationId, notify);
}
}
@Override
public void onDestroy() {
Log.d(TAG, "onDestroy");
super.onDestroy();
}
}
下载Demo地址在这里:点击这里!!!!!