Android 自动更新 后代通知栏显示进度

来源:互联网 发布:网络兼职项目申请表 编辑:程序博客网 时间:2024/05/18 03:06

app的更新功能

开启一个服务后台下载apk 并且在通知栏显示进度

package com.baidu.text;import android.app.IntentService;import android.app.Notification;import android.app.NotificationManager;import android.app.PendingIntent;import android.app.Service;import android.content.Intent;import android.graphics.BitmapFactory;import android.net.Uri;import android.os.Environment;import android.support.v7.app.NotificationCompat;import android.util.Log;import java.io.File;import java.io.FileOutputStream;import java.io.IOException;import java.io.InputStream;import java.net.HttpURLConnection;import java.net.URL;/* *  @项目名:  text  *  @包名:    com.baidu.text *  @文件名:   MyIntentService *  @创建者:   okmin *  @创建时间:  2016/12/15 0015 14:16 *  @描述:    TODO */public class MyIntentService extends IntentService {    private    String                     mDownloadUrl;//APK的下载路径    private NotificationManager        mNotificationManager;    private Notification               mNotification;    private File                       mFile;    private NotificationCompat.Builder mBuilder;    /**     * Creates an IntentService.  Invoked by your subclass's constructor.     *     */    public MyIntentService() {        super("MyIntentService");    }    @Override    protected void onHandleIntent(Intent intent) {        mDownloadUrl = intent.getStringExtra("apkUrl");//获取下载APK的链接        mNotificationManager = (NotificationManager) getSystemService(Service.NOTIFICATION_SERVICE);        downloadFile();//下载APK    }    private void downloadFile() {        FileOutputStream fos = null;        InputStream      is  = null;        try {            URL               url  = new URL(mDownloadUrl);            HttpURLConnection conn = (HttpURLConnection) url.openConnection();            conn.setConnectTimeout(8000);            conn.setReadTimeout(8000);            conn.connect();            if (conn.getResponseCode() == 200) {                int max = conn.getContentLength();                mFile = new File(Environment.getExternalStorageDirectory(), "new.apk");                fos = new FileOutputStream(mFile);                is = conn.getInputStream();                byte[] buffer = new byte[1024];                int len;                int progress = 0;                while ((len = is.read(buffer)) > 1) {                    fos.write(buffer, 0, len);                    progress += len;                    inProgress(progress,max);                }            }        } catch (Exception e) {            e.printStackTrace();        } finally {            if (fos!=null) {                try {                    fos.close();                } catch (IOException e) {                    e.printStackTrace();                }            }            if (is!=null) {                try {                    is.close();                } catch (IOException e) {                    e.printStackTrace();                }            }        }    }    public void inProgress(int progress, int total) {        int pro=progress*100/total;        Log.e("dfsf", "max"+total+"progress"+progress+"百分比"+pro);        if (pro % 5 == 0) {            //避免频繁刷新View,这里设置每下载5%提醒更新一次进度            notifyMsg("温馨提醒", "文件正在下载..", pro);        }    }    private void notifyMsg(String title, String content, int progress) {        if (mBuilder==null) {            mBuilder = new NotificationCompat.Builder(this);            mBuilder.setSmallIcon(R.mipmap.ic_launcher).setLargeIcon(BitmapFactory.decodeResource(getResources(), R.mipmap.ic_launcher)).setContentTitle(title);        }        if (progress > 0 && progress < 100) {            //下载进行中            mBuilder.setProgress(100, progress, false);        } else {            mBuilder.setProgress(0, 0, false);        }        mBuilder.setAutoCancel(true);        mBuilder.setWhen(System.currentTimeMillis());        if (progress >= 100) {            //下载完成            mBuilder.setContentIntent(getInstallIntent());            mBuilder.setContentText("下载完成点击安装");        } else {            mBuilder.setContentText(content);        }        mNotification = mBuilder.build();        mNotificationManager.notify(0, mNotification);    }    private PendingIntent getInstallIntent() {        Intent intent = new Intent(Intent.ACTION_VIEW);        intent.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK);        intent.setDataAndType(Uri.parse("file://" + mFile.getAbsolutePath()), "application/vnd.android.package-archive");        PendingIntent pendingIntent = PendingIntent.getActivity(this, 0, intent, PendingIntent.FLAG_UPDATE_CURRENT);        return pendingIntent;    }}
想立马看见效果只需要调用 这是一个下载豌豆荚的链接

 Intent intent = new Intent(this, MyIntentService.class);        String str="http://a.wdjcdn.com/release/files/phoenix/5.23.1.12064/wandoujia-wandoujia-web_inner_referral_binded_5.23.1.12064.apk?remove=2&append=%94%00eyJhcHBEb3dubG9hZCI6eyJkb3dubG9hZFR5cGUiOiJkb3dubG9hZF9ieV9wYWNrYWdlX25hbWUiLCJwYWNrYWdlTmFtZSI6ImNvbS5leGFtcGxlLmRhb2RpYW53YW5nIn19Wdj01B0000842730";        intent.putExtra("apkUrl", str);        startService(intent);
其中你可以会遇见这个错误

12-15 14:52:22.726 7884-8717/com.baidu.text W/System.err: java.lang.RuntimeException:bad array lengths
12-15 14:52:22.746 7884-8717/com.baidu.text W/System.err:     at android.os.Parcel.readIntArray(Parcel.java:820)
12-15 14:52:22.746 7884-8717/com.baidu.text W/System.err:     at android.app.INotificationManager$Stub$Proxy.enqueueNotificationWithTag(INotificationManager.java:321)
12-15 14:52:22.746 7884-8717/com.baidu.text W/System.err:     at android.app.NotificationManager.notify(NotificationManager.java:136)
12-15 14:52:22.746 7884-8717/com.baidu.text W/System.err:     at android.app.NotificationManager.notify(NotificationManager.java:109)
12-15 14:52:22.746 7884-8717/com.baidu.text W/System.err:     at com.baidu.text.MyIntentService.notifyMsg(MyIntentService.java:125)
12-15 14:52:22.746 7884-8717/com.baidu.text W/System.err:     at com.baidu.text.MyIntentService.inProgress(MyIntentService.java:101)
12-15 14:52:22.746 7884-8717/com.baidu.text W/System.err:     at com.baidu.text.MyIntentService.downloadFile(MyIntentService.java:72)
12-15 14:52:22.746 7884-8717/com.baidu.text W/System.err:     at com.baidu.text.MyIntentService.onHandleIntent(MyIntentService.java:48)
12-15 14:52:22.746 7884-8717/com.baidu.text W/System.err:     at android.app.IntentService$ServiceHandler.handleMessage(IntentService.java:65)
12-15 14:52:22.746 7884-8717/com.baidu.text W/System.err:     at android.os.Handler.dispatchMessage(Handler.java:102)
12-15 14:52:22.746 7884-8717/com.baidu.text W/System.err:     at android.os.Looper.loop(Looper.java:136)
12-15 14:52:22.746 7884-8717/com.baidu.text W/System.err:     at android.os.HandlerThread.run(HandlerThread.java:61)
这是因为你过于频繁的修改通知的一个进度了.所以我每隔5%才去更新进度 setProgress

根据手机性能报错的次数不一样

只要不太频繁就不会出问题

1 0