entry : requestProperty.entrySet()){
@@ -112,7 +117,7 @@ public class HttpManager implements IHttpManager {
connect.connect();
- Log.d(Constants.TAG,"Content-Type:" + connect.getContentType());
+ LogUtils.d("Content-Type:" + connect.getContentType());
int responseCode = connect.getResponseCode();
switch (responseCode){
case HttpURLConnection.HTTP_OK: {
@@ -124,7 +129,7 @@ public class HttpManager implements IHttpManager {
length = connect.getContentLengthLong();
}
- Log.d(Constants.TAG, "contentLength:" + length);
+ LogUtils.d( "contentLength:" + length);
long progress = 0;
@@ -140,7 +145,7 @@ public class HttpManager implements IHttpManager {
}
fos.write(buffer, 0, len);
progress += len;
- //更新进度
+ // 更新进度
if (length > 0) {
publishProgress(progress, length);
}
@@ -163,9 +168,9 @@ public class HttpManager implements IHttpManager {
case HttpURLConnection.HTTP_MOVED_TEMP:
case HttpURLConnection.HTTP_SEE_OTHER:
case HTTP_TEMP_REDIRECT:
- case HTTP_PERM_REDIRECT: {//重定向
+ case HTTP_PERM_REDIRECT: {// 重定向
String redirectUrl = connect.getHeaderField("Location");
- Log.d(Constants.TAG,"redirectUrl = " + redirectUrl);
+ LogUtils.d("redirectUrl = " + redirectUrl);
connect.disconnect();
return download(redirectUrl);
}
@@ -230,7 +235,6 @@ public class HttpManager implements IHttpManager {
}
}
-
}
}
\ No newline at end of file
diff --git a/app-updater/src/main/java/com/king/app/updater/http/IHttpManager.java b/app-updater/src/main/java/com/king/app/updater/http/IHttpManager.java
index 7d71d63..47ba9ce 100644
--- a/app-updater/src/main/java/com/king/app/updater/http/IHttpManager.java
+++ b/app-updater/src/main/java/com/king/app/updater/http/IHttpManager.java
@@ -8,7 +8,7 @@ import java.util.Map;
import androidx.annotation.Nullable;
/**
- * IHttpManager 默认提供{@link HttpManager} 和 {@link OkHttpManager}两种实现。
+ * IHttpManager 默认提供 {@link HttpManager} 和 {@link OkHttpManager} 两种实现。
* @author Jenly Jenly
*/
public interface IHttpManager {
diff --git a/app-updater/src/main/java/com/king/app/updater/http/OkHttpManager.java b/app-updater/src/main/java/com/king/app/updater/http/OkHttpManager.java
index a1b00a8..42d181f 100644
--- a/app-updater/src/main/java/com/king/app/updater/http/OkHttpManager.java
+++ b/app-updater/src/main/java/com/king/app/updater/http/OkHttpManager.java
@@ -1,9 +1,8 @@
package com.king.app.updater.http;
import android.os.AsyncTask;
-import android.util.Log;
-import com.king.app.updater.constant.Constants;
+import com.king.app.updater.util.LogUtils;
import com.king.app.updater.util.SSLSocketFactoryUtils;
import org.apache.http.conn.ssl.SSLSocketFactory;
@@ -23,8 +22,8 @@ import okhttp3.Request;
import okhttp3.Response;
/**
- * OkHttpManager使用{@link OkHttpClient}实现{@link IHttpManager}
- * 使用OkHttpManager时必须依赖OkHttp库
+ * OkHttpManager使用 {@link OkHttpClient} 实现的 {@link IHttpManager}
+ * 使用 OkHttpManager 时必须依赖 OkHttp 库
* @author Jenly
*/
public class OkHttpManager implements IHttpManager {
@@ -33,7 +32,7 @@ public class OkHttpManager implements IHttpManager {
private OkHttpClient okHttpClient;
- private boolean isCancel;
+ private DownloadTask mDownloadTask;
private static volatile OkHttpManager INSTANCE;
@@ -77,20 +76,23 @@ public class OkHttpManager implements IHttpManager {
@Override
public void download(String url,final String path,final String filename, @Nullable Map requestProperty,final DownloadCallback callback) {
- isCancel = false;
- new DownloadTask(okHttpClient,url,path,filename,requestProperty,callback).execute();
+ mDownloadTask = new DownloadTask(okHttpClient, url, path, filename, requestProperty, callback);
+ mDownloadTask.execute();
}
@Override
public void cancel() {
- isCancel = true;
+ if(mDownloadTask != null){
+ mDownloadTask.isCancel = true;
+ }
}
/**
* 异步下载任务
*/
- private class DownloadTask extends AsyncTask {
+ private static class DownloadTask extends AsyncTask {
+
private String url;
private String path;
@@ -105,6 +107,8 @@ public class OkHttpManager implements IHttpManager {
private OkHttpClient okHttpClient;
+ private volatile boolean isCancel;
+
public DownloadTask(OkHttpClient okHttpClient,String url, String path, String filename ,@Nullable Map requestProperty, DownloadCallback callback){
this.okHttpClient = okHttpClient;
this.url = url;
@@ -138,7 +142,7 @@ public class OkHttpManager implements IHttpManager {
long length = response.body().contentLength();
- Log.d(Constants.TAG,"contentLength:" + length);
+ LogUtils.d("contentLength:" + length);
long progress = 0;
@@ -157,7 +161,7 @@ public class OkHttpManager implements IHttpManager {
}
fos.write(buffer,0,len);
progress += len;
- //更新进度
+ // 更新进度
if(length > 0){
publishProgress(progress,length);
}
@@ -175,7 +179,7 @@ public class OkHttpManager implements IHttpManager {
return file;
- }else {//连接失败
+ }else {// 连接失败
throw new ConnectException(String.format("responseCode = %d",response.code()));
}
diff --git a/app-updater/src/main/java/com/king/app/updater/notify/INotification.java b/app-updater/src/main/java/com/king/app/updater/notify/INotification.java
new file mode 100644
index 0000000..2f7c41f
--- /dev/null
+++ b/app-updater/src/main/java/com/king/app/updater/notify/INotification.java
@@ -0,0 +1,25 @@
+package com.king.app.updater.notify;
+
+import android.content.Context;
+
+import com.king.app.updater.UpdateConfig;
+
+import java.io.File;
+
+import androidx.annotation.DrawableRes;
+
+/**
+ * @author Jenly
+ */
+public interface INotification {
+
+ void onStart(Context context, int notifyId, String channelId, String channelName, @DrawableRes int icon, CharSequence title, CharSequence content, boolean isVibrate, boolean isSound, boolean isCancelDownload);
+
+ void onProgress(Context context, int notifyId, String channelId, @DrawableRes int icon, CharSequence title, CharSequence content, int progress, int size, boolean isCancelDownload);
+
+ void onFinish(Context context, int notifyId, String channelId, @DrawableRes int icon, CharSequence title, CharSequence content, File file, String authority);
+
+ void onError(Context context, int notifyId, String channelId, @DrawableRes int icon, CharSequence title, CharSequence content, boolean isReDownload, UpdateConfig config);
+
+ void onCancel(Context context, int notifyId);
+}
diff --git a/app-updater/src/main/java/com/king/app/updater/notify/NotificationImpl.java b/app-updater/src/main/java/com/king/app/updater/notify/NotificationImpl.java
new file mode 100644
index 0000000..1ab4108
--- /dev/null
+++ b/app-updater/src/main/java/com/king/app/updater/notify/NotificationImpl.java
@@ -0,0 +1,38 @@
+package com.king.app.updater.notify;
+
+import android.content.Context;
+
+import com.king.app.updater.UpdateConfig;
+import com.king.app.updater.util.NotificationUtils;
+
+import java.io.File;
+
+/**
+ * @author Jenly
+ */
+public class NotificationImpl implements INotification {
+ @Override
+ public void onStart(Context context, int notifyId, String channelId, String channelName, int icon, CharSequence title, CharSequence content, boolean isVibrate, boolean isSound, boolean isCancelDownload) {
+ NotificationUtils.showStartNotification(context, notifyId, channelId, channelName, icon, title, content, isVibrate, isSound, isCancelDownload);
+ }
+
+ @Override
+ public void onProgress(Context context, int notifyId, String channelId, int icon, CharSequence title, CharSequence content, int progress, int size, boolean isCancelDownload) {
+ NotificationUtils.showProgressNotification(context, notifyId, channelId, icon, title, content, progress, size, isCancelDownload);
+ }
+
+ @Override
+ public void onFinish(Context context, int notifyId, String channelId, int icon, CharSequence title, CharSequence content, File file, String authority) {
+ NotificationUtils.showFinishNotification(context, notifyId, channelId, icon, title, content, file, authority);
+ }
+
+ @Override
+ public void onError(Context context, int notifyId, String channelId, int icon, CharSequence title, CharSequence content, boolean isReDownload, UpdateConfig config) {
+ NotificationUtils.showErrorNotification(context, notifyId, channelId, icon, title, content, isReDownload, config);
+ }
+
+ @Override
+ public void onCancel(Context context, int notifyId) {
+ NotificationUtils.cancelNotification(context, notifyId);
+ }
+}
diff --git a/app-updater/src/main/java/com/king/app/updater/service/DownloadService.java b/app-updater/src/main/java/com/king/app/updater/service/DownloadService.java
index 2d7d05f..0507670 100644
--- a/app-updater/src/main/java/com/king/app/updater/service/DownloadService.java
+++ b/app-updater/src/main/java/com/king/app/updater/service/DownloadService.java
@@ -7,7 +7,6 @@ import android.os.Binder;
import android.os.Build;
import android.os.IBinder;
import android.text.TextUtils;
-import android.util.Log;
import com.king.app.updater.R;
import com.king.app.updater.UpdateConfig;
@@ -15,16 +14,22 @@ import com.king.app.updater.callback.UpdateCallback;
import com.king.app.updater.constant.Constants;
import com.king.app.updater.http.HttpManager;
import com.king.app.updater.http.IHttpManager;
+import com.king.app.updater.notify.INotification;
+import com.king.app.updater.notify.NotificationImpl;
import com.king.app.updater.util.AppUtils;
-import com.king.app.updater.util.NotificationUtils;
+import com.king.app.updater.util.LogUtils;
import java.io.File;
+import java.util.Locale;
+import androidx.annotation.NonNull;
import androidx.annotation.Nullable;
+import androidx.annotation.StringRes;
import androidx.core.content.ContextCompat;
/**
+ * 下载服务
* @author Jenly Jenly
*/
public class DownloadService extends Service {
@@ -34,22 +39,16 @@ public class DownloadService extends Service {
* 是否在下载,防止重复下载。
*/
private boolean isDownloading;
- /**
- * 最后更新进度,用来降频刷新
- */
- private int mLastProgress = -1;
- /**
- * 最后进度更新时间,用来降频刷新
- */
- private long mLastTime;
/**
* 失败后重新下载次数
*/
private int mCount = 0;
-
+ /**
+ * Http管理器
+ */
private IHttpManager mHttpManager;
- private File mFile;
+ private File mApkFile;
private Context getContext(){
return this;
@@ -57,9 +56,7 @@ public class DownloadService extends Service {
@Override
public int onStartCommand(Intent intent, int flags, int startId) {
-
if(intent != null){
-
boolean isStop = intent.getBooleanExtra(Constants.KEY_STOP_DOWNLOAD_SERVICE,false);
if(isStop){
stopDownload();
@@ -70,10 +67,10 @@ public class DownloadService extends Service {
mCount++;
}
//获取配置信息
- UpdateConfig config = intent.getParcelableExtra(Constants.KEY_UPDATE_CONFIG);
- startDownload(config,null,null);
+ UpdateConfig config = intent.getParcelableExtra(Constants.KEY_UPDATE_CONFIG);
+ startDownload(config,null,null, new NotificationImpl());
}else{
- Log.w(Constants.TAG,"Please do not duplicate downloads.");
+ LogUtils.w("Please do not duplicate downloads.");
}
}
@@ -90,18 +87,13 @@ public class DownloadService extends Service {
* @param httpManager
* @param callback
*/
- public void startDownload(UpdateConfig config,IHttpManager httpManager,UpdateCallback callback){
-
- if(config == null){
- return;
- }
-
+ public void startDownload(@NonNull UpdateConfig config,@Nullable IHttpManager httpManager,@Nullable UpdateCallback callback, @Nullable INotification notification){
if(callback != null){
callback.onDownloading(isDownloading);
}
if(isDownloading){
- Log.w(Constants.TAG,"Please do not duplicate downloads.");
+ LogUtils.w("Please do not duplicate downloads.");
return;
}
@@ -111,7 +103,7 @@ public class DownloadService extends Service {
//如果保存路径为空则使用缓存路径
if(TextUtils.isEmpty(path)){
- path = getExternalFilesDir(getContext());
+ path = getCacheFilesDir(getContext());
}
File dirFile = new File(path);
if(!dirFile.exists()){
@@ -123,49 +115,45 @@ public class DownloadService extends Service {
filename = AppUtils.getAppFullName(getContext(),url,getResources().getString(R.string.app_name));
}
- mFile = new File(path,filename);
- if(mFile.exists()){//文件是否存在
-
+ mApkFile = new File(path, filename);
+ if(mApkFile.exists()){//文件是否存在
Integer versionCode = config.getVersionCode();
String apkMD5 = config.getApkMD5();
//是否存在相同的apk
boolean isExistApk = false;
if(!TextUtils.isEmpty(apkMD5)){//如果存在MD5,则优先校验MD5
- Log.d(Constants.TAG,String.format("UpdateConfig.apkMD5:%s",apkMD5));
- isExistApk = AppUtils.checkFileMD5(mFile,apkMD5);
+ LogUtils.d(String.format(Locale.getDefault(),"UpdateConfig.apkMD5:%s",apkMD5));
+ isExistApk = AppUtils.checkFileMD5(mApkFile,apkMD5);
}else if(versionCode != null){//如果存在versionCode,则校验versionCode
- try{
- Log.d(Constants.TAG,String.format("UpdateConfig.versionCode:%d",versionCode));
- isExistApk = AppUtils.apkExists(getContext(),versionCode,mFile);
- }catch (Exception e){
- Log.w(Constants.TAG,e);
- }
+ LogUtils.d(String.format(Locale.getDefault(),"UpdateConfig.versionCode:%d",versionCode));
+ isExistApk = AppUtils.apkExists(getContext(),versionCode,mApkFile);
}
if(isExistApk){
//本地已经存在要下载的APK
- Log.d(Constants.TAG,"CacheFile:" + mFile);
+ LogUtils.d("CacheFile:" + mApkFile);
if(config.isInstallApk()){
String authority = config.getAuthority();
if(TextUtils.isEmpty(authority)){//如果为空则默认
- authority = getContext().getPackageName() + Constants.DEFAULT_FILE_PROVIDER;
+ authority = AppUtils.getFileProviderAuthority(getContext());
}
- AppUtils.installApk(getContext(),mFile,authority);
+ AppUtils.installApk(getContext(), mApkFile, authority);
}
- if(callback!=null){
- callback.onFinish(mFile);
+ if(callback != null){
+ callback.onFinish(mApkFile);
}
stopService();
return;
}
//删除旧文件
- mFile.delete();
+ mApkFile.delete();
}
- Log.d(Constants.TAG,"File:" + mFile);
+ LogUtils.d("File:" + mApkFile);
mHttpManager = httpManager != null ? httpManager : HttpManager.getInstance();
- mHttpManager.download(url,path,filename,config.getRequestProperty(),new AppDownloadCallback(config,callback));
+ IHttpManager.DownloadCallback downloadCallback = new AppDownloadCallback(getContext(),this, config, mApkFile, callback, notification);
+ mHttpManager.download(url,path,filename,config.getRequestProperty(), downloadCallback);
}
@@ -183,12 +171,18 @@ public class DownloadService extends Service {
* @param context
* @return
*/
- private String getExternalFilesDir(Context context) {
- File[] files = ContextCompat.getExternalFilesDirs(context,Constants.DEFAULT_DIR);
- if(files!=null && files.length > 0){
+ private String getCacheFilesDir(Context context) {
+ File[] files = ContextCompat.getExternalFilesDirs(context, Constants.DEFAULT_DIR);
+ if(files != null && files.length > 0){
return files[0].getAbsolutePath();
}
- return context.getExternalFilesDir(Constants.DEFAULT_DIR).getAbsolutePath();
+
+ File externalFilesDir = context.getExternalFilesDir(Constants.DEFAULT_DIR);
+ if(externalFilesDir != null){
+ return externalFilesDir.getAbsolutePath();
+ }
+
+ return new File(context.getFilesDir(), Constants.DEFAULT_DIR).getAbsolutePath();
}
@@ -203,7 +197,14 @@ public class DownloadService extends Service {
//---------------------------------------- DownloadCallback
- public class AppDownloadCallback implements IHttpManager.DownloadCallback{
+ /**
+ * App下载回调接口
+ */
+ public static class AppDownloadCallback implements IHttpManager.DownloadCallback {
+
+ private Context context;
+
+ private DownloadService downloadService;
public UpdateConfig config;
@@ -231,22 +232,38 @@ public class DownloadService extends Service {
private UpdateCallback callback;
- private int reDownloads;
-
-
- private AppDownloadCallback(UpdateConfig config,UpdateCallback callback){
+ private INotification notification;
+
+ /**
+ * 最后更新进度,用来降频刷新
+ */
+ private int lastProgress;
+ /**
+ * 最后进度更新时间,用来降频刷新
+ */
+ private long lastTime;
+ /**
+ * APK文件
+ */
+ private File apkFile;
+
+
+ private AppDownloadCallback(Context context, DownloadService downloadService, UpdateConfig config, File apkFile, UpdateCallback callback, INotification notification){
+ this.context = context;
+ this.downloadService = downloadService;
this.config = config;
+ this.apkFile = apkFile;
this.callback = callback;
+ this.notification = notification;
this.isShowNotification = config.isShowNotification();
this.notifyId = config.getNotificationId();
- this.reDownloads = config.getReDownloads();
if(Build.VERSION.SDK_INT >= Build.VERSION_CODES.O){
this.channelId = TextUtils.isEmpty(config.getChannelId()) ? Constants.DEFAULT_NOTIFICATION_CHANNEL_ID : config.getChannelId();
this.channelName = TextUtils.isEmpty(config.getChannelName()) ? Constants.DEFAULT_NOTIFICATION_CHANNEL_NAME : config.getChannelName();
}
if(config.getNotificationIcon() <= 0){
- this.notificationIcon = AppUtils.getAppIcon(getContext());
+ this.notificationIcon = AppUtils.getAppIcon(context);
}else{
this.notificationIcon = config.getNotificationIcon();
}
@@ -255,23 +272,25 @@ public class DownloadService extends Service {
this.authority = config.getAuthority();
if(TextUtils.isEmpty(config.getAuthority())){//如果为空则默认
- authority = getContext().getPackageName() + Constants.DEFAULT_FILE_PROVIDER;
+ authority = AppUtils.getFileProviderAuthority(context);
}
this.isShowPercentage = config.isShowPercentage();
- this.isReDownload = config.isReDownload();
this.isDeleteCancelFile = config.isDeleteCancelFile();
this.isCancelDownload = config.isCancelDownload();
+ //支持下载失败时重新下载,当重新下载次数不超过限制时才被允许
+ this.isReDownload = config.isReDownload() && downloadService.mCount < config.getReDownloads();
+
}
@Override
public void onStart(String url) {
- Log.d(Constants.TAG,"onStart:" + url);
- isDownloading = true;
- mLastProgress = 0;
- if(isShowNotification){
- NotificationUtils.showStartNotification(getContext(),notifyId,channelId,channelName,notificationIcon,getString(R.string.app_updater_start_notification_title),getString(R.string.app_updater_start_notification_content),config.isVibrate(),config.isSound(),isCancelDownload);
+ LogUtils.i("url:" + url);
+ downloadService.isDownloading = true;
+ lastProgress = 0;
+ if(isShowNotification && notification != null){
+ notification.onStart(context,notifyId,channelId,channelName,notificationIcon,getString(R.string.app_updater_start_notification_title),getString(R.string.app_updater_start_notification_content),config.isVibrate(),config.isSound(),isCancelDownload);
}
if(callback != null){
@@ -281,25 +300,24 @@ public class DownloadService extends Service {
@Override
public void onProgress(long progress, long total) {
-
boolean isChange = false;
long curTime = System.currentTimeMillis();
- if(mLastTime + 200 < curTime) {//降低更新频率
- mLastTime = curTime;
+ if(lastTime + 200 < curTime || progress == total) {//降低更新频率
+ lastTime = curTime;
int currProgress = Math.round(progress * 1.0f / total * 100.0f);
- if(currProgress != mLastProgress){//百分比改变了才更新
+ if(currProgress != lastProgress){//百分比改变了才更新
isChange = true;
- mLastProgress = currProgress;
+ lastProgress = currProgress;
String percentage = currProgress + "%";
- if(isShowNotification) {
- String content = getString(R.string.app_updater_progress_notification_content);
+ LogUtils.i(String.format(Locale.getDefault(),"%s \t(%d/%d)", percentage, progress, total));
+ if(isShowNotification && notification != null) {
+ String content = context.getString(R.string.app_updater_progress_notification_content);
if (isShowPercentage) {
content += percentage;
}
- NotificationUtils.showProgressNotification(getContext(),notifyId, channelId, notificationIcon, getString(R.string.app_updater_progress_notification_title), content, currProgress, 100,isCancelDownload);
-
+ notification.onProgress(context,notifyId, channelId, notificationIcon, context.getString(R.string.app_updater_progress_notification_title), content, currProgress, 100,isCancelDownload);
}
}
}
@@ -311,50 +329,56 @@ public class DownloadService extends Service {
@Override
public void onFinish(File file) {
- Log.d(Constants.TAG,"onFinish:" + file);
- isDownloading = false;
- NotificationUtils.showFinishNotification(getContext(),notifyId,channelId,notificationIcon,getString(R.string.app_updater_finish_notification_title),getString(R.string.app_updater_finish_notification_content),file,authority);
+ LogUtils.d("File:" + file);
+ downloadService.isDownloading = false;
+ if(isShowNotification && notification != null){
+ notification.onFinish(context,notifyId,channelId,notificationIcon,getString(R.string.app_updater_finish_notification_title),getString(R.string.app_updater_finish_notification_content),file,authority);
+ }
if(isInstallApk){
- AppUtils.installApk(getContext(),file,authority);
+ AppUtils.installApk(context,file,authority);
}
if(callback != null){
callback.onFinish(file);
}
- stopService();
+ downloadService.stopService();
}
@Override
public void onError(Exception e) {
- Log.w(Constants.TAG,"onError:"+ e.getMessage());
- isDownloading = false;
- if(isShowNotification){
- //支持下载失败时重新下载,当重新下载次数不超过限制时才被允许
- boolean isReDownload = this.isReDownload && mCount < reDownloads;
+ LogUtils.w(e.getMessage());
+ downloadService.isDownloading = false;
+ if(isShowNotification && notification != null){
String content = isReDownload ? getString(R.string.app_updater_error_notification_content_re_download) : getString(R.string.app_updater_error_notification_content);
- NotificationUtils.showErrorNotification(getContext(),notifyId,channelId,notificationIcon,getString(R.string.app_updater_error_notification_title),content,isReDownload,config);
+ notification.onError(context,notifyId,channelId,notificationIcon,getString(R.string.app_updater_error_notification_title),content,isReDownload,config);
}
if(callback != null){
callback.onError(e);
}
if(!isReDownload){
- stopService();
+ downloadService.stopService();
}
}
@Override
public void onCancel() {
- Log.d(Constants.TAG,"onCancel");
- isDownloading = false;
- NotificationUtils.cancelNotification(getContext(),notifyId);
+ LogUtils.d("Cancel download.");
+ downloadService.isDownloading = false;
+ if(isShowNotification && notification != null){
+ notification.onCancel(context,notifyId);
+ }
if(callback != null){
callback.onCancel();
}
- if(isDeleteCancelFile && mFile!=null){
- mFile.delete();
+ if(isDeleteCancelFile && apkFile != null){
+ apkFile.delete();
}
- stopService();
+ downloadService.stopService();
+ }
+
+ private String getString(@StringRes int resId){
+ return context.getString(resId);
}
}
@@ -374,22 +398,47 @@ public class DownloadService extends Service {
}
/**
- * 提供绑定服务的方式下载
+ * 提供绑定服务的方式进行下载
*/
public class DownloadBinder extends Binder {
- public void start(UpdateConfig config){
+ /**
+ * 开始下载
+ * @param config {@link UpdateConfig}
+ */
+ public void start(@NonNull UpdateConfig config){
start(config,null);
}
- public void start(UpdateConfig config,UpdateCallback callback){
- start(config,null,callback);
+ /**
+ * 开始下载
+ * @param config {@link UpdateConfig}
+ * @param callback {@link UpdateCallback}
+ */
+ public void start(@NonNull UpdateConfig config, @Nullable UpdateCallback callback){
+ start(config,null, callback);
}
- public void start(UpdateConfig config,IHttpManager httpManager,UpdateCallback callback){
- startDownload(config,httpManager,callback);
+ /**
+ * 开始下载
+ * @param config {@link UpdateConfig}
+ * @param httpManager {@link IHttpManager}
+ * @param callback {@link UpdateCallback}
+ */
+ public void start(@NonNull UpdateConfig config, @Nullable IHttpManager httpManager, @Nullable UpdateCallback callback){
+ start(config, httpManager, callback, new NotificationImpl());
}
+ /**
+ * 开始下载
+ * @param config {@link UpdateConfig}
+ * @param httpManager {@link IHttpManager}
+ * @param callback {@link UpdateCallback}
+ * @param notification {@link INotification}
+ */
+ public void start(@NonNull UpdateConfig config, @Nullable IHttpManager httpManager, @Nullable UpdateCallback callback,@NonNull INotification notification){
+ startDownload(config, httpManager, callback, notification);
+ }
}
diff --git a/app-updater/src/main/java/com/king/app/updater/util/AppUtils.java b/app-updater/src/main/java/com/king/app/updater/util/AppUtils.java
index 9280677..893f8d0 100644
--- a/app-updater/src/main/java/com/king/app/updater/util/AppUtils.java
+++ b/app-updater/src/main/java/com/king/app/updater/util/AppUtils.java
@@ -47,7 +47,7 @@ public final class AppUtils {
}
String filename = getAppName(context);
-
+ Log.d(Constants.TAG, "AppName:" + filename);
if(TextUtils.isEmpty(filename)){
filename = defaultName;
}
@@ -65,7 +65,7 @@ public final class AppUtils {
*/
public static PackageInfo getPackageInfo(Context context) throws PackageManager.NameNotFoundException {
PackageManager packageManager = context.getPackageManager();
- PackageInfo packageInfo = packageManager.getPackageInfo( context.getPackageName(), 0);
+ PackageInfo packageInfo = packageManager.getPackageInfo(context.getPackageName(), 0);
return packageInfo;
}
@@ -75,7 +75,7 @@ public final class AppUtils {
* @param archiveFilePath
* @return
*/
- public static PackageInfo getPackageInfo(Context context, String archiveFilePath) throws Exception {
+ public static PackageInfo getPackageInfo(Context context, String archiveFilePath) {
PackageManager packageManager = context.getPackageManager();
PackageInfo packageInfo = packageManager.getPackageArchiveInfo(archiveFilePath, PackageManager.GET_ACTIVITIES);
return packageInfo;
@@ -106,7 +106,6 @@ public final class AppUtils {
} catch (Exception e) {
e.printStackTrace();
}
-
return 0;
}
@@ -128,7 +127,6 @@ public final class AppUtils {
* @return
*/
public static Intent getInstallIntent(Context context,File file,String authority){
-
Intent intent = new Intent(Intent.ACTION_VIEW);
intent.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
intent.addCategory(Intent.CATEGORY_DEFAULT);
@@ -152,11 +150,11 @@ public final class AppUtils {
* @return
* @throws Exception
*/
- public static boolean apkExists(Context context,int versionCode,File file) throws Exception{
- if(file!=null && file.exists()){
+ public static boolean apkExists(Context context,int versionCode,File file){
+ if(file != null && file.exists()){
String packageName = context.getPackageName();
PackageInfo packageInfo = AppUtils.getPackageInfo(context,file.getAbsolutePath());
- if(packageInfo != null){//比对versionCode
+ if(packageInfo != null){// 比对versionCode
Log.d(Constants.TAG,String.format("ApkVersionCode:%d",packageInfo.versionCode));
if(versionCode == packageInfo.versionCode){
ApplicationInfo applicationInfo = packageInfo.applicationInfo;
@@ -244,6 +242,10 @@ public final class AppUtils {
return null;
}
+ public static String getFileProviderAuthority(Context context){
+ return context.getPackageName() + Constants.DEFAULT_FILE_PROVIDER;
+ }
+
/**
* 关闭
* @param descriptor
diff --git a/app-updater/src/main/java/com/king/app/updater/util/LogUtils.java b/app-updater/src/main/java/com/king/app/updater/util/LogUtils.java
new file mode 100644
index 0000000..3a1ad2e
--- /dev/null
+++ b/app-updater/src/main/java/com/king/app/updater/util/LogUtils.java
@@ -0,0 +1,316 @@
+/*
+ Copyright © 2015, 2016 Jenly Yu Jenly
+
+ Licensed under the Apache License, Version 2.0 (the "License");
+ you may not use this file except in compliance with the License.
+ You may obtain a copy of the License at
+
+ http://www.apache.org/licenses/LICENSE-2.0
+
+ Unless required by applicable law or agreed to in writing, software
+ distributed under the License is distributed on an "AS IS" BASIS,
+ WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ See the License for the specific language governing permissions and
+ limitations under the License.
+
+ */
+package com.king.app.updater.util;
+
+
+import android.util.Log;
+
+import java.util.Locale;
+
+/**
+ * @author Jenly Jenly
+ */
+public class LogUtils {
+
+ public static final String TAG = "AppUpdater";
+
+ public static final String VERTICAL = "|";
+
+ /** 是否显示Log日志 */
+ private static boolean isShowLog = true;
+
+ /** Log日志优先权 */
+ private static int priority = 1;
+
+ /**
+ * Priority constant for the println method;use System.out.println
+ */
+ public static final int PRINTLN = 1;
+
+ /**
+ * Priority constant for the println method; use Log.v.
+ */
+ public static final int VERBOSE = 2;
+
+ /**
+ * Priority constant for the println method; use Log.d.
+ */
+ public static final int DEBUG = 3;
+
+ /**
+ * Priority constant for the println method; use Log.i.
+ */
+ public static final int INFO = 4;
+
+ /**
+ * Priority constant for the println method; use Log.w.
+ */
+ public static final int WARN = 5;
+
+ /**
+ * Priority constant for the println method; use Log.e.
+ */
+ public static final int ERROR = 6;
+
+ /**
+ * Priority constant for the println method.use Log.wtf.
+ */
+ public static final int ASSERT = 7;
+
+ public static final String TAG_FORMAT = "%s.%s(%s:%d)";
+
+ private LogUtils(){
+ throw new AssertionError();
+ }
+
+ public static void setShowLog(boolean isShowLog) {
+
+ LogUtils.isShowLog = isShowLog;
+ }
+
+ public static boolean isShowLog() {
+
+ return isShowLog;
+ }
+
+ public static int getPriority() {
+
+ return priority;
+ }
+
+ public static void setPriority(int priority) {
+
+ LogUtils.priority = priority;
+ }
+
+ /**
+ * 根据堆栈生成TAG
+ * @return TAG|className.methodName(fileName:lineNumber)
+ */
+ private static String generateTag(StackTraceElement caller) {
+ String tag = TAG_FORMAT;
+ String callerClazzName = caller.getClassName();
+ callerClazzName = callerClazzName.substring(callerClazzName.lastIndexOf(".") + 1);
+ tag = String.format(Locale.getDefault(),tag,callerClazzName, caller.getMethodName(),caller.getFileName(),caller.getLineNumber());
+ return new StringBuilder().append(TAG).append(VERTICAL).append(tag).toString();
+ }
+
+ /**
+ * 获取堆栈
+ * @param n
+ * n=0 VMStack
+ * n=1 Thread
+ * n=3 CurrentStack
+ * n=4 CallerStack
+ * ...
+ * @return
+ */
+ public static StackTraceElement getStackTraceElement(int n) {
+ return Thread.currentThread().getStackTrace()[n];
+ }
+
+ /**
+ * 获取调用方的堆栈TAG
+ * @return
+ */
+ private static String getCallerStackLogTag(){
+ return generateTag(getStackTraceElement(5));
+ }
+
+ /**
+ *
+ * @param t
+ * @return
+ */
+ private static String getStackTraceString(Throwable t){
+ return Log.getStackTraceString(t);
+ }
+
+ // -----------------------------------Log.v
+
+ /**
+ * Log.v
+ * @param msg
+ */
+ public static void v(String msg) {
+ if (isShowLog && priority <= VERBOSE)
+ Log.v(getCallerStackLogTag(), String.valueOf(msg));
+
+ }
+
+ public static void v(Throwable t) {
+ if (isShowLog && priority <= VERBOSE)
+ Log.v(getCallerStackLogTag(), getStackTraceString(t));
+ }
+
+ public static void v(String msg,Throwable t) {
+ if (isShowLog && priority <= VERBOSE)
+ Log.v(getCallerStackLogTag(), String.valueOf(msg), t);
+ }
+
+ // -----------------------------------Log.d
+
+ /**
+ * Log.d
+ * @param msg
+ */
+ public static void d(String msg) {
+ if (isShowLog && priority <= DEBUG)
+ Log.d(getCallerStackLogTag(), String.valueOf(msg));
+ }
+
+ public static void d(Throwable t) {
+ if (isShowLog && priority <= DEBUG)
+ Log.d(getCallerStackLogTag(), getStackTraceString(t));
+ }
+
+ public static void d(String msg,Throwable t) {
+ if (isShowLog && priority <= DEBUG)
+ Log.d(getCallerStackLogTag(), String.valueOf(msg), t);
+ }
+
+ // -----------------------------------Log.i
+
+ /**
+ * Log.i
+ * @param msg
+ */
+ public static void i(String msg) {
+ if (isShowLog && priority <= INFO)
+ Log.i(getCallerStackLogTag(), String.valueOf(msg));
+ }
+
+ public static void i(Throwable t) {
+ if (isShowLog && priority <= INFO)
+ Log.i(getCallerStackLogTag(), getStackTraceString(t));
+ }
+
+ public static void i(String msg,Throwable t) {
+ if (isShowLog && priority <= INFO)
+ Log.i(getCallerStackLogTag(), String.valueOf(msg), t);
+ }
+
+ // -----------------------------------Log.w
+
+ /**
+ * Log.w
+ * @param msg
+ */
+ public static void w(String msg) {
+ if (isShowLog && priority <= WARN)
+ Log.w(getCallerStackLogTag(), String.valueOf(msg));
+ }
+
+ public static void w(Throwable t) {
+ if (isShowLog && priority <= WARN)
+ Log.w(getCallerStackLogTag(), getStackTraceString(t));
+ }
+
+ public static void w(String msg,Throwable t) {
+ if (isShowLog && priority <= WARN)
+ Log.w(getCallerStackLogTag(), String.valueOf(msg), t);
+ }
+
+ // -----------------------------------Log.e
+
+ /**
+ * Log.e
+ * @param msg
+ */
+ public static void e(String msg) {
+ if (isShowLog && priority <= ERROR)
+ Log.e(getCallerStackLogTag(), String.valueOf(msg));
+ }
+
+ public static void e(Throwable t) {
+ if (isShowLog && priority <= ERROR)
+ Log.e(getCallerStackLogTag(), getStackTraceString(t));
+ }
+
+ public static void e(String msg,Throwable t) {
+ if (isShowLog && priority <= ERROR)
+ Log.e(getCallerStackLogTag(), String.valueOf(msg), t);
+ }
+
+ // -----------------------------------Log.wtf
+
+ /**
+ * Log.wtf
+ * @param msg
+ */
+ public static void wtf(String msg) {
+ if (isShowLog && priority <= ASSERT)
+ Log.wtf(getCallerStackLogTag(), String.valueOf(msg));
+ }
+
+ public static void wtf(Throwable t) {
+ if (isShowLog && priority <= ASSERT)
+ Log.wtf(getCallerStackLogTag(), getStackTraceString(t));
+ }
+
+ public static void wtf(String msg,Throwable t) {
+ if (isShowLog && priority <= ASSERT)
+ Log.wtf(getCallerStackLogTag(), String.valueOf(msg), t);
+ }
+
+ // -----------------------------------System.out.print
+
+ /**
+ * System.out.print
+ *
+ * @param msg
+ */
+ public static void print(String msg) {
+ if (isShowLog && priority <= PRINTLN)
+ System.out.print(msg);
+ }
+
+ public static void print(Object obj) {
+ if (isShowLog && priority <= PRINTLN)
+ System.out.print(obj);
+ }
+
+ // -----------------------------------System.out.printf
+
+ /**
+ * System.out.printf
+ *
+ * @param msg
+ */
+ public static void printf(String msg) {
+ if (isShowLog && priority <= PRINTLN)
+ System.out.printf(msg);
+ }
+
+ // -----------------------------------System.out.println
+
+ /**
+ * System.out.println
+ *
+ * @param msg
+ */
+ public static void println(String msg) {
+ if (isShowLog && priority <= PRINTLN)
+ System.out.println(msg);
+ }
+
+ public static void println(Object obj) {
+ if (isShowLog && priority <= PRINTLN)
+ System.out.println(obj);
+ }
+
+}
diff --git a/app-updater/src/main/java/com/king/app/updater/util/NotificationUtils.java b/app-updater/src/main/java/com/king/app/updater/util/NotificationUtils.java
index 89a5c53..e7a394e 100644
--- a/app-updater/src/main/java/com/king/app/updater/util/NotificationUtils.java
+++ b/app-updater/src/main/java/com/king/app/updater/util/NotificationUtils.java
@@ -53,7 +53,7 @@ public class NotificationUtils {
if(isCancelDownload){
Intent intent = new Intent(context, DownloadService.class);
intent.putExtra(Constants.KEY_STOP_DOWNLOAD_SERVICE,true);
- PendingIntent deleteIntent = PendingIntent.getService(context, notifyId,intent, PendingIntent.FLAG_CANCEL_CURRENT);
+ PendingIntent deleteIntent = PendingIntent.getService(context, notifyId,intent, getPendingIntentFlags(PendingIntent.FLAG_CANCEL_CURRENT));
builder.setDeleteIntent(deleteIntent);
}
@@ -83,7 +83,7 @@ public class NotificationUtils {
if(isCancelDownload){
Intent intent = new Intent(context, DownloadService.class);
intent.putExtra(Constants.KEY_STOP_DOWNLOAD_SERVICE,true);
- PendingIntent deleteIntent = PendingIntent.getService(context, notifyId,intent, PendingIntent.FLAG_CANCEL_CURRENT);
+ PendingIntent deleteIntent = PendingIntent.getService(context, notifyId, intent, getPendingIntentFlags(PendingIntent.FLAG_CANCEL_CURRENT));
builder.setDeleteIntent(deleteIntent);
}
@@ -112,7 +112,7 @@ public class NotificationUtils {
NotificationCompat.Builder builder = buildNotification(context,channelId,icon,title,content);
builder.setAutoCancel(true);
Intent intent = AppUtils.getInstallIntent(context,file,authority);
- PendingIntent clickIntent = PendingIntent.getActivity(context, notifyId,intent, PendingIntent.FLAG_UPDATE_CURRENT);
+ PendingIntent clickIntent = PendingIntent.getActivity(context, notifyId, intent, getPendingIntentFlags(PendingIntent.FLAG_UPDATE_CURRENT));
builder.setContentIntent(clickIntent);
Notification notification = builder.build();
notification.flags = Notification.FLAG_AUTO_CANCEL;
@@ -133,14 +133,15 @@ public class NotificationUtils {
public static void showErrorNotification(Context context, int notifyId, String channelId, @DrawableRes int icon, CharSequence title, CharSequence content, boolean isReDownload, UpdateConfig config){
NotificationCompat.Builder builder = buildNotification(context,channelId,icon,title,content);
builder.setAutoCancel(true);
- if(isReDownload){//重新下载
- Intent intent = new Intent(context, DownloadService.class);
+ int flag = getPendingIntentFlags(PendingIntent.FLAG_UPDATE_CURRENT);
+ if(isReDownload){// 重新下载
+ Intent intent = new Intent(context, DownloadService.class);
intent.putExtra(Constants.KEY_RE_DOWNLOAD,true);
intent.putExtra(Constants.KEY_UPDATE_CONFIG,config);
- PendingIntent clickIntent = PendingIntent.getService(context, notifyId,intent, PendingIntent.FLAG_UPDATE_CURRENT);
+ PendingIntent clickIntent = PendingIntent.getService(context, notifyId,intent, flag);
builder.setContentIntent(clickIntent);
}else{
- PendingIntent clickIntent = PendingIntent.getService(context, notifyId,new Intent(), PendingIntent.FLAG_UPDATE_CURRENT);
+ PendingIntent clickIntent = PendingIntent.getService(context, notifyId, new Intent(), flag);
builder.setContentIntent(clickIntent);
}
@@ -229,7 +230,7 @@ public class NotificationUtils {
builder.setContentText(content);
builder.setOngoing(true);
- if(progress!= Constants.NONE && size!=Constants.NONE){
+ if(progress != Constants.NONE && size != Constants.NONE){
builder.setProgress(size,progress,false);
}
@@ -245,4 +246,15 @@ public class NotificationUtils {
getNotificationManager(context).notify(id,notification);
}
+ /**
+ * 获取 PendingIntent 的 flags
+ * @param flag
+ * @return
+ */
+ private static int getPendingIntentFlags(int flag){
+ if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.M) {
+ return flag | PendingIntent.FLAG_IMMUTABLE;
+ }
+ return flag;
+ }
}
diff --git a/app-updater/src/main/java/com/king/app/updater/util/PermissionUtils.java b/app-updater/src/main/java/com/king/app/updater/util/PermissionUtils.java
index cd45154..2f4fd29 100644
--- a/app-updater/src/main/java/com/king/app/updater/util/PermissionUtils.java
+++ b/app-updater/src/main/java/com/king/app/updater/util/PermissionUtils.java
@@ -20,51 +20,49 @@ import androidx.core.app.ActivityCompat;
*/
public final class PermissionUtils {
- private static String[] PERMISSIONS_STORAGE = {
- Manifest.permission.READ_EXTERNAL_STORAGE,
- Manifest.permission.WRITE_EXTERNAL_STORAGE,
- Manifest.permission.READ_PHONE_STATE};
-
- private PermissionUtils(){
+ private PermissionUtils() {
throw new AssertionError();
}
/**
* 校验权限
+ *
* @param activity
* @param requestCode
* @return
*/
- public static boolean verifyReadAndWritePermissions(@NonNull Activity activity,int requestCode){
-
- int readResult = checkPermission(activity,Manifest.permission.READ_EXTERNAL_STORAGE);
- int writeResult = checkPermission(activity,Manifest.permission.WRITE_EXTERNAL_STORAGE);
- int readPhoneState = checkPermission(activity,Manifest.permission.READ_PHONE_STATE);
- if(readResult != PackageManager.PERMISSION_GRANTED || writeResult != PackageManager.PERMISSION_GRANTED || readPhoneState != PackageManager.PERMISSION_GRANTED){
- ActivityCompat.requestPermissions(activity,PERMISSIONS_STORAGE,requestCode);
- return false;
+ public static boolean verifyReadAndWritePermissions(@NonNull Activity activity, int requestCode) {
+ if(Build.VERSION.SDK_INT >= Build.VERSION_CODES.M){
+ int readResult = checkPermission(activity, Manifest.permission.READ_EXTERNAL_STORAGE);
+ int writeResult = checkPermission(activity, Manifest.permission.WRITE_EXTERNAL_STORAGE);
+ if (readResult != PackageManager.PERMISSION_GRANTED || writeResult != PackageManager.PERMISSION_GRANTED) {
+ ActivityCompat.requestPermissions(activity, new String[]{
+ Manifest.permission.READ_EXTERNAL_STORAGE,
+ Manifest.permission.WRITE_EXTERNAL_STORAGE}, requestCode);
+ return false;
+ }
}
return true;
}
- public static int checkPermission(@NonNull Activity activity,@NonNull String permission){
- return ActivityCompat.checkSelfPermission(activity,permission);
+ public static int checkPermission(@NonNull Activity activity, @NonNull String permission) {
+ return ActivityCompat.checkSelfPermission(activity, permission);
}
/**
* 获取通知权限
+ *
* @param context
*/
public static boolean isNotificationEnabled(Context context) {
-
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.O) {
- NotificationManager notificationManager = (NotificationManager)context.getSystemService(Context.NOTIFICATION_SERVICE);
+ NotificationManager notificationManager = (NotificationManager) context.getSystemService(Context.NOTIFICATION_SERVICE);
if (notificationManager.getImportance() == NotificationManager.IMPORTANCE_NONE) {
return false;
}
}
- if(Build.VERSION.SDK_INT >= Build.VERSION_CODES.KITKAT){
+ if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.KITKAT) {
String CHECK_OP_NO_THROW = "checkOpNoThrow";
String OP_POST_NOTIFICATION = "OP_POST_NOTIFICATION";
diff --git a/app-updater/src/main/java/com/king/app/updater/util/SSLSocketFactoryUtils.java b/app-updater/src/main/java/com/king/app/updater/util/SSLSocketFactoryUtils.java
index 840d084..f4927b6 100644
--- a/app-updater/src/main/java/com/king/app/updater/util/SSLSocketFactoryUtils.java
+++ b/app-updater/src/main/java/com/king/app/updater/util/SSLSocketFactoryUtils.java
@@ -1,17 +1,18 @@
package com.king.app.updater.util;
import android.content.Context;
+import android.text.TextUtils;
+
import androidx.annotation.RawRes;
import java.io.InputStream;
-import java.security.KeyManagementException;
import java.security.KeyStore;
-import java.security.NoSuchAlgorithmException;
import java.security.SecureRandom;
import java.security.cert.Certificate;
import java.security.cert.CertificateException;
import java.security.cert.CertificateFactory;
import java.security.cert.X509Certificate;
+import java.util.Arrays;
import javax.net.ssl.HostnameVerifier;
import javax.net.ssl.SSLContext;
@@ -27,7 +28,9 @@ import javax.net.ssl.X509TrustManager;
*/
public final class SSLSocketFactoryUtils {
- private SSLSocketFactoryUtils(){
+ private static final String[] VERIFY_HOST_NAME = new String[]{};
+
+ private SSLSocketFactoryUtils() {
throw new AssertionError();
}
@@ -35,7 +38,7 @@ public final class SSLSocketFactoryUtils {
SSLSocketFactory sslSocketFactory = null;
try {
SSLContext sslContext = SSLContext.getInstance("TLS");
- sslContext.init(null, new TrustManager[]{createTrustAllManager()}, new SecureRandom());
+ sslContext.init(null, getTrustAllManager(), new SecureRandom());
sslSocketFactory = sslContext.getSocketFactory();
} catch (Exception e) {
@@ -46,7 +49,7 @@ public final class SSLSocketFactoryUtils {
public static X509TrustManager createTrustAllManager() {
X509TrustManager tm = null;
try {
- tm = new X509TrustManager() {
+ tm = new X509TrustManager() {
public void checkClientTrusted(X509Certificate[] chain, String authType)
throws CertificateException {
//do nothing
@@ -67,66 +70,55 @@ public final class SSLSocketFactoryUtils {
return tm;
}
- public static TrustAllHostnameVerifier createTrustAllHostnameVerifier(){
+ public static TrustAllHostnameVerifier createTrustAllHostnameVerifier() {
return new TrustAllHostnameVerifier();
}
public static class TrustAllHostnameVerifier implements HostnameVerifier {
@Override
public boolean verify(String hostname, SSLSession session) {
- return true;
+ if (TextUtils.isEmpty(hostname)) {
+ return false;
+ }
+ return !Arrays.asList(VERIFY_HOST_NAME).contains(hostname);
}
}
/**
- *
* @param context
* @param keyServerStoreID
* @return
*/
- public static SSLSocketFactory createSSLSocketFactory(Context context,@RawRes int keyServerStoreID){
+ public static SSLSocketFactory createSSLSocketFactory(Context context, @RawRes int keyServerStoreID) {
InputStream trustStream = context.getResources().openRawResource(keyServerStoreID);
return createSSLSocketFactory(trustStream);
}
/**
- *
* @param certificates
* @return
*/
public static SSLSocketFactory createSSLSocketFactory(InputStream... certificates) {
- SSLSocketFactory mSSLSocketFactory = null;
- if(mSSLSocketFactory==null){
+ SSLSocketFactory sSLSocketFactory = null;
+ if (sSLSocketFactory == null) {
synchronized (SSLSocketFactoryUtils.class) {
- if(mSSLSocketFactory==null){
-
- SSLContext sslContext = null;
+ if (sSLSocketFactory == null) {
try {
- sslContext = SSLContext.getInstance("TLS");
- } catch (NoSuchAlgorithmException e) {
+ SSLContext sslContext = SSLContext.getInstance("TLS");
+ sslContext.init(null, getTrustManager(certificates), new SecureRandom());
+ sSLSocketFactory = sslContext.getSocketFactory();
+ } catch (Exception e) {
e.printStackTrace();
- return null;
}
- //获得服务器端证书
- TrustManager[] turstManager = getTrustManager(certificates);
-
- //初始化ssl证书库
- try {
- sslContext.init(null,turstManager,new SecureRandom());
- } catch (KeyManagementException e) {
- e.printStackTrace();
- }
-
- //获得sslSocketFactory
- mSSLSocketFactory = sslContext.getSocketFactory();
}
}
}
- return mSSLSocketFactory;
+ return sSLSocketFactory;
}
/**
* 获得指定流中的服务器端证书库
+ *
* @param certificates
* @return
*/
@@ -134,7 +126,7 @@ public final class SSLSocketFactoryUtils {
try {
CertificateFactory certificateFactory = CertificateFactory.getInstance("X.509");
KeyStore keyStore = KeyStore.getInstance(KeyStore.getDefaultType());
- keyStore.load(null,null);
+ keyStore.load(null, null);
int index = 0;
for (InputStream certificate : certificates) {
if (certificate == null) {
@@ -143,12 +135,12 @@ public final class SSLSocketFactoryUtils {
Certificate certificate1;
try {
certificate1 = certificateFactory.generateCertificate(certificate);
- }finally {
+ } finally {
certificate.close();
}
String certificateAlias = Integer.toString(index++);
- keyStore.setCertificateEntry(certificateAlias,certificate1);
+ keyStore.setCertificateEntry(certificateAlias, certificate1);
}
TrustManagerFactory trustManagerFactory = TrustManagerFactory.getInstance(TrustManagerFactory
@@ -167,9 +159,9 @@ public final class SSLSocketFactoryUtils {
/**
* 获得信任所有服务器端证书库
- * */
+ */
public static TrustManager[] getTrustAllManager() {
- return new X509TrustManager[] {createTrustAllManager()};
+ return new TrustManager[]{createTrustAllManager()};
}
diff --git a/app/release/app-release.apk b/app/release/app-release.apk
index b116e86..741f1a5 100644
Binary files a/app/release/app-release.apk and b/app/release/app-release.apk differ
diff --git a/app/release/output-metadata.json b/app/release/output-metadata.json
index 777296f..a0992d1 100644
--- a/app/release/output-metadata.json
+++ b/app/release/output-metadata.json
@@ -10,8 +10,8 @@
{
"type": "SINGLE",
"filters": [],
- "versionCode": 21,
- "versionName": "1.1.2",
+ "versionCode": 22,
+ "versionName": "1.1.3",
"outputFile": "app-release.apk"
}
]
diff --git a/app/src/main/AndroidManifest.xml b/app/src/main/AndroidManifest.xml
index 8e0b0f8..42ae627 100644
--- a/app/src/main/AndroidManifest.xml
+++ b/app/src/main/AndroidManifest.xml
@@ -2,6 +2,9 @@
+
+
+