这次是我第一次写博客哦,各位程序大哥大姐们多多捧场啊.,下面是我自己写的一个像支付宝一样在
通知栏弹出notification来动态实时更新app版本,成功则让用户点击安装,失败则可以点击重试,也可以点击取消.
里面用了广播接收者和service组件.
话不多说,直接上代码啦.
首先是activity判断是否需要更新,如果需要更新,则把URL放到bundle里,传递给service
public void update() {
Intent intent = new Intent(this, UpdateService.class);
//这里是以支付宝的APP URL 来当作更新的APP, 大家自行修改就行啦
intent.putExtra("downUrl", "http://tfs.alipayobjects.com/L1/71/100/and/alipay_wap_main.apk");
startService(intent);
}
接下来就是更新的service了,我用到了xutils框架,其实没什么东西,如果你没用过的话,你就用个别的能下载,下载完了 成功和失败都有回调就行啦.
package com.ycb.www.news.services;
import android.app.Service;
import android.content.Intent;
import android.os.Environment;
import android.os.IBinder;
import android.support.annotation.Nullable;
import android.text.TextUtils;
import android.util.Log;
import com.lidroid.xutils.HttpUtils;
import com.lidroid.xutils.exception.HttpException;
import com.lidroid.xutils.http.HttpHandler;
import com.lidroid.xutils.http.ResponseInfo;
import com.lidroid.xutils.http.callback.RequestCallBack;
import java.io.File;
import java.text.NumberFormat;
/**
* 下载的services,配合xutils的httputils使用,完成notification的下载功能
*/
public class UpdateService extends Service{
//是否已经开始下载
private boolean isBegin=false;
Intent intent ;
public static HttpHandler<File> downLoadHandler;
private NumberFormat numberFormat;
@Nullable
@Override
public IBinder onBind(Intent intent) {
return null;
}
@Override
public void onCreate() {
super.onCreate();
intent =new Intent();
numberFormat = NumberFormat.getInstance();
numberFormat.setMaximumFractionDigits(2);
}
@Override
public int onStartCommand(Intent intent, int flags, int startId) {
String downUrl = intent.getStringExtra("downUrl");
//如果下载地址为空,则什么都不干
if(TextUtils.isEmpty(downUrl)){
stopSelf();
// throw new IllegalArgumentException("the download url is empty!!!!");
return 0;
}
if(isBegin){
//此时已经开始了
return 0;