Android版本更新(Service下载 Notification进度条:直接拿来用)

来源:互联网 发布:linux 邮件系统 编辑:程序博客网 时间:2024/05/21 14:08

废话不多说:直接上代码:

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 = 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;    //params    private 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 ico    private int icoSmallResId;    private int updateProgress;   //update notification progress when it add number    private String storeDir;          //default sdcard/Android/package/update    private 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;    }    private static Intent installIntent(String path){        Intent intent = new Intent(Intent.ACTION_VIEW);        if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.N) {            intent.setFlags(Intent.FLAG_GRANT_READ_URI_PERMISSION);            Uri contentUri = FileProvider.getUriForFile(BaseApplication.app, "com.hx.socialapp.FileProvider", new File(path));            intent.setDataAndType(contentUri, "application/vnd.android.package-archive");        }else {            Uri uri = Uri.fromFile(new File(path));            intent.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK);            intent.setDataAndType(uri, "application/vnd.android.package-archive");        }        return intent;    }    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;    }    private static String getSaveFileName(String downloadUrl) {        if (downloadUrl == null || TextUtils.isEmpty(downloadUrl)) {            return "noName.apk";        }        return downloadUrl.substring(downloadUrl.lastIndexOf("/"));    }    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;    }    @Override    public void onCreate() {        super.onCreate();        appName = getApplicationName();    }    @Override    public 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){                Log.d(TAG, "downloadUrl: " + downloadUrl);                Log.d(TAG, "icoResId: " + icoResId);                Log.d(TAG, "icoSmallResId: " + icoSmallResId);                Log.d(TAG, "storeDir: " + storeDir);                Log.d(TAG, "updateProgress: " + updateProgress);                Log.d(TAG, "downloadNotificationFlag: " + downloadNotificationFlag);                Log.d(TAG, "downloadErrorNotificationFlag: " + downloadErrorNotificationFlag);                Log.d(TAG, "downloadSuccessNotificationFlag: " + downloadSuccessNotificationFlag);                Log.d(TAG, "isSendBroadcast: " + isSendBroadcast);            }            notifyId = startId;            buildNotification();            buildBroadcast();            downloadApkTask = new DownloadApk(this);            downloadApkTask.execute(downloadUrl);        }        return super.onStartCommand(intent, flags, startId);    }    @Nullable    @Override    public IBinder onBind(Intent intent) {        return localBinder;    }    @Override    public boolean onUnbind(Intent intent) {        return true;    }    public void setUpdateProgressListener(UpdateProgressListener updateProgressListener) {        this.updateProgressListener = updateProgressListener;    }    @Override    public void onDestroy() {        if (downloadApkTask != null){            downloadApkTask.cancel(true);        }        if (updateProgressListener != null){            updateProgressListener = null;        }        localIntent = null;        builder = null;        super.onDestroy();    }    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);    }    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();        }    }    /**     *     * @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);            }        }    }    private void success(String path) {        builder.setProgress(0, 0, false);        builder.setContentText(getString(R.string.update_app_model_success));        Intent i = installIntent(path);        PendingIntent intent = PendingIntent.getActivity(this, 0, i, PendingIntent.FLAG_UPDATE_CURRENT);        builder.setContentIntent(intent);        builder.setDefaults(downloadSuccessNotificationFlag);        Notification n = builder.build();        n.contentIntent = intent;        manager.notify(notifyId, n);        sendLocalBroadcast(UPDATE_SUCCESS_STATUS, 100);        if (updateProgressListener != null){            updateProgressListener.success();        }        startActivity(i);        stopSelf();    }    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<String, Integer, String>{        private WeakReference<UpdateService> updateServiceWeakReference;        public DownloadApk(UpdateService service){            updateServiceWeakReference = new WeakReference<>(service);        }        @Override        protected void onPreExecute() {            super.onPreExecute();            UpdateService service = updateServiceWeakReference.get();            if (service != null){                service.start();            }        }        @Override        protected String doInBackground(String... params) {            final String downloadUrl = params[0];            final File file = new File(UpdateService.getDownloadDir(updateServiceWeakReference.get()),                    UpdateService.getSaveFileName(downloadUrl));            if (DEBUG){                Log.d(TAG, "download url is " + downloadUrl);                Log.d(TAG, "download apk cache at " + file.getAbsolutePath());            }            File dir = file.getParentFile();            if (!dir.exists()){                dir.mkdirs();            }            HttpURLConnection httpConnection = null;            InputStream is = null;            FileOutputStream fos = null;            int updateTotalSize = 0;            URL url;            try {                url = new URL(downloadUrl);                httpConnection = (HttpURLConnection) url.openConnection();                httpConnection.setConnectTimeout(20000);                httpConnection.setReadTimeout(20000);                if (DEBUG){                    Log.d(TAG, "download status code: " + httpConnection.getResponseCode());                }                if (httpConnection.getResponseCode() != 200) {                    return null;                }                updateTotalSize = httpConnection.getContentLength();                if (file.exists()) {                    if (updateTotalSize == file.length()) {                        // 下载完成                        return file.getAbsolutePath();                    } else {                        file.delete();                    }                }                file.createNewFile();                is = httpConnection.getInputStream();                fos = new FileOutputStream(file, false);                byte buffer[] = new byte[4096];                int readSize = 0;                int currentSize = 0;                while ((readSize = is.read(buffer)) > 0) {                    fos.write(buffer, 0, readSize);                    currentSize += readSize;                    publishProgress((currentSize * 100 / updateTotalSize));                }                // download success            } catch (Exception e) {                e.printStackTrace();                return null;            } finally {                if (httpConnection != null) {                    httpConnection.disconnect();                }                if (is != null) {                    try {                        is.close();                    } catch (IOException e) {                        e.printStackTrace();                    }                }                if (fos != null) {                    try {                        fos.close();                    } catch (IOException e) {                        e.printStackTrace();                    }                }            }            return file.getAbsolutePath();        }        @Override        protected void onProgressUpdate(Integer... values) {            super.onProgressUpdate(values);            if (DEBUG){                Log.d(TAG, "current progress is " + values[0]);            }            UpdateService service = updateServiceWeakReference.get();            if (service != null){                service.update(values[0]);            }        }        @Override        protected void onPostExecute(String s) {            super.onPostExecute(s);            UpdateService service = updateServiceWeakReference.get();            if (service != null){                if (s != null){                    service.success(s);                }else {                    service.error();                }            }        }    }    /**     * a builder class helper use UpdateService     */    public static class Builder{        private String downloadUrl;        private int icoResId = DEFAULT_RES_ID;             //default app ico        private int icoSmallResId = DEFAULT_RES_ID;        private int updateProgress = UPDATE_NUMBER_SIZE;   //update notification progress when it add number        private String storeDir;          //default sdcard/Android/package/update        private int downloadNotificationFlag;        private int downloadSuccessNotificationFlag;        private int downloadErrorNotificationFlag;        private boolean isSendBroadcast;        protected Builder(String downloadUrl){            this.downloadUrl = downloadUrl;        }        public static Builder create(String downloadUrl){            if (downloadUrl == null) {                throw new NullPointerException("downloadUrl == null");            }            return new Builder(downloadUrl);        }        public String getDownloadUrl() {            return downloadUrl;        }        public int getIcoResId() {            return icoResId;        }        public Builder setIcoResId(int icoResId) {            this.icoResId = icoResId;            return this;        }        public int getIcoSmallResId() {            return icoSmallResId;        }        public Builder setIcoSmallResId(int icoSmallResId) {            this.icoSmallResId = icoSmallResId;            return this;        }        public int getUpdateProgress() {            return updateProgress;        }        public Builder setUpdateProgress(int updateProgress) {            if (updateProgress < 1){                throw new IllegalArgumentException("updateProgress < 1");            }            this.updateProgress = updateProgress;            return this;        }        public String getStoreDir() {            return storeDir;        }        public Builder setStoreDir(String storeDir) {            this.storeDir = storeDir;            return this;        }        public int getDownloadNotificationFlag() {            return downloadNotificationFlag;        }        public Builder setDownloadNotificationFlag(int downloadNotificationFlag) {            this.downloadNotificationFlag = downloadNotificationFlag;            return this;        }        public int getDownloadSuccessNotificationFlag() {            return downloadSuccessNotificationFlag;        }        public Builder setDownloadSuccessNotificationFlag(int downloadSuccessNotificationFlag) {            this.downloadSuccessNotificationFlag = downloadSuccessNotificationFlag;            return this;        }        public int getDownloadErrorNotificationFlag() {            return downloadErrorNotificationFlag;        }        public Builder setDownloadErrorNotificationFlag(int downloadErrorNotificationFlag) {            this.downloadErrorNotificationFlag = downloadErrorNotificationFlag;            return this;        }        public boolean isSendBroadcast() {            return isSendBroadcast;        }        public Builder setIsSendBroadcast(boolean isSendBroadcast) {            this.isSendBroadcast = isSendBroadcast;            return this;        }        public Builder build(Context context){            if (context == null){                throw new NullPointerException("context == null");            }            Intent intent = new Intent();            intent.setClass(context, UpdateService.class);            intent.putExtra(URL, downloadUrl);            if (icoResId == DEFAULT_RES_ID){                icoResId = getIcon(context);            }            if (icoSmallResId == DEFAULT_RES_ID){                icoSmallResId = icoResId;            }            intent.putExtra(ICO_RES_ID, icoResId);            intent.putExtra(STORE_DIR, storeDir);            intent.putExtra(ICO_SMALL_RES_ID, icoSmallResId);            intent.putExtra(UPDATE_PROGRESS, updateProgress);            intent.putExtra(DOWNLOAD_NOTIFICATION_FLAG, downloadNotificationFlag);            intent.putExtra(DOWNLOAD_SUCCESS_NOTIFICATION_FLAG, downloadSuccessNotificationFlag);            intent.putExtra(DOWNLOAD_ERROR_NOTIFICATION_FLAG, downloadErrorNotificationFlag);            intent.putExtra(IS_SEND_BROADCAST, isSendBroadcast);            context.startService(intent);            return this;        }        private int getIcon(Context context){            final PackageManager packageManager = context.getPackageManager();            ApplicationInfo appInfo = null;            try {                appInfo = packageManager.getApplicationInfo(context.getPackageName(), PackageManager.GET_META_DATA);            } catch (PackageManager.NameNotFoundException e) {                e.printStackTrace();            }            if (appInfo != null){                return appInfo.icon;            }            return 0;        }    }}

--------------------------------

用法:

//获取版本号    private void requestAppVersion() {        RequestParams params = ParamsUtil.getInstances().appUpgrade(Constant.getAppVersion(mContext)                , ContantUrl.SERVER_VERSION_NAME);        BaseApplication.getInstance().httpRequest.xPostjson(mContext, params, Constant.BASE_HTTP                + ContantUrl.appUpgrade, new                RequestResultJsonCallBack() {                    @Override                    public void onSucess(String result) {                        Map item = Constant.getPerson(result, Map.class);                        CommonEntity info = Constant.getPerson(result, CommonEntity.class);                        String str = item.get("object") + "";                        if (info.getRetCode().equals(Constant.RETURN_SUCCESS_CODE)) {                            mUpdateItem = Constant.getPerson(str, UpdateEntity.class);                            if (mUpdateItem != null) {                                Log.i("downurl", mUpdateItem.getUrl());                                String text = mContext.getResources().getString(R.string                                        .check_upgrade);                                UpgradeDialog upgrade = new UpgradeDialog(MainActivity.this,                                        text, new UpgradeDialog.OnClickconfirmListener() {                                    @Override                                    public void confirm() {                                        if (!checkPermission(Manifest.permission                                                .WRITE_EXTERNAL_STORAGE)) {                                            ActivityCompat.requestPermissions(MainActivity.this,                                                    new String[]{Manifest.permission                                                            .WRITE_EXTERNAL_STORAGE},                                                    REQUEST_PERMISSION_STORAGE);                                            return;                                        }                                        UpdateService.Builder.create(mUpdateItem.getUrl())                                                .setStoreDir(ContantUrl.AppFile)                                                .setDownloadSuccessNotificationFlag(Notification                                                        .DEFAULT_ALL)                                                .setDownloadErrorNotificationFlag(Notification                                                        .DEFAULT_ALL)                                                .build(mContext);                                        Toast.makeText(mContext, "正在后台下载", Toast.LENGTH_LONG)                                                .show();                                    }                                });                                upgrade.show();                                upgrade.setDetail(mUpdateItem.getDescription());                                AppConfig.saveObject(mContext, Constant.VERSION, mUpdateItem);                            }                        } else {                        }                    }                    @Override                    public void onFailure(int errorCode, String errorMsg) {                    }                });    }



-------------------------------

附上其他比较好的博客链接:

Android sdk version 9以上就有DownManager使用DownManager,我们可以很简便的在各个安卓机子上升级自家的应用本例写了一个UpdataService实现后台下载新的APK到sdcard,并自动安装更新。[java] view plain copy/**  * 检测安装更新文件的助手类  *   * @author G.Y.Y  *   */    public class UpdataService extends Service {        /** 安卓系统下载类 **/      DownloadManager manager;        /** 接收下载完的广播 **/      DownloadCompleteReceiver receiver;        /** 初始化下载器 **/      private void initDownManager() {                    manager = (DownloadManager) getSystemService(DOWNLOAD_SERVICE);                    receiver = new DownloadCompleteReceiver();            //设置下载地址          DownloadManager.Request down = new DownloadManager.Request(                  Uri.parse("http://gdown.baidu.com/data/wisegame/fd84b7f6746f0b18/baiduyinyue_4802.apk"));                    // 设置允许使用的网络类型,这里是移动网络和wifi都可以          down.setAllowedNetworkTypes(DownloadManager.Request.NETWORK_MOBILE                  | DownloadManager.Request.NETWORK_WIFI);                    // 下载时,通知栏显示途中          down.setNotificationVisibility(Request.VISIBILITY_VISIBLE);                    // 显示下载界面          down.setVisibleInDownloadsUi(true);                    // 设置下载后文件存放的位置          down.setDestinationInExternalFilesDir(this,                  Environment.DIRECTORY_DOWNLOADS, "baidumusic.apk");                    // 将下载请求放入队列          manager.enqueue(down);                    //注册下载广播          registerReceiver(receiver, new IntentFilter(                  DownloadManager.ACTION_DOWNLOAD_COMPLETE));      }        @Override      public int onStartCommand(Intent intent, int flags, int startId) {                    // 调用下载          initDownManager();                    return super.onStartCommand(intent, flags, startId);      }        @Override      public IBinder onBind(Intent intent) {                return null;      }        @Override      public void onDestroy() {            // 注销下载广播          if (receiver != null)              unregisterReceiver(receiver);                    super.onDestroy();      }        // 接受下载完成后的intent      class DownloadCompleteReceiver extends BroadcastReceiver {                    @Override          public void onReceive(Context context, Intent intent) {                //判断是否下载完成的广播              if (intent.getAction().equals(                      DownloadManager.ACTION_DOWNLOAD_COMPLETE)) {                                    //获取下载的文件id                  long downId = intent.getLongExtra(                          DownloadManager.EXTRA_DOWNLOAD_ID, -1);                                    //自动安装apk                  installAPK(manager.getUriForDownloadedFile(downId));                                    //停止服务并关闭广播                  UpdataService.this.stopSelf();                }          }            /**          * 安装apk文件          */          private void installAPK(Uri apk) {                            // 通过Intent安装APK文件              Intent intents = new Intent();                            intents.setAction("android.intent.action.VIEW");              intents.addCategory("android.intent.category.DEFAULT");              intents.setType("application/vnd.android.package-archive");              intents.setData(apk);              intents.setDataAndType(apk,"application/vnd.android.package-archive");              intents.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK);              android.os.Process.killProcess(android.os.Process.myPid());              // 如果不加上这句的话在apk安装完成之后点击单开会崩溃                            startActivity(intents);            }        }  }  AndroidManifest.xml注册service[html] view plain copy<service             android:name="com.example.test.UpdataService"            android:enabled="true"            >        </service>  添加调用DownManager的权限[html] view plain copy<uses-permission android:name="android.permission.INTERNET" />    <uses-permission android:name="android.permission.WRITE_EXTERNAL_STORAGE" />    <uses-permission android:name="android.permission.DOWNLOAD_WITHOUT_NOTIFICATION" />  

和:附上自动更新的祖师爷写的代码和博客!

功能:版本更新、文件后台下载以及Notification显示进度条。

效果图:

主要代码:

Java代码  收藏代码
  1. <strong style="color: #262626; font-family: Simsun;">package com.ljp.download;  
  2.    
  3. import java.io.File;  
  4.    
  5. import android.app.ActivityGroup;  
  6. import android.app.AlertDialog;  
  7. import android.app.Dialog;  
  8. import android.content.DialogInterface;  
  9. import android.content.Intent;  
  10. import android.net.Uri;  
  11. import android.os.Bundle;  
  12. import android.view.View;  
  13. import android.view.View.OnClickListener;  
  14. import android.widget.Button;  
  15.    
  16. import com.ljp.download.service.AppUpgradeService;  
  17. import com.ljp.version.R;  
  18.    
  19. public class MainActivity extends ActivityGroup {  
  20.    
  21.     private Button button1;  
  22.    
  23.     private String mDownloadUrl = "http://gdown.baidu.com/data/wisegame/ba226d3cf2cfc97b/baiduyinyue_4920.apk";  
  24.     private String apkUpdateMsg = "1.内容1\n2.内容2\n3.内容3";  
  25.     private Dialog updateVersionDialog;  
  26.    
  27.     @Override  
  28.     protected void onCreate(Bundle savedInstanceState) {  
  29.         super.onCreate(savedInstanceState);  
  30.         setContentView(R.layout.layout_main);  
  31.         button1 = (Button) findViewById(R.id.button1);  
  32.         button1.setOnClickListener(new OnClickListener() {  
  33.             @Override  
  34.             public void onClick(View v) {  
  35.                 showDialog();  
  36.             }  
  37.         });  
  38.     }  
  39.     private void showDialog() {  
  40.         updateVersionDialog = new AlertDialog.Builder(MainActivity.this).setTitle("有新版本需要更新").setMessage(apkUpdateMsg)  
  41.                 .setPositiveButton("现在更新"new DialogInterface.OnClickListener() {  
  42.                     @Override  
  43.                     public void onClick(DialogInterface dialog, int which) {  
  44.                         downLoadApk();  
  45.                     }  
  46.                 }).setNegativeButton("以后再说"new DialogInterface.OnClickListener() {  
  47.                     public void onClick(DialogInterface dialog, int whichButton) {  
  48.                         dialog.dismiss();  
  49.                     }  
  50.                 }).create();  
  51.         updateVersionDialog.show();  
  52.    
  53.     }  
  54.    
  55.     /** 
  56.      * 文件下载 
  57.      */  
  58.     private void downLoadApk() {  
  59.         Intent intent = new Intent(MainActivity.this, AppUpgradeService.class);  
  60.         intent.putExtra("mDownloadUrl", mDownloadUrl);  
  61.         startService(intent);  
  62.         updateVersionDialog.dismiss();  
  63.     }  
  64.    
  65.    
  66. }</strong>  

 

Java代码  收藏代码
  1. package com.ljp.download.service;  
  2.    
  3. import java.io.File;  
  4. import java.io.FileOutputStream;  
  5. import java.io.InputStream;  
  6. import java.net.URLEncoder;  
  7. import java.util.HashMap;  
  8. import java.util.Map;  
  9.    
  10. import org.apache.http.HttpEntity;  
  11. import org.apache.http.HttpResponse;  
  12. import org.apache.http.client.HttpClient;  
  13. import org.apache.http.client.methods.HttpGet;  
  14. import org.apache.http.impl.client.DefaultHttpClient;  
  15. import android.app.Notification;  
  16. import android.app.NotificationManager;  
  17. import android.app.PendingIntent;  
  18. import android.app.Service;  
  19. import android.content.Intent;  
  20. import android.content.pm.PackageInfo;  
  21. import android.content.pm.PackageManager;  
  22. import android.graphics.drawable.Drawable;  
  23. import android.net.Uri;  
  24. import android.os.Bundle;  
  25. import android.os.Environment;  
  26. import android.os.Handler;  
  27. import android.os.IBinder;  
  28. import android.os.Message;  
  29. import android.util.Log;  
  30. import android.view.View;  
  31. import android.widget.Button;  
  32. import android.widget.ImageView;  
  33. import android.widget.ProgressBar;  
  34. import android.widget.RemoteViews;  
  35. import android.widget.TextView;  
  36. import android.widget.Toast;  
  37.    
  38. import com.ljp.download.DownloadUtils;  
  39. import com.ljp.download.MainActivity;  
  40. import com.ljp.version.R;  
  41. /** 
  42.  * 程序版本更新Service 
  43.  * @author yingjun10627 
  44.  * 
  45.  */  
  46. public class AppUpgradeService extends Service {  
  47.     private NotificationManager mNotificationManager = null;  
  48.     private Notification mNotification = null;  
  49.     private PendingIntent mPendingIntent = null;  
  50.    
  51.     private String mDownloadUrl;  
  52.     private File destDir = null;  
  53.     private File destFile = null;  
  54.    
  55.     public static final String downloadPath = "/winner";  
  56.     public static final int mNotificationId = 111;  
  57.     private static final int DOWNLOAD_FAIL = -1;  
  58.     private static final int DOWNLOAD_SUCCESS = 0;  
  59.    
  60.     private Handler mHandler = new Handler() {  
  61.         @Override  
  62.         public void handleMessage(Message msg) {  
  63.             switch (msg.what) {  
  64.             case DOWNLOAD_SUCCESS:  
  65.                 Toast.makeText(getApplicationContext(), "下载成功", Toast.LENGTH_LONG).show();  
  66.                 install(destFile);  
  67.                 mNotificationManager.cancel(mNotificationId);  
  68.                 break;  
  69.             case DOWNLOAD_FAIL:  
  70.                 Toast.makeText(getApplicationContext(), "下载失败", Toast.LENGTH_LONG).show();  
  71.                 mNotificationManager.cancel(mNotificationId);  
  72.                 break;  
  73.             default:  
  74.                 break;  
  75.             }  
  76.         }  
  77.    
  78.     };  
  79.    
  80.     @Override  
  81.     public int onStartCommand(Intent intent, int flags, int startId) {  
  82.         if(intent==null){  
  83.              stopSelf();  
  84.              return super.onStartCommand(intent, flags, startId);  
  85.         }  
  86.         mDownloadUrl = intent.getStringExtra("mDownloadUrl");  
  87.         if (Environment.getExternalStorageState().equals(android.os.Environment.MEDIA_MOUNTED)) {  
  88.             destDir = new File(Environment.getExternalStorageDirectory().getPath() + downloadPath);  
  89.             if (destDir.exists()) {  
  90.                 File destFile = new File(destDir.getPath() + "/" + URLEncoder.encode(mDownloadUrl));  
  91.                 if (destFile.exists() && destFile.isFile() && checkApkFile(destFile.getPath())) {  
  92.                     install(destFile);  
  93.                     stopSelf();  
  94.                     return super.onStartCommand(intent, flags, startId);  
  95.                 }  
  96.             }  
  97.         } else {  
  98.             return super.onStartCommand(intent, flags, startId);  
  99.         }  
  100.         mNotificationManager = (NotificationManager) getSystemService(NOTIFICATION_SERVICE);  
  101.         mNotification = new Notification();  
  102.         Intent completingIntent = new Intent();  
  103.         completingIntent.setFlags(Intent.FLAG_ACTIVITY_SINGLE_TOP);  
  104.         completingIntent.setClass(getApplicationContext(), AppUpgradeService.class);  
  105.         // 创建Notifcation对象,设置图标,提示文字,策略  
  106.         mPendingIntent = PendingIntent.getActivity(AppUpgradeService.this, R.string.app_name, completingIntent,  
  107.                 PendingIntent.FLAG_UPDATE_CURRENT);  
  108.         mNotification.icon = R.drawable.ic_launcher;  
  109.         mNotification.tickerText = "开始下载";  
  110.         mNotification.contentIntent = mPendingIntent;  
  111.    
  112.         mNotification.contentView = new RemoteViews(getPackageName(), R.layout.app_upgrade_notification);  
  113.         mNotification.contentView.setProgressBar(R.id.app_upgrade_progressbar, 1000false);  
  114.         mNotification.contentView.setTextViewText(R.id.app_upgrade_title, "正在下载...");  
  115.         mNotification.contentView.setTextViewText(R.id.app_upgrade_text, "当前进度:0%");  
  116.         mNotificationManager.cancel(mNotificationId);  
  117.         mNotificationManager.notify(mNotificationId, mNotification);  
  118.         new AppUpgradeThread().start();  
  119.         return  super.onStartCommand(intent, flags, startId);  
  120.    
  121.     }  
  122.    
  123.        
  124.     /** 
  125.      * 用于监听文件下载 
  126.      */  
  127.     private DownloadUtils.DownloadListener downloadListener = new DownloadUtils.DownloadListener() {  
  128.         @Override  
  129.         public void downloading(int progress) {  
  130.             System.out.println(progress);  
  131.             mNotification.contentView.setProgressBar(R.id.app_upgrade_progressbar, 100, progress, false);  
  132.             mNotification.contentView.setTextViewText(R.id.app_upgrade_text, "当前进度:" + progress + "%");  
  133.             mNotificationManager.notify(mNotificationId, mNotification);  
  134.         }  
  135.    
  136.         @Override  
  137.         public void downloaded() {  
  138.             mNotification.contentView.setViewVisibility(R.id.app_upgrade_progressbar, View.GONE);  
  139.             mNotification.defaults = Notification.DEFAULT_SOUND;  
  140.             mNotification.contentIntent = mPendingIntent;  
  141.             mNotification.contentView.setTextViewText(R.id.app_upgrade_title, "下载完成");  
  142.             mNotificationManager.notify(mNotificationId, mNotification);  
  143.             if (destFile.exists() && destFile.isFile() && checkApkFile(destFile.getPath())) {  
  144.                 Message msg = mHandler.obtainMessage();  
  145.                 msg.what = DOWNLOAD_SUCCESS;  
  146.                 mHandler.sendMessage(msg);  
  147.             }  
  148.             mNotificationManager.cancel(mNotificationId);  
  149.         }  
  150.     };  
  151.    
  152.     /** 
  153.      * 用于文件下载线程 
  154.      * @author yingjun10627 
  155.      * 
  156.      */  
  157.     class AppUpgradeThread extends Thread {  
  158.         @Override  
  159.         public void run() {  
  160.             if (Environment.getExternalStorageState().equals(android.os.Environment.MEDIA_MOUNTED)) {  
  161.                 if (destDir == null) {  
  162.                     destDir = new File(Environment.getExternalStorageDirectory().getPath() + downloadPath);  
  163.                 }  
  164.                 if (destDir.exists() || destDir.mkdirs()) {  
  165.                     destFile = new File(destDir.getPath() + "/" + URLEncoder.encode(mDownloadUrl));  
  166.                     if (destFile.exists() && destFile.isFile() && checkApkFile(destFile.getPath())) {  
  167.                         install(destFile);  
  168.                     } else {  
  169.                         try {  
  170.                             DownloadUtils.download(mDownloadUrl, destFile, false, downloadListener);  
  171.                         } catch (Exception e) {  
  172.                             Message msg = mHandler.obtainMessage();  
  173.                             msg.what = DOWNLOAD_FAIL;  
  174.                             mHandler.sendMessage(msg);  
  175.                             e.printStackTrace();  
  176.                         }  
  177.                     }  
  178.                 }  
  179.             }  
  180.             stopSelf();  
  181.         }  
  182.     }  
  183.    
  184.     /** 
  185.      * apk文件安装 
  186.      *  
  187.      * @param apkFile 
  188.      */  
  189.     public void install(File apkFile) {  
  190.         Uri uri = Uri.fromFile(apkFile);  
  191.         Intent intent = new Intent(Intent.ACTION_VIEW);  
  192.         intent.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK);  
  193.         intent.setDataAndType(uri, "application/vnd.android.package-archive");  
  194.         startActivity(intent);  
  195.     }  
  196.    
  197.     /** 
  198.      * 判断文件是否完整 
  199.      *  
  200.      * @param apkFilePath 
  201.      * @return 
  202.      */  
  203.     public boolean checkApkFile(String apkFilePath) {  
  204.         boolean result = false;  
  205.         try {  
  206.             PackageManager pManager = getPackageManager();  
  207.             PackageInfo pInfo = pManager.getPackageArchiveInfo(apkFilePath, PackageManager.GET_ACTIVITIES);  
  208.             if (pInfo == null) {  
  209.                 result = false;  
  210.             } else {  
  211.                 result = true;  
  212.             }  
  213.         } catch (Exception e) {  
  214.             result = false;  
  215.             e.printStackTrace();  
  216.         }  
  217.         return result;  
  218.     }  
  219.    
  220.     @Override  
  221.     public IBinder onBind(Intent intent) {  
  222.         return null;  
  223.     }  
  224.    
  225. }  

 

Java代码  收藏代码
  1. package com.ljp.download;  
  2.    
  3. import java.io.File;  
  4. import java.io.FileInputStream;  
  5. import java.io.FileOutputStream;  
  6. import java.io.IOException;  
  7. import java.io.InputStream;  
  8. import java.util.zip.GZIPInputStream;  
  9.    
  10. import org.apache.http.Header;  
  11. import org.apache.http.HttpResponse;  
  12. import org.apache.http.HttpStatus;  
  13. import org.apache.http.client.HttpClient;  
  14. import org.apache.http.client.methods.HttpGet;  
  15. import org.apache.http.impl.client.DefaultHttpClient;  
  16. import org.apache.http.params.BasicHttpParams;  
  17. import org.apache.http.params.HttpConnectionParams;  
  18. import org.apache.http.params.HttpParams;  
  19.    
  20. public class DownloadUtils {  
  21.     private static final int CONNECT_TIMEOUT = 10000;  
  22.     private static final int DATA_TIMEOUT = 40000;  
  23.     private final static int DATA_BUFFER = 8192;  
  24.    
  25.        
  26.        
  27.     public interface DownloadListener {  
  28.         public void downloading(int progress);  
  29.         public void downloaded();  
  30.     }  
  31.    
  32.     public static long download(String urlStr, File dest, boolean append, DownloadListener downloadListener) throws Exception {  
  33.         int downloadProgress = 0;  
  34.         long remoteSize = 0;  
  35.         int currentSize = 0;  
  36.         long totalSize = -1;  
  37.    
  38.         if (!append && dest.exists() && dest.isFile()) {  
  39.             dest.delete();  
  40.         }  
  41.    
  42.         if (append && dest.exists() && dest.exists()) {  
  43.             FileInputStream fis = null;  
  44.             try {  
  45.                 fis = new FileInputStream(dest);  
  46.                 currentSize = fis.available();  
  47.             } catch (IOException e) {  
  48.                 throw e;  
  49.             } finally {  
  50.                 if (fis != null) {  
  51.                     fis.close();  
  52.                 }  
  53.             }  
  54.         }  
  55.    
  56.         HttpGet request = new HttpGet(urlStr);  
  57.    
  58.         if (currentSize > 0) {  
  59.             request.addHeader("RANGE""bytes=" + currentSize + "-");  
  60.         }  
  61.    
  62.         HttpParams params = new BasicHttpParams();  
  63.         HttpConnectionParams.setConnectionTimeout(params, CONNECT_TIMEOUT);  
  64.         HttpConnectionParams.setSoTimeout(params, DATA_TIMEOUT);  
  65.         HttpClient httpClient = new DefaultHttpClient(params);  
  66.    
  67.         InputStream is = null;  
  68.         FileOutputStream os = null;  
  69.         try {  
  70.             HttpResponse response = httpClient.execute(request);  
  71.             if (response.getStatusLine().getStatusCode() == HttpStatus.SC_OK) {  
  72.                 is = response.getEntity().getContent();  
  73.                 remoteSize = response.getEntity().getContentLength();  
  74.                 Header contentEncoding = response.getFirstHeader("Content-Encoding");  
  75.                 if (contentEncoding != null && contentEncoding.getValue().equalsIgnoreCase("gzip")) {  
  76.                     is = new GZIPInputStream(is);  
  77.                 }  
  78.                 os = new FileOutputStream(dest, append);  
  79.                 byte buffer[] = new byte[DATA_BUFFER];  
  80.                 int readSize = 0;  
  81.                 int temp=0;  
  82.                 while ((readSize = is.read(buffer)) > 0) {  
  83.                     os.write(buffer, 0, readSize);  
  84.                     os.flush();  
  85.                     totalSize += readSize;  
  86.                     if (downloadListener != null) {  
  87.                         downloadProgress = (int) (totalSize * 100 / remoteSize);  
  88.                         if(downloadProgress>=temp){  
  89.                            temp++;  
  90.                            downloadListener.downloading(downloadProgress);  
  91.                         }  
  92.                     }  
  93.                 }  
  94.                 if (totalSize < 0) {  
  95.                     totalSize = 0;  
  96.                 }  
  97.             }  
  98.         } finally {  
  99.             if (os != null) {  
  100.                 os.close();  
  101.             }  
  102.             if (is != null) {  
  103.                 is.close();  
  104.             }  
  105.         }  
  106.    
  107.         if (totalSize < 0) {  
  108.             throw new Exception("Download file fail: " + urlStr);  
  109.         }  
  110.    
  111.         if (downloadListener != null) {  
  112.             downloadListener.downloaded();  
  113.         }  
  114.    
  115.         return totalSize;  
  116.     }  
  117. }  

 

Service启动方式说明:

 

START_STICKY:如果service进程被kill掉,保留service的状态为开始状态,但不保留递送的intent对象。随后系统会尝试重新创建service,由于服务状态为开始状态,所以创建服务后一定会调用onStartCommand(Intent,int,int)方法。如果在此期间没有任何启动命令被传递到service,那么参数Intent将为null。

 

START_NOT_STICKY:“非粘性的”。使用这个返回值时,如果在执行完onStartCommand后,服务被异常kill掉,系统不会自动重启该服务。

 

START_REDELIVER_INTENT:重传Intent。使用这个返回值时,如果在执行完onStartCommand后,服务被异常kill掉,系统会自动重启该服务,并将Intent的值传入。

 

START_STICKY_COMPATIBILITY:START_STICKY的兼容版本,但不保证服务被kill后一定能重启。

 


------------------------------------

阅读全文
0 0