手写Service后台下载app——跳出DownloadManager系统7

前言
之前项目中有关app的现在和更新相关工具类一直用的是系统下载管理功能 。如果随着系统的不断提升再加上开源性 手机厂家
对此作恶部分改动 。导致一些系统自带的工具类出现异常情况 。
华为P9
华为P9/P9 Plus上线,你的APP准备好了吗?
新机入手后,MTC率先从应用市场随机下载部分APP做基于P9/P9 Plus的兼容性测试,在脚本跑完之后,我们发现部分App会出现Crash、ANR的问题 。在此跟开发小伙伴们分享下产生此类问题的原因,开发小伙伴们在App开发过程中多加注意,避免此类问题的产生 。
华为P9使用该 华为P9在7.1的时候,利用系统工具类下载时就出现异常——在下载过程中竟突然自动消失!
怀疑这个应该是系统和华为P9不兼容导致的一个的bug 。
大家都知道,老板不懂代码,有时候出现的问题还不属于你的问题 。在其他手机上好使,部分手机就出现问题 。只要有一款手机出现一个问题就认为你的程序有问题 。

手写Service后台下载app——跳出DownloadManager系统7

文章插图
这是最蛋疼的 。so,问题来了,谁让你是安卓程序员呢
哈哈,抱怨是没有用的 。有问题还是要解决的 。
1.首先是要判断是6.0权限
/** * 请求运行时权限 * eg: */public void requestRuntimePermission(QuestPermissionListener questPermissionListener, String... permissions){BasePermisitionActivity.requestRuntimePermission(permissions,questPermissionListener);}.......
6.0运行权限请参考: .0运行时权限完美封装
下载工具类:
/*** 类功能描述:
* 自定义Service后台下载app——跳出DownloadManager系统下载之坑
* 修改人:yuyahao* @version 1.0
修改时间:
修改备注:
*/public class UpdateService extends Service {public static final String TAG ="ServiceDownLoadApp";public static final String ACTION = "me.shenfan.UPDATE_APP";public static final String STATUS = "status";public static final String PROGRESS = "progress";public static boolean DEBUG = true;//下载大小通知频率public static final int UPDATE_NUMBER_SIZE = 1;public static final int DEFAULT_RES_ID = -1;public static final int UPDATE_PROGRESS_STATUS = 0;public static final int UPDATE_ERROR_STATUS = -1;public static final int UPDATE_SUCCESS_STATUS = 1;//paramsprivate static final String URL = "downloadUrl";private static final String ICO_RES_ID = "icoResId";private static final String ICO_SMALL_RES_ID = "icoSmallResId";private static final String UPDATE_PROGRESS = "updateProgress";private static final String STORE_DIR = "storeDir";private static final String DOWNLOAD_NOTIFICATION_FLAG = "downloadNotificationFlag";private static final String DOWNLOAD_SUCCESS_NOTIFICATION_FLAG = "downloadSuccessNotificationFlag";private static final String DOWNLOAD_ERROR_NOTIFICATION_FLAG = "downloadErrorNotificationFlag";private static final String IS_SEND_BROADCAST = "isSendBroadcast";private String downloadUrl;private int icoResId;//default app icoprivate int icoSmallResId;private int updateProgress;//update notification progress when it add numberprivate staticString storeDir;//default sdcard/Android/package/updateprivate int downloadNotificationFlag;private int downloadSuccessNotificationFlag;private int downloadErrorNotificationFlag;private boolean isSendBroadcast;private UpdateProgressListener updateProgressListener;private LocalBinder localBinder = new LocalBinder();/*** Class used for the client Binder.*/public class LocalBinder extends Binder{/*** set update progress call back* @param listener*/public void setUpdateProgressListener(UpdateProgressListener listener){UpdateService.this.setUpdateProgressListener(listener);}}private boolean startDownload;//开始下载private int lastProgressNumber;private NotificationCompat.Builder builder;private NotificationManager manager;private int notifyId;private String appName;private LocalBroadcastManager localBroadcastManager;private Intent localIntent;private DownloadApk downloadApkTask;/*** whether debug*/public static void debug(){DEBUG = true;}/*** 点击通知栏去进行安装* @param path* @return*/private static Intent installIntent(String path){Uri uri = Uri.fromFile(new File(path));Intent installIntent = new Intent(Intent.ACTION_VIEW);installIntent.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK);installIntent.setDataAndType(uri, "application/vnd.android.package-archive");return installIntent;}/*** 通过浏览器进行下载* @param downloadUrl* @return*/private static Intent webLauncher(String downloadUrl){Uri download = Uri.parse(downloadUrl);Intent intent = new Intent(Intent.ACTION_VIEW, download);intent.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK);return intent;}/*** 通过URL获取要下载的apk的前缀没弄过* @param downloadUrl* @return*/private static String getSaveFileName(String downloadUrl) {if (downloadUrl == null || TextUtils.isEmpty(downloadUrl)) {return "noName.apk";}return downloadUrl.substring(downloadUrl.lastIndexOf("/"));}/*** 来设置要下载apk储存的文件夹* @param service* @return*/private static File getDownloadDir(UpdateService service){File downloadDir = null;if (Environment.getExternalStorageState().equals(Environment.MEDIA_MOUNTED)) {if (service.storeDir != null){downloadDir = new File(Environment.getExternalStorageDirectory(), service.storeDir);}else {downloadDir = new File(service.getExternalCacheDir(), "update");}} else {downloadDir = new File(service.getCacheDir(), "update");}if (!downloadDir.exists()) {downloadDir.mkdirs();}return downloadDir;}@Overridepublic void onCreate() {super.onCreate();appName = getApplicationName();}@Overridepublic int onStartCommand(Intent intent, int flags, int startId) {if (!startDownload && intent != null){startDownload = true;downloadUrl = intent.getStringExtra(URL);icoResId = intent.getIntExtra(ICO_RES_ID, DEFAULT_RES_ID);icoSmallResId = intent.getIntExtra(ICO_SMALL_RES_ID, DEFAULT_RES_ID);storeDir = intent.getStringExtra(STORE_DIR);updateProgress = intent.getIntExtra(UPDATE_PROGRESS, UPDATE_NUMBER_SIZE);downloadNotificationFlag = intent.getIntExtra(DOWNLOAD_NOTIFICATION_FLAG, 0);downloadErrorNotificationFlag = intent.getIntExtra(DOWNLOAD_ERROR_NOTIFICATION_FLAG, 0);downloadSuccessNotificationFlag = intent.getIntExtra(DOWNLOAD_SUCCESS_NOTIFICATION_FLAG, 0);isSendBroadcast = intent.getBooleanExtra(IS_SEND_BROADCAST, false);if (DEBUG){LogUtil.e(TAG, "downloadUrl: " + downloadUrl);LogUtil.e(TAG, "icoResId: " + icoResId);LogUtil.e(TAG, "icoSmallResId: " + icoSmallResId);LogUtil.e(TAG, "storeDir: " + storeDir);LogUtil.e(TAG, "updateProgress: " + updateProgress);LogUtil.e(TAG, "downloadNotificationFlag: " + downloadNotificationFlag);LogUtil.e(TAG, "downloadErrorNotificationFlag: " + downloadErrorNotificationFlag);LogUtil.e(TAG, "downloadSuccessNotificationFlag: " + downloadSuccessNotificationFlag);LogUtil.e(TAG, "isSendBroadcast: " + isSendBroadcast);}notifyId = startId;buildNotification();buildBroadcast();downloadApkTask = new DownloadApk(this);downloadApkTask.execute(downloadUrl);}return super.onStartCommand(intent, flags, startId);}@Nullable@Overridepublic IBinder onBind(Intent intent) {return localBinder;}@Overridepublic boolean onUnbind(Intent intent) {return true;}public void setUpdateProgressListener(UpdateProgressListener updateProgressListener) {this.updateProgressListener = updateProgressListener;}@Overridepublic void onDestroy() {if (downloadApkTask != null){downloadApkTask.cancel(true);}if (updateProgressListener != null){updateProgressListener = null;}localIntent = null;builder = null;super.onDestroy();}/*** 获取当前的应用名* @return*/public String getApplicationName() {PackageManager packageManager = null;ApplicationInfo applicationInfo = null;try {packageManager = getApplicationContext().getPackageManager();applicationInfo = packageManager.getApplicationInfo(getPackageName(), 0);} catch (PackageManager.NameNotFoundException e) {applicationInfo = null;}String applicationName =(String) packageManager.getApplicationLabel(applicationInfo);return applicationName;}private void buildBroadcast(){if (!isSendBroadcast){return;}localBroadcastManager = LocalBroadcastManager.getInstance(this);localIntent = new Intent(ACTION);}/*** 发送广播* @param status* @param progress*/private void sendLocalBroadcast(int status, int progress){if (!isSendBroadcast || localIntent == null){return;}localIntent.putExtra(STATUS, status);localIntent.putExtra(PROGRESS, progress);localBroadcastManager.sendBroadcast(localIntent);}/*** 环形通知安*/private void buildNotification(){manager = (NotificationManager) getSystemService(NOTIFICATION_SERVICE);builder = new NotificationCompat.Builder(this);builder.setContentTitle(getString(R.string.update_app_model_prepare, appName)).setWhen(System.currentTimeMillis()).setProgress(100, 1, false).setSmallIcon(icoSmallResId).setLargeIcon(BitmapFactory.decodeResource(getResources(), icoResId)).setDefaults(downloadNotificationFlag);manager.notify(notifyId, builder.build());}/*** 开始 下载*/private void start(){builder.setContentTitle(appName);builder.setContentText(getString(R.string.update_app_model_prepare, 1));manager.notify(notifyId, builder.build());sendLocalBroadcast(UPDATE_PROGRESS_STATUS, 1);if (updateProgressListener != null){updateProgressListener.start();}}/**** 通知进度条,进度条* 大小范围(1~100)*/private void update(int progress){if (progress - lastProgressNumber > updateProgress){lastProgressNumber = progress;builder.setProgress(100, progress, false);builder.setContentText(getString(R.string.update_app_model_progress, progress, "%"));manager.notify(notifyId, builder.build());sendLocalBroadcast(UPDATE_PROGRESS_STATUS, progress);if (updateProgressListener != null){updateProgressListener.update(progress);}}}/*** 下载成功的回调* @param path*/private void success(String path) {builder.setProgress(0, 0, false);builder.setContentText(getString(R.string.update_app_model_success));GetToast.useString(this,"asdfasdf");manager.cancel(0);if(FileHelper.checkFileIsExists(path)){Intent i = installIntent(path);PendingIntent intent = PendingIntent.getActivity(this, 0, i, PendingIntent.FLAG_UPDATE_CURRENT);builder.setContentIntent(intent).setAutoCancel(true)//用户点击就自动消失.setDefaults(downloadSuccessNotificationFlag);Notification n = builder.build();n.contentIntent = intent;manager.notify(notifyId, n);if (updateProgressListener != null){updateProgressListener.success();}startActivity(i);IntentFilter filter = new IntentFilter();}else{DataCleanManager.deleteFilesByDirectory2(storeDir);}stopSelf();}/*** 清除本地文件*/public static void deleteFilesByDirectory(){DataCleanManager.deleteFilesByDirectory2(storeDir);}/*** 下载失败通知浏览器下载回调*/private void error(){Intent i = webLauncher(downloadUrl);PendingIntent intent = PendingIntent.getActivity(this, 0, i,PendingIntent.FLAG_UPDATE_CURRENT);builder.setContentText(getString(R.string.update_app_model_error));builder.setContentIntent(intent);builder.setProgress(0, 0, false);builder.setDefaults(downloadErrorNotificationFlag);Notification n = builder.build();n.contentIntent = intent;manager.notify(notifyId, n);sendLocalBroadcast(UPDATE_ERROR_STATUS, -1);if (updateProgressListener != null){updateProgressListener.error();}stopSelf();}/*** 下载异步任务*/private static class DownloadApk extends AsyncTask{private WeakReference