纯干货,下面开始讲解
1.0 下载器,你需要一个下载器从服务器下载更新包:
调用方法:UpdateManager updateManager = new UpdateManager(context);
updateManager.down("https://myclod-1259560102.cos.ap-nanjing.myqcloud.com/trainApp.apk")
"
public class UpdateManager {
private Disposable downDisposable;
private Context activity;
private ProgressBar progressBar;
private TextView textView4;
private Button upgrade;
private long downloadLength = 0;
private long contentLength = 0;
private String[] PERMISSIONS_STORAGE = {
Manifest.permission.READ_EXTERNAL_STORAGE,
Manifest.permission.WRITE_EXTERNAL_STORAGE};
private String bigFilePath;
public UpdateManager(Context context) {
this.activity = context;
}
public void test(String url) {
down(url);
// down("https://myclod-1259560102.cos.ap-nanjing.myqcloud.com/trainApp.apk");
}
public static Activity getCurrentActivity () {
try {
Class activityThreadClass = Class.forName("android.app.ActivityThread");
Object activityThread = activityThreadClass.getMethod("currentActivityThread").invoke(
null);
Field activitiesField = activityThreadClass.getDeclaredField("mActivities");
activitiesField.setAccessible(true);
Map activities = (Map) activitiesField.get(activityThread);
for (Object activityRecord : activities.values()) {
Class activityRecordClass = activityRecord.getClass();
Field pausedField = activityRecordClass.getDeclaredField("paused");
pausedField.setAccessible(true);
if (!pausedField.getBoolean(activityRecord)) {
Field activityField = activityRecordClass.getDeclaredField("activity");
activityField.setAccessible(true);
Activity activity = (Activity) activityField.get(activityRecord);
return activity;
}
}
} catch (ClassNotFoundException e) {
e.printStackTrace();
} catch (InvocationTargetException e) {
e.printStackTrace();
} catch (NoSuchMethodException e) {
e.printStackTrace();
} catch (NoSuchFieldException e) {
e.printStackTrace();
} catch (IllegalAccessException e) {
e.printStackTrace();
}
return null;
}
private void down(final String downloadUrl) {
downApk(downloadUrl);
// Observable.create(new ObservableOnSubscribe<Integer>() {
// @Override
// public void subscribe(ObservableEmitter<Integer> emitter) throws Exception {
// downApk(downloadUrl, emitter);
// }
// }).subscribeOn(Schedulers.io())// 将被观察者切换到子线程
// .observeOn(AndroidSchedulers.mainThread())// 将观察者切换到主线程
// .subscribe(new Observer<Integer>() {
//
// @Override
// public void onSubscribe(Disposable d) {
// downDisposable = d;
// }
//
// @Override
// public void onNext(Integer result) {
// System.out.println("恶性" + result);
// //设置ProgressDialog 进度条进度
// // progressBar.setProgress(result);
// // textView4.setText(result+"%");
// }
//
// @Override
// public void onError(Throwable e) {
// // Toast.makeText(activity.getApplication(), "网络异常!请重新下载!", Toast.LENGTH_SHORT).show();
// //upgrade.setEnabled(true);
// }
//
// @Override
// public void onComplete() {
// // upgrade.setEnabled(true);
//