在android 7.0使用的是同一套框架却没有问题?
然后通过adb命令抓取一下异常发现
代码语言:txt复制12-18 19:21:32.665 4804 5604 W InstallStaging: java.lang.SecurityException: Permission Denial: reading android.support.v4.content.FileProvider uri content://com.***.***.update_app.file_provider/download/update/***.apk from pid=4804, uid=1000 requires the provider be exported, or grantUriPermission()代码语言:txt复制12-18 19:21:32.665 4804 5604 W InstallStaging: at android.os.Parcel.createException(Parcel.java:1950)代码语言:txt复制12-18 19:21:32.665 4804 5604 W InstallStaging: at android.os.Parcel.readException(Parcel.java:1918)代码语言:txt复制12-18 19:21:32.665 4804 5604 W InstallStaging: at android.database.DatabaseUtils.readExceptionFromParcel(DatabaseUtils.java:183)代码语言:txt复制12-18 19:21:32.665 4804 5604 W InstallStaging: at android.database.DatabaseUtils.readExceptionWithFileNotFoundExceptionFromParcel(DatabaseUtils.java:146)代码语言:txt复制12-18 19:21:32.665 4804 5604 W InstallStaging: at android.content.ContentProviderProxy.openTypedAssetFile(ContentProviderNative.java:698)代码语言:txt复制12-18 19:21:32.665 4804 5604 W InstallStaging: at android.content.ContentResolver.openTypedAssetFileDescriptor(ContentResolver.java:1459)代码语言:txt复制12-18 19:21:32.665 4804 5604 W InstallStaging: at android.content.ContentResolver.openAssetFileDescriptor(ContentResolver.java:1296)代码语言:txt复制12-18 19:21:32.665 4804 5604 W InstallStaging: at android.content.ContentResolver.openInputStream(ContentResolver.java:1016)代码语言:txt复制12-18 19:21:32.665 4804 5604 W InstallStaging: at com.android.packageinstaller.InstallStaging$StagingAsyncTask.doInBackground(InstallStaging.java:167)代码语言:txt复制12-18 19:21:32.665 4804 5604 W InstallStaging: at com.android.packageinstaller.InstallStaging$StagingAsyncTask.doInBackground(InstallStaging.java:160)代码语言:txt复制12-18 19:21:32.665 4804 5604 W InstallStaging: at android.os.AsyncTask$2.call(AsyncTask.java:333)代码语言:txt复制12-18 19:21:32.665 4804 5604 W InstallStaging: at java.util.concurrent.FutureTask.run(FutureTask.java:266)代码语言:txt复制12-18 19:21:32.665 4804 5604 W InstallStaging: at android.os.AsyncTask$SerialExecutor$1.run(AsyncTask.java:245)代码语言:txt复制12-18 19:21:32.665 4804 5604 W InstallStaging: at java.util.concurrent.ThreadPoolExecutor.runWorker(ThreadPoolExecutor.java:1167)代码语言:txt复制12-18 19:21:32.665 4804 5604 W InstallStaging: at java.util.concurrent.ThreadPoolExecutor$Worker.run(ThreadPoolExecutor.java:641)代码语言:txt复制12-18 19:21:32.665 4804 5604 W InstallStaging: at java.lang.Thread.run(Thread.java:764)代码语言:txt复制private Intent installIntent(Context context, String path) {代码语言:txt复制 Intent intent = new Intent(Intent.ACTION_VIEW);代码语言:txt复制 intent.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK);代码语言:txt复制 intent.addCategory(Intent.CATEGORY_DEFAULT);代码语言:txt复制 String fileProviderAuthority = getFileProviderAuthority(context);代码语言:txt复制 if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.N && null!= fileProviderAuthority) {代码语言:txt复制 Uri fileUri = FileProvider.getUriForFile(context, fileProviderAuthority, new File(path));代码语言:txt复制 intent.setDataAndType(fileUri, "application/vnd.android.package-archive");代码语言:txt复制 intent.addFlags(Intent.FLAG_GRANT_READ_URI_PERMISSION);代码语言:txt复制 } else {代码语言:txt复制 intent.setDataAndType(Uri.fromFile(new File(path)), "application/vnd.android.package-archive");代码语言:txt复制 }代码语言:txt复制 return intent;代码语言:txt复制 }于是我就扒了一下源码对其进行修改
代码语言:txt复制private Intent installIntent(Context context, String path) {代码语言:txt复制 Intent intent = new Intent(Intent.ACTION_VIEW);代码语言:txt复制 intent.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK);代码语言:txt复制 intent.addCategory(Intent.CATEGORY_DEFAULT);代码语言:txt复制 String fileProviderAuthority = getFileProviderAuthority(context);代码语言:txt复制 if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.N && null!= fileProviderAuthority) {代码语言:txt复制 Uri fileUri = FileProvider.getUriForFile(context, fileProviderAuthority, new File(path));代码语言:txt复制 intent.setDataAndType(fileUri, "application/vnd.android.package-archive");代码语言:txt复制 grantUriPermission(getPackageName(), fileUri, Intent.FLAG_GRANT_READ_URI_PERMISSION);代码语言:txt复制 intent.addFlags(Intent.FLAG_GRANT_READ_URI_PERMISSION);代码语言:txt复制 intent.addFlags(Intent.FLAG_GRANT_PERSISTABLE_URI_PERMISSION);代码语言:txt复制 } else {代码语言:txt复制 intent.setDataAndType(Uri.fromFile(new File(path)), "application/vnd.android.package-archive");代码语言:txt复制 }代码语言:txt复制 return intent;代码语言:txt复制 }测试通过,完美安装,没有出现解析失败问题
代码:
代码语言:txt复制<!--AndroidManifest.xml-->代码语言:txt复制 <uses-permission android:name="android.permission.FOREGROUND_SERVICE" />代码语言:txt复制 <uses-permission android:name="android.permission.WRITE_EXTERNAL_STORAGE" />代码语言:txt复制 <uses-permission android:name="android.permission.INTERNET"/>代码语言:txt复制 <provider代码语言:txt复制 android:name="android.support.v4.content.FileProvider"代码语言:txt复制 android:authorities="包名.file_provider"代码语言:txt复制 android:exported="false"代码语言:txt复制 android:grantUriPermissions="true">代码语言:txt复制 <!-- 元数据 -->代码语言:txt复制 <meta-data代码语言:txt复制 android:name="android.support.FILE_PROVIDER_PATHS"代码语言:txt复制 android:resource="@xml/file_paths"代码语言:txt复制 tools:replace="android:resource" />代码语言:txt复制 </provider> 代码语言:txt复制 <service android:name=".UpdateService"/>//从源码下载的升级下载安装apk的服务代码语言:txt复制 <!-- file_paths.xml -->代码语言:txt复制<?xml version="1.0" encoding="utf-8"?>代码语言:txt复制<paths>代码语言:txt复制 <external-path path="." name="download" />代码语言:txt复制 <external-cache-path代码语言:txt复制 name="storage/emulated/0"代码语言:txt复制 path="." />代码语言:txt复制</paths>代码语言:txt复制/**代码语言:txt复制 * Created by Sun on 2020/12/19.
*/
public class UpdateService extends Service {
public static final String TAG = "UpdateService";
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 = false;代码语言:txt复制 //下载大小通知频率代码语言:txt复制 public static final int UPDATE_NUMBER_SIZE = 1;代码语言:txt复制 public static final int DEFAULT_RES_ID = -1;代码语言:txt复制 public static final int UPDATE_PROGRESS_STATUS = 0;代码语言:txt复制 public static final int UPDATE_ERROR_STATUS = -1;代码语言:txt复制 public static final int UPDATE_SUCCESS_STATUS = 1;代码语言:txt复制 //params代码语言:txt复制 private static final String URL = "downloadUrl";代码语言:txt复制 private static final String ICO_RES_ID = "icoResId";代码语言:txt复制 private static final String ICO_SMALL_RES_ID = "icoSmallResId";代码语言:txt复制 private static final String UPDATE_PROGRESS = "updateProgress";代码语言:txt复制 private static final String STORE_DIR = "storeDir";代码语言:txt复制 private static final String DOWNLOAD_NOTIFICATION_FLAG = "downloadNotificationFlag";代码语言:txt复制 private static final String DOWNLOAD_SUCCESS_NOTIFICATION_FLAG = "downloadSuccessNotificationFlag";代码语言:txt复制 private static final String DOWNLOAD_ERROR_NOTIFICATION_FLAG = "downloadErrorNotificationFlag";代码语言:txt复制 private static final String IS_SEND_BROADCAST = "isSendBroadcast";代码语言:txt复制 private String downloadUrl;代码语言:txt复制 private int icoResId; //default app ico代码语言:txt复制 private int icoSmallResId;代码语言:txt复制 private int updateProgress; //update notification progress when it add number代码语言:txt复制 private String storeDir; //default sdcard/Android/package/update代码语言:txt复制 private int downloadNotificationFlag;代码语言:txt复制 private int downloadSuccessNotificationFlag;代码语言:txt复制 private int downloadErrorNotificationFlag;代码语言:txt复制 private boolean isSendBroadcast;代码语言:txt复制 private UpdateProgressListener updateProgressListener;代码语言:txt复制 private LocalBinder localBinder = new LocalBinder();代码语言:txt复制 /**代码语言:txt复制 * 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);
}
}代码语言:txt复制 private boolean startDownload;//开始下载代码语言:txt复制 private int lastProgressNumber;代码语言:txt复制 private NotificationCompat.Builder builder;代码语言:txt复制 private NotificationManager manager;代码语言:txt复制 private int notifyId;代码语言:txt复制 private String appName;代码语言:txt复制 private LocalBroadcastManager localBroadcastManager;代码语言:txt复制 private Intent localIntent;代码语言:txt复制 private DownloadApk downloadApkTask;代码语言:txt复制 /**代码语言:txt复制 * whether debug
*/
public static void debug() {
DEBUG = true;
}代码语言:txt复制 private Intent installIntent(Context context, String path) {代码语言:txt复制 Intent intent = new Intent(Intent.ACTION_VIEW);代码语言:txt复制 intent.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK);代码语言:txt复制 intent.addCategory(Intent.CATEGORY_DEFAULT);代码语言:txt复制 String fileProviderAuthority = getFileProviderAuthority(context);代码语言:txt复制 if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.N && null!= fileProviderAuthority) {代码语言:txt复制 Uri fileUri = FileProvider.getUriForFile(context, fileProviderAuthority, new File(path));代码语言:txt复制 intent.setDataAndType(fileUri, "application/vnd.android.package-archive");代码语言:txt复制 grantUriPermission(getPackageName(), fileUri, Intent.FLAG_GRANT_READ_URI_PERMISSION);代码语言:txt复制 intent.addFlags(Intent.FLAG_GRANT_READ_URI_PERMISSION);代码语言:txt复制 intent.addFlags(Intent.FLAG_GRANT_PERSISTABLE_URI_PERMISSION);代码语言:txt复制 } else {代码语言:txt复制 intent.setDataAndType(Uri.fromFile(new File(path)), "application/vnd.android.package-archive");代码语言:txt复制 }代码语言:txt复制 return intent;代码语言:txt复制 }代码语言:txt复制 /**代码语言:txt复制 * 获取FileProvider的auth
*/
private static String getFileProviderAuthority(Context context) {
try {
for (ProviderInfo provider : context.getPackageManager().getPackageInfo(context.getPackageName(), PackageManager.GET_PROVIDERS).providers) {
if (FileProvider.class.getName().equals(provider.name) && provider.authority.endsWith(".update_app.file_provider")) {
return provider.authority;
}
}
} catch (PackageManager.NameNotFoundException ignore) {
}
return null;
}代码语言:txt复制 private static Intent webLauncher(String downloadUrl) {代码语言:txt复制 Uri download = Uri.parse(downloadUrl);代码语言:txt复制 Intent intent = new Intent(Intent.ACTION_VIEW, download);代码语言:txt复制 intent.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK);代码语言:txt复制 return intent;代码语言:txt复制 }代码语言:txt复制 private static String getSaveFileName(String downloadUrl) {代码语言:txt复制 if (downloadUrl == null || TextUtils.isEmpty(downloadUrl)) {代码语言:txt复制 return System.currentTimeMillis() ".apk";代码语言:txt复制 }代码语言:txt复制 return downloadUrl.substring(downloadUrl.lastIndexOf("/"));代码语言:txt复制 }代码语言:txt复制 private static File getDownloadDir(UpdateService service) {代码语言:txt复制 File downloadDir = null;代码语言:txt复制 if (Environment.getExternalStorageState().equals(代码语言:txt复制 Environment.MEDIA_MOUNTED)) {代码语言:txt复制 if (service.storeDir != null) {代码语言:txt复制 downloadDir = new File(Environment.getExternalStorageDirectory(), service.storeDir);代码语言:txt复制 } else {代码语言:txt复制 downloadDir = new File(service.getExternalCacheDir(), "update");代码语言:txt复制 }代码语言:txt复制 } else {代码语言:txt复制 downloadDir = new File(service.getCacheDir(), "update");代码语言:txt复制 }代码语言:txt复制 if (!downloadDir.exists()) {代码语言:txt复制 downloadDir.mkdirs();代码语言:txt复制 }代码语言:txt复制 return downloadDir;代码语言:txt复制 }代码语言:txt复制 @Override代码语言:txt复制 public void onCreate() {代码语言:txt复制 super.onCreate();代码语言:txt复制 appName = getApplicationName();代码语言:txt复制 }代码语言:txt复制 @Override代码语言:txt复制 public int onStartCommand(Intent intent, int flags, int startId) {代码语言:txt复制 if (!startDownload && intent != null) {代码语言:txt复制 startDownload = true;代码语言:txt复制 downloadUrl = intent.getStringExtra(URL);代码语言:txt复制 icoResId = intent.getIntExtra(ICO_RES_ID, DEFAULT_RES_ID);代码语言:txt复制 icoSmallResId = intent.getIntExtra(ICO_SMALL_RES_ID, DEFAULT_RES_ID);代码语言:txt复制 storeDir = intent.getStringExtra(STORE_DIR);代码语言:txt复制 updateProgress = intent.getIntExtra(UPDATE_PROGRESS, UPDATE_NUMBER_SIZE);代码语言:txt复制 downloadNotificationFlag = intent.getIntExtra(DOWNLOAD_NOTIFICATION_FLAG, 0);代码语言:txt复制 downloadErrorNotificationFlag = intent.getIntExtra(DOWNLOAD_ERROR_NOTIFICATION_FLAG, 0);代码语言:txt复制 downloadSuccessNotificationFlag = intent.getIntExtra(DOWNLOAD_SUCCESS_NOTIFICATION_FLAG, 0);代码语言:txt复制 isSendBroadcast = intent.getBooleanExtra(IS_SEND_BROADCAST, false);代码语言:txt复制 if (DEBUG) {代码语言:txt复制 Log.d(TAG, "downloadUrl: " downloadUrl);代码语言:txt复制 Log.d(TAG, "icoResId: " icoResId);代码语言:txt复制 Log.d(TAG, "icoSmallResId: " icoSmallResId);代码语言:txt复制 Log.d(TAG, "storeDir: " storeDir);代码语言:txt复制 Log.d(TAG, "updateProgress: " updateProgress);代码语言:txt复制 Log.d(TAG, "downloadNotificationFlag: " downloadNotificationFlag);代码语言:txt复制 Log.d(TAG, "downloadErrorNotificationFlag: " downloadErrorNotificationFlag);代码语言:txt复制 Log.d(TAG, "downloadSuccessNotificationFlag: " downloadSuccessNotificationFlag);代码语言:txt复制 Log.d(TAG, "isSendBroadcast: " isSendBroadcast);代码语言:txt复制 }代码语言:txt复制 notifyId = startId;代码语言:txt复制 buildNotification();代码语言:txt复制 buildBroadcast();代码语言:txt复制 downloadApkTask = new DownloadApk(this);代码语言:txt复制 downloadApkTask.execute(downloadUrl);代码语言:txt复制 }代码语言:txt复制 return super.onStartCommand(intent, flags, startId);代码语言:txt复制 }代码语言:txt复制 @Nullable代码语言:txt复制 @Override代码语言:txt复制 public IBinder onBind(Intent intent) {代码语言:txt复制 return localBinder;代码语言:txt复制 }代码语言:txt复制 @Override代码语言:txt复制 public boolean onUnbind(Intent intent) {代码语言:txt复制 return true;代码语言:txt复制 }代码语言:txt复制 public void setUpdateProgressListener(UpdateProgressListener updateProgressListener) {代码语言:txt复制 this.updateProgressListener = updateProgressListener;代码语言:txt复制 }代码语言:txt复制 @Override代码语言:txt复制 public void onDestroy() {代码语言:txt复制 if (downloadApkTask != null) {代码语言:txt复制 downloadApkTask.cancel(true);代码语言:txt复制 }代码语言:txt复制 if (updateProgressListener != null) {代码语言:txt复制 updateProgressListener = null;代码语言:txt复制 }代码语言:txt复制 localIntent = null;代码语言:txt复制 builder = null;代码语言:txt复制 super.onDestroy();代码语言:txt复制 }代码语言:txt复制 public String getApplicationName() {代码语言:txt复制 PackageManager packageManager = null;代码语言:txt复制 ApplicationInfo applicationInfo = null;代码语言:txt复制 try {代码语言:txt复制 packageManager = getApplicationContext().getPackageManager();代码语言:txt复制 applicationInfo = packageManager.getApplicationInfo(getPackageName(), 0);代码语言:txt复制 } catch (PackageManager.NameNotFoundException e) {代码语言:txt复制 applicationInfo = null;代码语言:txt复制 }代码语言:txt复制 String applicationName =代码语言:txt复制 (String) packageManager.getApplicationLabel(applicationInfo);代码语言:txt复制 return applicationName;代码语言:txt复制 }代码语言:txt复制 private void buildBroadcast() {代码语言:txt复制 if (!isSendBroadcast) {代码语言:txt复制 return;代码语言:txt复制 }代码语言:txt复制 localBroadcastManager = LocalBroadcastManager.getInstance(this);代码语言:txt复制 localIntent = new Intent(ACTION);代码语言:txt复制 }代码语言:txt复制 private void sendLocalBroadcast(int status, int progress) {代码语言:txt复制 if (!isSendBroadcast || localIntent == null) {代码语言:txt复制 return;代码语言:txt复制 }代码语言:txt复制 localIntent.putExtra(STATUS, status);代码语言:txt复制 localIntent.putExtra(PROGRESS, progress);代码语言:txt复制 localBroadcastManager.sendBroadcast(localIntent);代码语言:txt复制 }代码语言:txt复制 private void buildNotification() {代码语言:txt复制 manager = (NotificationManager) getSystemService(NOTIFICATION_SERVICE);代码语言:txt复制 builder = new NotificationCompat.Builder(this);代码语言:txt复制 builder.setContentTitle(getString(R.string.update_app_model_prepare, appName))代码语言:txt复制 .setWhen(System.currentTimeMillis())代码语言:txt复制 .setProgress(100, 1, false)代码语言:txt复制 .setSmallIcon(icoSmallResId)代码语言:txt复制 .setLargeIcon(BitmapFactory.decodeResource(代码语言:txt复制 getResources(), icoResId))代码语言:txt复制 .setDefaults(downloadNotificationFlag);代码语言:txt复制 manager.notify(notifyId, builder.build());代码语言:txt复制 }代码语言:txt复制 private void start() {代码语言:txt复制 builder.setContentTitle(appName);代码语言:txt复制 builder.setContentText(getString(R.string.update_app_model_progress, 1, "%"));代码语言:txt复制 //setChannelId 必须添加否则不能在通知栏显示(Android 8.0)代码语言:txt复制 builder.setChannelId(getPackageName());代码语言:txt复制 manager.notify(notifyId, builder.build());代码语言:txt复制 sendLocalBroadcast(UPDATE_PROGRESS_STATUS, 1);代码语言:txt复制 if (updateProgressListener != null) {代码语言:txt复制 updateProgressListener.start();代码语言:txt复制 }代码语言:txt复制 }代码语言:txt复制 /**代码语言:txt复制 * @param progress download percent , max 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);
}
}
}代码语言:txt复制 private void success(String path) {代码语言:txt复制 builder.setProgress(0, 0, false);代码语言:txt复制 builder.setContentText(getString(R.string.update_app_model_success));代码语言:txt复制 Intent i = installIntent(this, path);代码语言:txt复制 PendingIntent intent = PendingIntent.getActivity(this, 0, i, PendingIntent.FLAG_UPDATE_CURRENT);代码语言:txt复制 builder.setContentIntent(intent);代码语言:txt复制 builder.setDefaults(downloadSuccessNotificationFlag);代码语言:txt复制 Notification n = builder.build();代码语言:txt复制 n.contentIntent = intent;代码语言:txt复制 manager.notify(notifyId, n);代码语言:txt复制 sendLocalBroadcast(UPDATE_SUCCESS_STATUS, 100);代码语言:txt复制 if (updateProgressListener != null) {代码语言:txt复制 updateProgressListener.success();代码语言:txt复制 }代码语言:txt复制 startActivity(i);代码语言:txt复制 stopSelf();代码语言:txt复制 }代码语言:txt复制 private void error() {代码语言:txt复制 Intent i = webLauncher(downloadUrl);代码语言:txt复制 PendingIntent intent = PendingIntent.getActivity(this, 0, i,代码语言:txt复制 PendingIntent.FLAG_UPDATE_CURRENT);代码语言:txt复制 builder.setContentText(getString(R.string.update_app_model_error));代码语言:txt复制 builder.setContentIntent(intent);代码语言:txt复制 builder.setProgress(0, 0, false);代码语言:txt复制 builder.setDefaults(downloadErrorNotificationFlag);代码语言:txt复制 Notification n = builder.build();代码语言:txt复制 n.contentIntent = intent;代码语言:txt复制 manager.notify(notifyId, n);代码语言:txt复制 sendLocalBroadcast(UPDATE_ERROR_STATUS, -1);代码语言:txt复制 if (updateProgressListener != null) {代码语言:txt复制 updateProgressListener.error();代码语言:txt复制 }代码语言:txt复制 stopSelf();代码语言:txt复制 }代码语言:txt复制 private static class DownloadApk extends AsyncTask<String, Integer, String> {代码语言:txt复制 private WeakReference<UpdateService> updateServiceWeakReference;代码语言:txt复制 public DownloadApk(UpdateService service) {代码语言:txt复制 updateServiceWeakReference = new WeakReference<>(service);代码语言:txt复制 }代码语言:txt复制 @Override代码语言:txt复制 protected void onPreExecute() {代码语言:txt复制 super.onPreExecute();代码语言:txt复制 UpdateService service = updateServiceWeakReference.get();代码语言:txt复制 if (service != null) {代码语言:txt复制 service.start();代码语言:txt复制 }代码语言:txt复制 }代码语言:txt复制 @Override代码语言:txt复制 protected String doInBackground(String... params) {代码语言:txt复制 final String downloadUrl = params[0];代码语言:txt复制 final File file = new File(UpdateService.getDownloadDir(updateServiceWeakReference.get()),代码语言:txt复制 UpdateService.getSaveFileName(downloadUrl));代码语言:txt复制 if (DEBUG) {代码语言:txt复制 Log.d(TAG, "download url is " downloadUrl);代码语言:txt复制 Log.d(TAG, "download apk cache at " file.getAbsolutePath());代码语言:txt复制 }代码语言:txt复制 File dir = file.getParentFile();代码语言:txt复制 if (!dir.exists()) {代码语言:txt复制 dir.mkdirs();代码语言:txt复制 }代码语言:txt复制 HttpURLConnection httpConnection = null;代码语言:txt复制 InputStream is = null;代码语言:txt复制 FileOutputStream fos = null;代码语言:txt复制 int updateTotalSize = 0;代码语言:txt复制 URL url;代码语言:txt复制 try {代码语言:txt复制 url = new URL(downloadUrl);代码语言:txt复制 httpConnection = (HttpURLConnection) url.openConnection();代码语言:txt复制 httpConnection.setConnectTimeout(20000);代码语言:txt复制 httpConnection.setReadTimeout(20000);代码语言:txt复制 if (DEBUG) {代码语言:txt复制 Log.d(TAG, "download status code: " httpConnection.getResponseCode());代码语言:txt复制 }代码语言:txt复制 if (httpConnection.getResponseCode() != 200) {代码语言:txt复制 return null;代码语言:txt复制 }代码语言:txt复制 updateTotalSize = httpConnection.getContentLength();代码语言:txt复制 if (file.exists()) {代码语言:txt复制 if (updateTotalSize == file.length()) {代码语言:txt复制 // 下载完成代码语言:txt复制 return file.getAbsolutePath();代码语言:txt复制 } else {代码语言:txt复制 file.delete();代码语言:txt复制 }代码语言:txt复制 }代码语言:txt复制 file.createNewFile();代码语言:txt复制 is = httpConnection.getInputStream();代码语言:txt复制 fos = new FileOutputStream(file, false);代码语言:txt复制 byte buffer[] = new byte[4096];代码语言:txt复制 int readSize = 0;代码语言:txt复制 int currentSize = 0;代码语言:txt复制 while ((readSize = is.read(buffer)) > 0) {代码语言:txt复制 fos.write(buffer, 0, readSize);代码语言:txt复制 currentSize = readSize;代码语言:txt复制 publishProgress((currentSize * 100 / updateTotalSize));代码语言:txt复制 }代码语言:txt复制 // download success代码语言:txt复制 } catch (Exception e) {代码语言:txt复制 e.printStackTrace();代码语言:txt复制 return null;代码语言:txt复制 } finally {代码语言:txt复制 if (httpConnection != null) {代码语言:txt复制 httpConnection.disconnect();代码语言:txt复制 }代码语言:txt复制 if (is != null) {代码语言:txt复制 try {代码语言:txt复制 is.close();代码语言:txt复制 } catch (IOException e) {代码语言:txt复制 e.printStackTrace();代码语言:txt复制 }代码语言:txt复制 }代码语言:txt复制 if (fos != null) {代码语言:txt复制 try {代码语言:txt复制 fos.close();代码语言:txt复制 } catch (IOException e) {代码语言:txt复制 e.printStackTrace();代码语言:txt复制 }代码语言:txt复制 }代码语言:txt复制 }代码语言:txt复制 return file.getAbsolutePath();代码语言:txt复制 }代码语言:txt复制 @Override代码语言:txt复制 protected void onProgressUpdate(Integer... values) {代码语言:txt复制 super.onProgressUpdate(values);代码语言:txt复制 if (DEBUG) {代码语言:txt复制 Log.d(TAG, "current progress is " values[0]);代码语言:txt复制 }代码语言:txt复制 UpdateService service = updateServiceWeakReference.get();代码语言:txt复制 if (service != null) {代码语言:txt复制 service.update(values[0]);代码语言:txt复制 }代码语言:txt复制 }代码语言:txt复制 @Override代码语言:txt复制 protected void onPostExecute(String s) {代码语言:txt复制 super.onPostExecute(s);代码语言:txt复制 UpdateService service = updateServiceWeakReference.get();代码语言:txt复制 if (service != null) {代码语言:txt复制 if (s != null) {代码语言:txt复制 service.success(s);代码语言:txt复制 } else {代码语言:txt复制 service.error();代码语言:txt复制 }代码语言:txt复制 }代码语言:txt复制 }代码语言:txt复制 }代码语言:txt复制 /**代码语言:txt复制 * a builder class helper use UpdateService
*/
public static class Builder {代码语言:txt复制 private String downloadUrl;代码语言:txt复制 private int icoResId = DEFAULT_RES_ID; //default app ico代码语言:txt复制 private int icoSmallResId = DEFAULT_RES_ID;代码语言:txt复制 private int updateProgress = UPDATE_NUMBER_SIZE; //update notification progress when it add number代码语言:txt复制 private String storeDir; //default sdcard/Android/package/update代码语言:txt复制 private int downloadNotificationFlag;代码语言:txt复制 private int downloadSuccessNotificationFlag;代码语言:txt复制 private int downloadErrorNotificationFlag;代码语言:txt复制 private boolean isSendBroadcast;代码语言:txt复制 protected Builder(String downloadUrl) {代码语言:txt复制 this.downloadUrl = downloadUrl;代码语言:txt复制 }代码语言:txt复制 public static Builder create(String downloadUrl) {代码语言:txt复制 if (downloadUrl == null) {代码语言:txt复制 throw new NullPointerException("downloadUrl == null");代码语言:txt复制 }代码语言:txt复制 return new Builder(downloadUrl);代码语言:txt复制 }代码语言:txt复制 public String getDownloadUrl() {代码语言:txt复制 return downloadUrl;代码语言:txt复制 }代码语言:txt复制 public int getIcoResId() {代码语言:txt复制 return icoResId;代码语言:txt复制 }代码语言:txt复制 public Builder setIcoResId(int icoResId) {代码语言:txt复制 this.icoResId = icoResId;代码语言:txt复制 return this;代码语言:txt复制 }代码语言:txt复制 public int getIcoSmallResId() {代码语言:txt复制 return icoSmallResId;代码语言:txt复制 }代码语言:txt复制 public Builder setIcoSmallResId(int icoSmallResId) {代码语言:txt复制 this.icoSmallResId = icoSmallResId;代码语言:txt复制 return this;代码语言:txt复制 }代码语言:txt复制 public int getUpdateProgress() {代码语言:txt复制 return updateProgress;代码语言:txt复制 }代码语言:txt复制 public Builder setUpdateProgress(int updateProgress) {代码语言:txt复制 if (updateProgress < 1) {代码语言:txt复制 throw new IllegalArgumentException("updateProgress < 1");代码语言:txt复制 }代码语言:txt复制 this.updateProgress = updateProgress;代码语言:txt复制 return this;代码语言:txt复制 }代码语言:txt复制 public String getStoreDir() {代码语言:txt复制 return storeDir;代码语言:txt复制 }代码语言:txt复制 public Builder setStoreDir(String storeDir) {代码语言:txt复制 this.storeDir = storeDir;代码语言:txt复制 return this;代码语言:txt复制 }代码语言:txt复制 public int getDownloadNotificationFlag() {代码语言:txt复制 return downloadNotificationFlag;代码语言:txt复制 }代码语言:txt复制 public Builder setDownloadNotificationFlag(int downloadNotificationFlag) {代码语言:txt复制 this.downloadNotificationFlag = downloadNotificationFlag;代码语言:txt复制 return this;代码语言:txt复制 }代码语言:txt复制 public int getDownloadSuccessNotificationFlag() {代码语言:txt复制 return downloadSuccessNotificationFlag;代码语言:txt复制 }代码语言:txt复制 public Builder setDownloadSuccessNotificationFlag(int downloadSuccessNotificationFlag) {代码语言:txt复制 this.downloadSuccessNotificationFlag = downloadSuccessNotificationFlag;代码语言:txt复制 return this;代码语言:txt复制 }代码语言:txt复制 public int getDownloadErrorNotificationFlag() {代码语言:txt复制 return downloadErrorNotificationFlag;代码语言:txt复制 }代码语言:txt复制 public Builder setDownloadErrorNotificationFlag(int downloadErrorNotificationFlag) {代码语言:txt复制 this.downloadErrorNotificationFlag = downloadErrorNotificationFlag;代码语言:txt复制 return this;代码语言:txt复制 }代码语言:txt复制 public boolean isSendBroadcast() {代码语言:txt复制 return isSendBroadcast;代码语言:txt复制 }代码语言:txt复制 public Builder setIsSendBroadcast(boolean isSendBroadcast) {代码语言:txt复制 this.isSendBroadcast = isSendBroadcast;代码语言:txt复制 return this;代码语言:txt复制 }代码语言:txt复制 public Builder build(Context context) {代码语言:txt复制 if (context == null) {代码语言:txt复制 throw new NullPointerException("context == null");代码语言:txt复制 }代码语言:txt复制 Intent intent = new Intent();代码语言:txt复制 intent.setClass(context, UpdateService.class);代码语言:txt复制 intent.putExtra(URL, downloadUrl);代码语言:txt复制 if (icoResId == DEFAULT_RES_ID) {代码语言:txt复制 icoResId = getIcon(context);代码语言:txt复制 }代码语言:txt复制 if (icoSmallResId == DEFAULT_RES_ID) {代码语言:txt复制 icoSmallResId = icoResId;代码语言:txt复制 }代码语言:txt复制 intent.putExtra(ICO_RES_ID, icoResId);代码语言:txt复制 intent.putExtra(STORE_DIR, storeDir);代码语言:txt复制 intent.putExtra(ICO_SMALL_RES_ID, icoSmallResId);代码语言:txt复制 intent.putExtra(UPDATE_PROGRESS, updateProgress);代码语言:txt复制 intent.putExtra(DOWNLOAD_NOTIFICATION_FLAG, downloadNotificationFlag);代码语言:txt复制 intent.putExtra(DOWNLOAD_SUCCESS_NOTIFICATION_FLAG, downloadSuccessNotificationFlag);代码语言:txt复制 intent.putExtra(DOWNLOAD_ERROR_NOTIFICATION_FLAG, downloadErrorNotificationFlag);代码语言:txt复制 intent.putExtra(IS_SEND_BROADCAST, isSendBroadcast);代码语言:txt复制 context.startService(intent);代码语言:txt复制 return this;代码语言:txt复制 }代码语言:txt复制 private int getIcon(Context context) {代码语言:txt复制 final PackageManager packageManager = context.getPackageManager();代码语言:txt复制 ApplicationInfo appInfo = null;代码语言:txt复制 try {代码语言:txt复制 appInfo = packageManager.getApplicationInfo(context.getPackageName(), PackageManager.GET_META_DATA);代码语言:txt复制 } catch (PackageManager.NameNotFoundException e) {代码语言:txt复制 e.printStackTrace();代码语言:txt复制 }代码语言:txt复制 if (appInfo != null) {代码语言:txt复制 return appInfo.icon;代码语言:txt复制 }代码语言:txt复制 return 0;代码语言:txt复制 }代码语言:txt复制 }代码语言:txt复制}


