美文网首页
应用更新之_DownloadService

应用更新之_DownloadService

作者: Smart_Arvin | 来源:发表于2016-12-14 22:28 被阅读41次

    apk下载服务:

    package com.xxx.update;
    
    import java.io.File;
    import java.io.FileOutputStream;
    import java.io.IOException;
    import java.io.InputStream;
    import java.net.HttpURLConnection;
    import java.net.MalformedURLException;
    import java.net.URL;
    import com.xxx.base.SczwApplication;
    import com.xxx.sczwdemo.R;
    import com.xxx.update.UpdateNotifiActivity.ICallbackResult;
    import android.app.Notification;
    import android.app.NotificationManager;
    import android.app.PendingIntent;
    import android.app.Service;
    import android.content.Context;
    import android.content.Intent;
    import android.net.Uri;
    import android.os.Binder;
    import android.os.Handler;
    import android.os.IBinder;
    import android.os.Message;
    import android.util.Log;
    import android.widget.RemoteViews;
    
    /**
     * @Date 2016-5-31 上午11:32:59
     * @Author Arvin
     * @Description 后台下载新版apk服务
     */ 
    public class DownloadService extends Service {
        private static final String TAG = "DownloadService";
        private Context mContext = this;
        private static final int NOTIFY_ID = 0;
        private int progress;
        private NotificationManager mNotificationManager;
        private boolean canceled;
        // 返回的安装包url
            //http://softfile.3g.qq.com:8080/msoft/179/24659/43549/qq_hd_mini_1.4.apk
        private String apkUrl = "应用服务器地址";
        /* 下载包安装路径 */
        private static final String savePath = "/sdcard/updateApkDemo/";
    
        private static final String saveFileName = savePath + "3GQQ_AppUpdate.apk";
        private ICallbackResult callback;
        private DownloadBinder binder;
        private SczwApplication application;
        private boolean serviceIsDestroy = false;
        private Thread downLoadThread;
        private Notification mNotification;
        private int lastRate = 0;
        
        private static final int MSG_OVER_CANCEL = 0;//下载完毕取消
        private static final int MSG_UPDATE_PROGRESS = 1;//更新下载进度
        private static final int MSG_MANUAL_CANCEL = 2;//手动取消
        
        private Handler mHandler = new Handler() {
    
            @Override
            public void handleMessage(Message msg) {
                // TODO Auto-generated method stub
                super.handleMessage(msg);
                switch (msg.what) {
                case MSG_OVER_CANCEL:
                    application.setDownload(false);
                    // 下载完毕
                    // 取消通知
                    mNotificationManager.cancel(NOTIFY_ID);
                    installApk();
                    break;
                case MSG_MANUAL_CANCEL:
                    application.setDownload(false);
                    // 这里是用户界面手动取消,所以会经过activity的onDestroy();方法
                    // 取消通知
                    mNotificationManager.cancel(NOTIFY_ID);
                    break;
                case MSG_UPDATE_PROGRESS:
                    int rate = msg.arg1;
                    application.setDownload(true);
                    if (rate < 100) {
                        RemoteViews contentview = mNotification.contentView;
                        contentview.setTextViewText(R.id.tv_progress, rate + "%");
                        contentview.setProgressBar(R.id.progressbar, 100, rate, false);
                    } else {
                        // 下载完毕后变换通知形式
                        mNotification.flags = Notification.FLAG_AUTO_CANCEL;
                        mNotification.contentView = null;
                        Intent intent = new Intent(mContext, UpdateNotifiActivity.class);
                        // 告知已完成
                        intent.putExtra("completed", "yes");
                        // 更新参数,注意flags要使用FLAG_UPDATE_CURRENT
                        PendingIntent contentIntent = PendingIntent.getActivity(mContext, 0, intent,
                                PendingIntent.FLAG_UPDATE_CURRENT);
                        mNotification.setLatestEventInfo(mContext, "下载完成", "文件已下载完毕", contentIntent);
                        //
                        serviceIsDestroy = true;
                        stopSelf();// 停掉服务自身
                    }
                    mNotificationManager.notify(NOTIFY_ID, mNotification);
                    break;
                }
            }
        };
    
        @Override
        public IBinder onBind(Intent intent) {
            // TODO Auto-generated method stub
            Log.i(TAG,"是否执行了 onBind");
            return binder;
        }
    
        @Override
        public void onDestroy() {
            // TODO Auto-generated method stub
            super.onDestroy();
            Log.i(TAG,"downloadservice ondestroy");
            // 假如被销毁了,无论如何都默认取消了。
            application.setDownload(false);
        }
    
        @Override
        public boolean onUnbind(Intent intent) {
            // TODO Auto-generated method stub
            Log.i(TAG,"downloadservice onUnbind");
            return super.onUnbind(intent);
        }
    
        @Override
        public void onRebind(Intent intent) {
            // TODO Auto-generated method stub
    
            super.onRebind(intent);
            Log.i(TAG,"downloadservice onRebind");
        }
    
        @Override
        public void onCreate() {
            // TODO Auto-generated method stub
            super.onCreate();
            binder = new DownloadBinder();
            mNotificationManager = (NotificationManager) getSystemService(android.content.Context.NOTIFICATION_SERVICE);
    //      setForeground(true);// 这个不确定是否有作用
            application = SczwApplication.getInstance();
        }
    
        public class DownloadBinder extends Binder {
            public void start() {
                if (downLoadThread == null || !downLoadThread.isAlive()) {
                    progress = 0;
                    setUpNotification();
                    new Thread() {
                        public void run() {
                            // 下载
                            startDownload();
                        };
                    }.start();
                }
            }
    
            public void cancel() {
                canceled = true;
            }
    
            public int getProgress() {
                return progress;
            }
    
            public boolean isCanceled() {
                return canceled;
            }
    
            public boolean serviceIsDestroy() {
                return serviceIsDestroy;
            }
    
            public void cancelNotification() {
                mHandler.sendEmptyMessage(MSG_MANUAL_CANCEL);
            }
    
            public void addCallback(ICallbackResult callback) {
                DownloadService.this.callback = callback;
            }
        }
    
        /**
         * @Description 启动新版apk下载任务
         * @param null
         * @return void
         * @throws
         */
        private void startDownload() {
            // TODO Auto-generated method stub
            canceled = false;
            downloadApk();
        }
    
        /**
         * @Description 创建通知
         * @param null
         * @return void
         * @throws
         */
        private void setUpNotification() {
            int icon = R.drawable.ic_launcher;
            CharSequence tickerText = "开始下载";
            long when = System.currentTimeMillis();
            mNotification = new Notification(icon, tickerText, when);
            // 放置在"正在运行"栏目中
            mNotification.flags = Notification.FLAG_ONGOING_EVENT;
    
            RemoteViews contentView = new RemoteViews(getPackageName(), R.layout.update_notif_ly);
            contentView.setTextViewText(R.id.name, "腾讯QQ.apk 正在下载...");
            // 指定个性化视图
            mNotification.contentView = contentView;
    
            Intent intent = new Intent(this, UpdateNotifiActivity.class);
            // 下面两句是 在按home后,点击通知栏,返回之前activity 状态;
            PendingIntent contentIntent = PendingIntent.getActivity(this, 0, intent,
                    PendingIntent.FLAG_UPDATE_CURRENT);
    
            // 指定内容意图
            mNotification.contentIntent = contentIntent;
            mNotificationManager.notify(NOTIFY_ID, mNotification);
        }
    
        /**
         * @Description 下载新版apk
         * @param tags
         * @return return_type
         * @throws
         */
        private void downloadApk() {
            downLoadThread = new Thread(mdownApkRunnable);
            downLoadThread.start();
        }
    
        /**
         * @Description 安装新版apk
         * @param null
         * @return void
         * @throws
         */
        private void installApk() {
            File apkfile = new File(saveFileName);
            if (!apkfile.exists()) {
                return;
            }
            Intent i = new Intent(Intent.ACTION_VIEW);
            i.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
            i.setDataAndType(Uri.parse("file://" + apkfile.toString()), "application/vnd.android.package-archive");
            mContext.startActivity(i);
            callback.OnBackResult("finish");
    
        }
    
        /**
         * @Description 启动线程下载新版apk
         * @param String
         * @return null
         * @throws
         */
        private Runnable mdownApkRunnable = new Runnable() {
            @Override
            public void run() {
                try {
                    URL url = new URL(apkUrl);
    
                    HttpURLConnection conn = (HttpURLConnection) url.openConnection();
                    conn.connect();
                    int length = conn.getContentLength();
                    InputStream is = conn.getInputStream();
    
                    File file = new File(savePath);
                    if (!file.exists()) {
                        file.mkdirs();
                    }
                    String apkFile = saveFileName;
                    File ApkFile = new File(apkFile);
                    FileOutputStream fos = new FileOutputStream(ApkFile);
    
                    int count = 0;
                    byte buf[] = new byte[1024];
    
                    do {
                        int numread = is.read(buf);
                        count += numread;
                        progress = (int) (((float) count / length) * 100);
                        // 更新进度
                        Message msg = mHandler.obtainMessage();
                        msg.what = MSG_UPDATE_PROGRESS;
                        msg.arg1 = progress;
                        if (progress >= lastRate + 1) {
                            mHandler.sendMessage(msg);
                            lastRate = progress;
                            if (callback != null)
                                callback.OnBackResult(progress);
                        }
                        if (numread <= 0) {
                            // 下载完成通知安装
                            mHandler.sendEmptyMessage(MSG_OVER_CANCEL);
                            // 下载完了,cancelled也要设置
                            canceled = true;
                            break;
                        }
                        fos.write(buf, 0, numread);
                    } while (!canceled);// 点击取消就停止下载.
    
                    fos.close();
                    is.close();
                } catch (MalformedURLException e) {
                    e.printStackTrace();
                } catch (IOException e) {
                    e.printStackTrace();
                }
    
            }
        };
    
    }
    
    

    应用更新相关文章:
    应用更新之_UpdateNotifiActivity
    应用更新之_update_activity.xml
    应用更新之_update_notif_ly.xml
    应用更新之_permission

    相关文章

      网友评论

          本文标题:应用更新之_DownloadService

          本文链接:https://www.haomeiwen.com/subject/ycdwmttx.html