}
public LoadingService() {
super(“MyService”);
}
public static void startUploadImg(Context context)
{
Intent intent = new Intent(context, LoadingService.class);
context.startService(intent);
}
public void onCreate() {
super.onCreate();
httpUtils = new HttpUtils();
httpUtils.configCurrentHttpCacheExpiry(0);
nm = (NotificationManager) getSystemService(Context.NOTIFICATION_SERVICE);
sharedPreferences = getSharedPreferences(“data”,MODE_PRIVATE);
}
@Override
protected void onHandleIntent(@Nullable Intent intent) {
updateApk();
}
private void updateApk(){
url = sharedPreferences.getString(“url”,“”);
path = sharedPreferences.getString(“path”,“”);
httpUtils.download(url,
path , new RequestCallBack() {
@Override
public void onLoading(final long total, final long current,
boolean isUploading) {
createNotification(total,current);
sendBroadcast(new Intent().setAction(“android.intent.action.loading”));//发送正在下载的广播
super.onLoading(total, current, isUploading);
}
@Override
public void onSuccess(ResponseInfo arg0) {
nm.cancel(R.layout.notification_item);
Toast.makeText(LoadingService.this,“下载成功…”,Toast.LENGTH_SHORT).show();
installApk();//下载成功 打开安装界面
stopSelf();//结束服务
sendBroadcast(new Intent().setAction(“android.intent.action.loading_over”));//发送下载结束的广播
}
@Override
public void onFailure(HttpException arg0, String arg1) {
Toast.makeText(LoadingService.this,“下载失败…”,Toast.LENGTH_SHORT).show();
sendBroadcast(new Intent().setAction(“android.intent.action.loading_over”));//发送下载结束的广播
nm.cancel(R.layout.notification_item);
stopSelf();
}
});
}
/**
- 安装下载的新版本
*/
protected void installApk() {
Intent intent = new Intent(Intent.ACTION_VIEW);
intent.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
File file = new File(path);
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.N) {
// 7.0 以上
try {
Uri apkUri = FileProvider.getUriForFile(this, “com.jw.fileprovider”, file);
intent.addFlags(Intent.FLAG_GRANT_READ_URI_PERMISSION | Intent.FLAG_GRANT_WRITE_URI_PERMISSION);
intent.setDataAndType(apkUri, “application/vnd.android.package-archive”);
}catch (Exception e){
}
} else {
// 7.0以下
Uri uri = Uri.fromFile(file);
intent.setDataAndType(uri, “application/vnd.android.package-archive”);
}
this.startActivity(intent);
}
private void createNotification(final long total, final long current){
NotificationCompat.Builder builder = new NotificationCompat.Builder(this,“default”);
builder.setSmallIcon(R.mipmap.ic_launcher)//必须要设置这个属性,否则不显示
;
RemoteViews contentView = new RemoteViews(this.getPackageName(),R.layout.notification_item);
contentView.setProgressBar(R.i