在网上查询了下,Android版本号更新通知栏带进度条,醉了,基本都是复制过来。有的代码不全,连源代码下载都没有,有下载也须要积分。还不能用。真黑心啊!!

之前自己也写过自己定义通知栏Notification,想了还是自己写吧。

由于在通知栏更新,须要訪问网络下载,就写了个服务。在服务中实现了下载个更新。

先看MainActivity代码:

package com.wsj.wsjdemo;import android.os.Bundle;
import android.app.Activity;
import android.app.AlertDialog;
import android.content.DialogInterface;
import android.content.Intent;
import android.view.Menu;public class MainActivity extends Activity {@Overrideprotected void onCreate(Bundle savedInstanceState) {super.onCreate(savedInstanceState);setContentView(R.layout.activity_main);initGlobal();checkVersion();}/*** 初始化全局变量* 实际工作中这种方法中serverVersion从服务器端获取,最好在启动画面的activity中运行*/public void initGlobal(){try{Global.localVersion = getPackageManager().getPackageInfo(getPackageName(),0).versionCode; //设置本地版本号号Global.serverVersion = 2;//假定服务器版本号为2,本地版本号默认是1}catch (Exception ex){ex.printStackTrace();}}/*** 检查更新版本号*/public void checkVersion(){if(Global.localVersion < Global.serverVersion){//发现新版本号。提示用户更新AlertDialog.Builder alert = new AlertDialog.Builder(this);alert.setTitle("软件升级").setMessage("发现新版本号,建议马上更新使用.").setPositiveButton("更新", new DialogInterface.OnClickListener() {public void onClick(DialogInterface dialog, int which) {//开启更新服务UpdateService//这里为了把update更好模块化,能够传一些updateService依赖的值//如布局ID,资源ID。动态获取的标题,这里以app_name为例Intent updateIntent =new Intent(MainActivity.this, UpdateService.class);updateIntent.putExtra("app_name",R.string.app_name);updateIntent.putExtra("downurl","http://www.subangloan.com/Contract/App/Android/caijia_unsign_signed.apk");startService(updateIntent);}}).setNegativeButton("取消",new DialogInterface.OnClickListener(){public void onClick(DialogInterface dialog, int which) {dialog.dismiss();}});alert.create().show();}else{//清理工作,略去//cheanUpdateFile(),文章后面我会附上代码}}
}

activity_main.xml文件:什么都没有就一个简单界面

<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"xmlns:tools="http://schemas.android.com/tools"android:layout_width="match_parent"android:layout_height="match_parent" ><TextViewandroid:layout_width="wrap_content"android:layout_height="wrap_content"android:text="@string/hello_world" /></LinearLayout>

在Main中的用到的Global.java

package com.wsj.wsjdemo;public class Global {//版本号信息public static int localVersion = 0;public static int serverVersion = 0;public static String downloadDir = "app/download/";
}

写的服务实现UpdateService.java

package com.wsj.wsjdemo;import java.io.File;
import java.io.IOException;
import java.text.DecimalFormat;import com.lidroid.xutils.HttpUtils;
import com.lidroid.xutils.exception.HttpException;
import com.lidroid.xutils.http.ResponseInfo;
import com.lidroid.xutils.http.callback.RequestCallBack;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.Handler;
import android.os.IBinder;
import android.os.Message;
import android.widget.RemoteViews;public class UpdateService extends Service {private static String down_url; // = "http://192.168.1.112:8080/360.apk";private static final int DOWN_OK = 1; // 下载完毕private static final int DOWN_ERROR = 0;private String app_name;private NotificationManager notificationManager;private Notification notification;private Intent updateIntent;private PendingIntent pendingIntent;private String updateFile;private int notification_id = 0;long totalSize = 0;// 文件总大小/**** 更新UI*/final Handler handler = new Handler() {@SuppressWarnings("deprecation")@Overridepublic void handleMessage(Message msg) {switch (msg.what) {case DOWN_OK:// 下载完毕,点击安装Intent installApkIntent = getFileIntent(new File(updateFile));pendingIntent = PendingIntent.getActivity(UpdateService.this, 0, installApkIntent, 0);notification.contentIntent = pendingIntent;notification.flags |= Notification.FLAG_AUTO_CANCEL;notification.setLatestEventInfo(UpdateService.this, app_name, "下载成功,点击安装", pendingIntent);notificationManager.notify(notification_id, notification);stopService(updateIntent);break;case DOWN_ERROR:notification.setLatestEventInfo(UpdateService.this, app_name, "下载失败", pendingIntent);break;default:stopService(updateIntent);break;}}};@Overridepublic IBinder onBind(Intent arg0) {return null;}@Overridepublic int onStartCommand(Intent intent, int flags, int startId) {if (intent != null) {try {app_name = intent.getStringExtra("app_name");down_url = intent.getStringExtra("downurl");// 创建文件File updateFile = FileUtils.getDiskCacheDir(getApplicationContext(), "xxxx.apk");if (!updateFile.exists()) {try {updateFile.createNewFile();} catch (IOException e) {e.printStackTrace();}}// 创建通知createNotification();// 開始下载downloadUpdateFile(down_url, updateFile.getAbsolutePath());} catch (Exception e) {e.printStackTrace();}}return super.onStartCommand(intent, flags, startId);}/**** 创建通知栏*/RemoteViews contentView;@SuppressWarnings("deprecation")public void createNotification() {notificationManager = (NotificationManager) getSystemService(Context.NOTIFICATION_SERVICE);notification = new Notification();notification.icon = R.drawable.ic_launcher;// 这个參数是通知提示闪出来的值.notification.tickerText = "開始下载";// pendingIntent = PendingIntent.getActivity(this, 0, updateIntent, 0);// 这里面的參数是通知栏view显示的内容notification.setLatestEventInfo(this, app_name, "下载:0%", pendingIntent);// notificationManager.notify(notification_id, notification);/**** 在这里我们用自定的view来显示Notification*/contentView = new RemoteViews(getPackageName(), R.layout.notification_item);contentView.setTextViewText(R.id.notificationTitle, "正在下载");contentView.setTextViewText(R.id.notificationPercent, "0%");contentView.setProgressBar(R.id.notificationProgress, 100, 0, false);notification.contentView = contentView;updateIntent = new Intent(this, MainActivity.class);updateIntent.addFlags(Intent.FLAG_ACTIVITY_SINGLE_TOP);pendingIntent = PendingIntent.getActivity(this, 0, updateIntent, 0);notification.contentIntent = pendingIntent;notificationManager.notify(notification_id, notification);}/**** 下载文件*/public void downloadUpdateFile(String down_url, String file) throws Exception {updateFile = file;HttpUtils HttpUtils = new HttpUtils();HttpUtils.download(down_url, file, new RequestCallBack<File>() {@Overridepublic void onSuccess(ResponseInfo<File> responseInfo) {// 下载成功Message message = handler.obtainMessage();message.what = DOWN_OK;handler.sendMessage(message);installApk(new File(updateFile), UpdateService.this);}@Overridepublic void onFailure(HttpException error, String msg) {Message message = handler.obtainMessage();message.what = DOWN_ERROR;handler.sendMessage(message);}@Overridepublic void onLoading(long total, long current, boolean isUploading) {super.onLoading(total, current, isUploading);double x_double = current * 1.0;double tempresult = x_double / total;DecimalFormat df1 = new DecimalFormat("0.00"); // ##.00%// 百分比格式。后面不足2位的用0补齐String result = df1.format(tempresult);contentView.setTextViewText(R.id.notificationPercent, (int) (Float.parseFloat(result) * 100) + "%");contentView.setProgressBar(R.id.notificationProgress, 100, (int) (Float.parseFloat(result) * 100), false);notificationManager.notify(notification_id, notification);}});}// 下载完毕后打开安装apk界面public static void installApk(File file, Context context) {//L.i("msg", "版本号更新获取sd卡的安装包的路径=" + file.getAbsolutePath());Intent openFile = getFileIntent(file);context.startActivity(openFile);}public static Intent getFileIntent(File file) {Uri uri = Uri.fromFile(file);String type = getMIMEType(file);Intent intent = new Intent("android.intent.action.VIEW");intent.addCategory("android.intent.category.DEFAULT");intent.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK);intent.setDataAndType(uri, type);return intent;}public static String getMIMEType(File f) {String type = "";String fName = f.getName();// 取得扩展名String end = fName.substring(fName.lastIndexOf(".") + 1, fName.length());if (end.equals("apk")) {type = "application/vnd.android.package-archive";} else {// /*假设无法直接打开。就跳出软件列表给用户选择 */type = "*/*";}return type;}
}

基本上凝视写的清清楚楚,这当中用到了Xutils开源框架来下载文件。

如过你认为看的麻烦直接点击下载demo吧,不须要积分.。。。

Android更新带进度条的通知栏相关推荐

  1. android自定义带进度条的圆形图片

    前言:在项目听新闻的改版中需要实现环绕圆形新闻图片的进度条功能,作为技术预备工作我就去看了一些网上的相关的原理,做了一个自定义带进度条的圆形图片的demo,并将这个实现写成文章发布出来,谁需要了可以进 ...

  2. Android 通过蒲公英pgyer的接口 Service 实现带进度下载App 通知栏显示 在线更新 自动更新Demo

    Android 通过蒲公英pgyer的接口 Service 实现带进度下载App 通知栏显示 在线更新 自动更新Demo 标签: app在线更新下载Update升级 2016-09-18 20:47  ...

  3. web app升级—带进度条的App自动更新

    带进度条的App自动更新,效果如下图所示:   技术:vue.vant-ui.5+ 封装独立组件AppProgress.vue: <template><div><van- ...

  4. Android开发之带进度条的WebView

    老套路先看效果: 直接上代码: 区分java和kotlin版本 Java版本: package com.example.progresswebview;import android.os.Bundle ...

  5. android解压zip文件进度条,Android实现文件解压带进度条功能

    解压的工具类 package com.example.videodemo.zip; public class ZipProgressUtil { /*** * 解压通用方法 * * @param zi ...

  6. android 上传图片进度条,Android带进度条的文件上传示例(使用AsyncTask异步任务)...

    最近项目中要做一个带进度条的上传文件的功能,学习了AsyncTask,使用起来比较方便,将几个方法实现就行,另外做了一个很简单的demo,希望能对大家有帮助,在程序中设好文件路径和服务器IP即可. d ...

  7. Android花样loading进度条(四)-渐变色环形进度条

    背景 Android花样loading进度条系列文章主要讲解如何自定义所需的进度条,包括水平.圆形.环形.圆弧形.不规则形状等. 本篇我们对配文字环形进度条稍加变换,将圆环颜色改为渐变色的形式,使得进 ...

  8. 带进度条的ASP无组件断点续传下载代码

    <%@LANGUAGE="VBSCRIPT" CODEPAGE="936"%> <%Option Explicit%> <% '= ...

  9. 用MediaPlayer做个带进度条可后台的音乐播放器

    传送到github看源码 下载apk试用 密码:rukn 前言 想在天朝听音乐还是有些难度的, 一般来说, 两三个app还是要的. 那何不尝试自己做个手机播放器, 听个爽呢?!今天就带大家先做个简单的 ...

最新文章

  1. 咸阳高考成绩查询2021,2021咸阳市地区高考成绩排名查询,咸阳市高考各高中成绩喜报榜单...
  2. 关于使用pietty或putty终端连接ubuntu虚拟机时报被拒绝连接问题
  3. markdown图片设置
  4. bzoj2463 [中山市选2009]谁能赢呢?
  5. 获取滑动条高度_HexMap学习笔记(三)——海拔高度与阶梯连接
  6. 俄亥俄州立大学哥伦布分校计算机科学,美国俄亥俄州立大学哥伦布分校计算机科学与工程硕士专业入学要求精选.pdf...
  7. 扬帆牧哲-跨境电商的新路径
  8. uva10105 - Polynomial Coefficients(多项式系数)
  9. 计算机显示应用程序错误窗口,电脑出现应用程序错误窗口怎么办
  10. 一定要看:如何成为一名全栈工程师?
  11. 解决Android Studio无法下载
  12. 根据人民币大写规则写的java工具类
  13. Java,Android,计算机原理视频,500G视频资料
  14. Android音频可视化
  15. DB、DBMS、SQL分别是什么,有什么关系?
  16. 基于数据指纹的增量式
  17. 笨方法学Python—ex42:对象、类及从属关系
  18. java ppt转换为html5,Apache POI PPT - PPT转换为图片
  19. 常见Android面试题整理
  20. C++ 堆区,栈区,数据段,bss段,代码区(详解)

热门文章

  1. 知方可补不足~SQL中的count命令的一些优化措施(百万以上数据明显)
  2. 逻辑电路 - 与非门Nand Gate
  3. 【网摘】GTK中文显示解决方案
  4. WCF(Sender) to MSMQ to WCF(Receiver)
  5. 学会处理ASP.NET的页面和请求状态信息 (转载)
  6. 设计模式快速学习(六)模板模式
  7. Activity的setContentView的流程
  8. 简单的分页控件(原创)
  9. POJ 2186 Tarjan
  10. java第二阶段学习day5