android之apk自动更新采用Notification通知提示并显示下载进度

来源:互联网 发布:pps网络电视apk下载 编辑:程序博客网 时间:2024/06/11 12:48

        首先整理一下apk自动更新的思路:1 比较服务器和本地apk的版本;2 如果服务器版本比较新,那么发出Notification通知用户下载;3用户点击开始下载;4下载完成发出用户提示用户点击安装;5 用户点击安装完成结束整个流程;

        下面是效果图,可以先看下是否是你想要的效果咯,亲!

        ok,接下来直接上代码。版本比较这个东西就不讲了,出发出Notification通知开始

//概要String tickerText = context.getResources().getText(R.string.app_name).toString()+"发现新版本,建议您更新!";//标题String title = context.getResources().getText(R.string.app_name).toString()+"更新";//内容String content= "点击更新"+context.getResources().getText(R.string.app_name).toString();//logoint icon = R.drawable.logo;Notification notification = new Notification(icon, tickerText, System.currentTimeMillis());Intent updateinte = new Intent(context,UpdateService.class);updateinte.putExtra("url",re);PendingIntent pendingIntent = PendingIntent.getService(context, 0, updateinte, 0);//点击打开service下载notification.setLatestEventInfo(context, title, content, pendingIntent);notification.defaults = Notification.DEFAULT_SOUND;notification.flags = Notification.FLAG_AUTO_CANCEL;NotificationManager manager = (NotificationManager) context.getSystemService(Context.NOTIFICATION_SERVICE);manager.notify(101, notification);
       下面是service下载类。下面的代码我自己遇到两个问题,Notification版本兼容系问题在http://blog.csdn.net/caicongyang/article/details/10190727做了解释,下载完成后解析包出现问题在http://blog.csdn.net/caicongyang/article/details/10183095做了解析,其他的很简单!

/** * 下载更新服务 * @author Tom.Cai * */public class UpdateService extends Service {private String url = null;// 通知栏private NotificationManager updateNotificationManager = null;private Notification updateNotification = null;private String appName = null;private String fileName = null;private String updateDir = null;//通知栏跳转Intent@Overridepublic int onStartCommand(Intent intent, int flags, int startId) {// 获取传值url = intent.getStringExtra("url");appName = getApplication().getResources().getText(R.string.app_name).toString();if (url != null) {fileName = url.substring(url.lastIndexOf("/")+1);updateDir = Environment.getDataDirectory() + "/data/" + this.getPackageName() + "/files/";Intent nullIntent = new Intent();PendingIntent pendingIntent = PendingIntent.getActivity(getApplicationContext(), 0, nullIntent, 0);// 创建文件updateNotificationManager = (NotificationManager) getSystemService(NOTIFICATION_SERVICE);updateNotification = new Notification();updateNotification.icon = R.drawable.logo;updateNotification.tickerText = "正在更新" + appName;updateNotification.setLatestEventInfo(getApplication(), "正在下载"+appName,"0%", null);updateNotification.defaults = Notification.DEFAULT_SOUND;updateNotification.flags = Notification.FLAG_AUTO_CANCEL;updateNotification.contentIntent = pendingIntent;updateNotificationManager.notify(101, updateNotification);//开启线程现在new Thread(new updateRunnable()).start();}return super.onStartCommand(intent, 0, 0);}private class updateRunnable implements Runnable {Message message = updateHandler.obtainMessage();public void run() {message.what = 0;try {long downloadSize = downloadUpdateFile(url);Log.i("cai", downloadSize/1024+"");if (downloadSize > 0) {// 下载成功updateHandler.sendMessage(message);}} catch (Exception ex) {ex.printStackTrace();message.what = 1;// 下载失败updateHandler.sendMessage(message);}}}private Handler updateHandler = new Handler() {@Overridepublic void handleMessage(Message msg) {switch (msg.what) {case 0:/*try {Runtime.getRuntime().exec("chmod 777 " + updateDir.getAbsolutePath());Runtime.getRuntime().exec("chmod 777 " + updateFile.getAbsolutePath());} catch (IOException e) {e.printStackTrace();}*/// 点击安装PendingIntentIntent installIntent = new Intent(Intent.ACTION_VIEW);//installIntent.addFlags(Intent.FLAG_ACTIVITY_RESET_TASK_IF_NEEDED| Intent.FLAG_ACTIVITY_NEW_TASK);installIntent.setDataAndType(Uri.fromFile(new File(updateDir,fileName)),"application/vnd.android.package-archive");//getApplication().startActivity(installIntent);*/PendingIntent updatePendingIntent = PendingIntent.getActivity(UpdateService.this, 0, installIntent, 0);updateNotification.defaults = Notification.DEFAULT_SOUND;// 铃声提醒updateNotification.flags = Notification.FLAG_AUTO_CANCEL;updateNotification.setLatestEventInfo(UpdateService.this,appName, "下载完成,点击安装", updatePendingIntent);updateNotificationManager.notify(101, updateNotification);// 停止服务stopSelf();break;case 1:Intent nullIntent = new Intent();PendingIntent pendingIntent = PendingIntent.getActivity(UpdateService.this, 10, nullIntent, 0);// 下载失败updateNotification.setLatestEventInfo(UpdateService.this,appName, "网络连接不正常,下载失败!", pendingIntent);updateNotification.flags = Notification.FLAG_AUTO_CANCEL;updateNotificationManager.notify(101, updateNotification);break;default:stopSelf();}}};//下载@SuppressLint("WorldReadableFiles")public long downloadUpdateFile(String downloadUrl) throws Exception {        int downloadCount = 0;        int currentSize = 0;        long totalSize = 0;        int updateTotalSize = 0;                 HttpURLConnection httpConnection = null;        InputStream is = null;        FileOutputStream fos = null;                 try {            URL url = new URL(downloadUrl);            httpConnection = (HttpURLConnection)url.openConnection();            if(currentSize > 0) {                httpConnection.setRequestProperty("RANGE", "bytes=" + currentSize + "-");            }            httpConnection.setConnectTimeout(10000);            httpConnection.setReadTimeout(20000);            updateTotalSize = httpConnection.getContentLength();            if (httpConnection.getResponseCode() == 404) {                throw new Exception("fail!");            }            is = httpConnection.getInputStream();                              /* fos = new FileOutputStream(saveFile, false);*/            fos =  openFileOutput(fileName, MODE_WORLD_READABLE);                        byte buffer[] = new byte[4096];            int readsize = 0;            while((readsize = is.read(buffer)) > 0){                fos.write(buffer, 0, readsize);                totalSize += readsize;                //为了防止频繁的通知导致应用吃紧,百分比增加10才通知一次                if((downloadCount == 0)||(int) (totalSize*100/updateTotalSize)-10>downloadCount){                     downloadCount += 10;                    Intent nullIntent = new Intent();                    PendingIntent pendingIntent = PendingIntent.getActivity(getApplicationContext(), 0, nullIntent, 0);                    updateNotification.contentIntent = pendingIntent;                    updateNotification.setLatestEventInfo(UpdateService.this, appName+"正在下载", (int)totalSize*100/updateTotalSize+"%", null);                    updateNotificationManager.notify(101, updateNotification);                }                                    }        } finally {            if(httpConnection != null) {                httpConnection.disconnect();            }            if(is != null) {                is.close();            }            if(fos != null) {                fos.close();            }        }        return totalSize;    }@Overridepublic IBinder onBind(Intent intent) {return null;}}
        以上类并没有进行优化,仅可作为学习参考。欢迎留言讨论。。。






原创粉丝点击