android实现通知栏下载更新app示例

2019-12-10 20:08:19王冬梅

//获取传值
titleId = intent.getIntExtra("titleId",0);
//创建文件
if(android.os.Environment.MEDIA_MOUNTED.equals(android.os.Environment.getExternalStorageState())){
updateDir = new File(Environment.getExternalStorageDirectory(),Global.downloadDir);
updateFile = new File(updateDir.getPath(),getResources().getString(titleId)+".apk");
}

 

this.updateNotificationManager = (NotificationManager)getSystemService(NOTIFICATION_SERVICE);
this.updateNotification = new Notification();

//设置下载过程中,点击通知栏,回到主界面
updateIntent = new Intent(this, SubwayActivity.class);
updatePendingIntent = PendingIntent.getActivity(this,0,updateIntent,0);
//设置通知栏显示内容
updateNotification.icon = R.drawable.arrow_down_float;
updateNotification.tickerText = "开始下载";
updateNotification.setLatestEventInfo(this,"上海地铁","0%",updatePendingIntent);
//发出通知
updateNotificationManager.notify(0,updateNotification);

//开启一个新的线程下载,如果使用Service同步下载,会导致ANR问题,Service本身也会阻塞
new Thread(new updateRunnable()).start();//这个是下载的重点,是下载的过程

return super.onStartCommand(intent, flags, startId);
}


上面都是准备工作

 

从代码中可以看出来,updateRunnable类才是真正下载的类,出于用户体验的考虑,这个类是我们单独一个线程后台去执行的。
下载的过程有两个工作:1.从服务器上下载数据;2.通知用户下载的进度。
线程通知,我们先定义一个空的updateHandler。
[/code]
private Handler updateHandler = new Handler(){
@Override
public void handleMessage(Message msg) {

}
};
[/code]
再来创建updateRunnable类的真正实现:

复制代码
class updateRunnable implements Runnable {
Message message = updateHandler.obtainMessage();
public void run() {
message.what = DOWNLOAD_COMPLETE;
try{
//增加权限<uses-permission android:name="android.permission.WRITE_EXTERNAL_STORAGE">;
if(!updateDir.exists()){
updateDir.mkdirs();
}
if(!updateFile.exists()){
updateFile.createNewFile();
}
//下载函数,以QQ为例子
//增加权限<uses-permission android:name="android.permission.INTERNET">;