package com.app.retrofit;
import android.app.ActivityManager;
import android.app.IntentService;
import android.app.Notification;
import android.app.NotificationManager;
import android.content.Context;
import android.content.Intent;
import android.net.Uri;
import android.os.Bundle;
import android.os.Handler;
import android.os.IBinder;
import android.os.Looper;
import android.support.annotation.Nullable;
import android.util.Log;
import android.widget.RemoteViews;
import android.widget.Toast;
import com.app.retrofit.api.Network;
import java.io.File;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
import java.util.HashMap;
import java.util.Map;
import okhttp3.ResponseBody;
import retrofit2.Call;
import retrofit2.Response;
/**
* author: Yangbin
* time : 2016/11/10 18:02
* desc : 下载app
*/
public class DownLoadAppService extends IntentService {
private static String TAG = "UpdataAppThread";
// NotificationManager : 是状态栏通知的管理类,负责发通知、清楚通知等。
private NotificationManager manager;
private int notifiId = 789;
private int progress = 0;
private String apkName;
// 定义Map来保存Notification对象
private Map<Integer, Notification> map = null;
public DownLoadAppService() {
super("DownLoadAppService");
}
public static void startDownLoadAppService(Context cxt, String apkName, String url) {
ActivityManager manager = (ActivityManager) cxt.getSystemService(ACTIVITY_SERVICE);
for (ActivityManager.RunningServiceInfo service : manager.getRunningServices(Integer.MAX_VALUE)) {
if (DownLoadAppService.class.getName().equals(service.service.getClassName())) {
Log.d(TAG, "-->不再启动服务,已经在下载更新了");
return;//退出不再继续执行
}
}
Intent startServiceIntent = new Intent(cxt, DownLoadAppService.class);
Bundle bundle2 = new Bundle();
bundle2.putString("apkName", apkName);
bundle2.putString("url", url);
startServiceIntent.putExtras(bundle2);
Log.d(TAG, "-->启动了下载服务");
cxt.startService(startServiceIntent);
}
@Nullable
@Override
public IBinder onBind(Intent intent) {
return null;
}
@Override
protected void onHandleIntent(Intent intent) {
//NotificationManager 是一个系统Service,必须通过 getSystemService()方法来获取。
manager = (NotificationManager) getSystemService(Context.NOTIFICATION_SERVICE);
map = new HashMap<>();
this.apkName = intent.getExtras().getString("apkName");
String url = intent.getExtras().getString("url");
showNotification(notifiId);
Log.d(TAG, "-->同步下载开始");
// 启动后台服务下载apk
Call<ResponseBody> call = Network.getInstance().getApi().downloadFileWithDynamicUrlSync(url);
try {
Response<ResponseBody> response = call.execute();
if (response.isSuccessful()) {
Log.d(TAG, "server contacted and has file");
boolean writtenToDisk = writeResponseBodyToDisk(response.body());
Log.d(TAG, "file download was a success? " + writtenToDisk);
cancel(notifiId);
if (writtenToDisk) {
installApk();
} else {
new Handler(Looper.getMainLooper()).post(new Runnable() {
@Override
public void run() {
Toast.makeText(DownLoadAppService.this, "更新失败", Toast.LENGTH_LONG).show();
}
});
}
} else {
Log.d(TAG, "server contact failed");
cancel(notifiId);
Toast.makeText(DownLoadAppService.this, "更新失败", Toast.LENGTH_LONG).show();
}
} catch (IOException e) {
e.printStackTrace();
}
Log.d(TAG, "-->同步下载结束");
}
/**
* 写入
*
* @param body
* @return
*/
private boolean writeResponseBodyToDisk(ResponseBody body) {
try {
// todo change the file location/name according to your needs
File futureStudioIconFile = new File(getExternalFilesDir(null) + File.separator + apkName);
InputStream inputStream = null;
OutputStream outputStream = null;
try {
byte[] fileReader = new byte[4096];
long fileSize = body.contentLength();
long fileSizeDownloaded = 0;
inputStream = body.byteStream();
outputStream = new FileOutputStream(futureStudioIconFile);
while (true) {
int read = inputStream.read(fileReader);
if (read == -1) {
break;
}
outputStream.write(fileReader, 0, read);
fileSizeDownloaded += read;
int pro = (int) (fileSizeDownloaded * 100 / fileSize);
if (pro > progress) {
progress = pro;
updateProgress(notifiId, pro);
Log.d(TAG, "file download: " + fileSizeDownloaded + " of " + fileSize);
}
}
outputStream.flush();
return true;
} catch (IOException e) {
return false;
} finally {
if (inputStream != null) {
inputStream.close();
}
}
} catch (IOException e) {
return false;
}
}
/**
* 安装APK文件
*/
private void installApk() {
File apkfile = new File(getExternalFilesDir(null) + File.separator, apkName);
if (!apkfile.exists()) {
return;
}
// 通过Intent安装APK文件
Intent intent = new Intent(Intent.ACTION_VIEW);
intent.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
intent.setDataAndType(Uri.parse("file://" + apkfile.toString()), "application/vnd.android.package-archive");
startActivity(intent);
}
/**
* 显示通知
*/
public void showNotification(int notificationId) {
if (!map.containsKey(notificationId)) {
Notification notification = new Notification();
notification.tickerText = "正在开始下载文件...";
notification.when = System.currentTimeMillis();
notification.icon = R.mipmap.ic_launcher;
// 设置通知的特性: 通知被点击后,自动消失
notification.flags = Notification.FLAG_AUTO_CANCEL;
// 设置通知的显示视图
RemoteViews remoteViews = new RemoteViews(getPackageName(), R.layout.notification_contentview);
notification.contentView = remoteViews;
// 发出通知
manager.notify(notificationId, notification);
map.put(notificationId, notification);// 存入Map中
}
}
/**
* 取消通知操作
*
* @param notificationId
*/
public void cancel(int notificationId) {
manager.cancel(notificationId);
map.remove(notificationId);
}
/**
* 显示进度
*
* @param notificationId
* @param progress
*/
public void updateProgress(int notificationId, int progress) {
this.progress = progress;
Notification notify = map.get(notificationId);
if (null != notify) {
没有合适的资源?快使用搜索试试~ 我知道了~
IntentService+retrofit2.0下载文件、更新APP(项目一部分demo)
共122个文件
xml:54个
java:20个
bin:10个
5星 · 超过95%的资源 需积分: 17 127 下载量 139 浏览量
2016-11-16
09:54:58
上传
评论 3
收藏 584KB RAR 举报
温馨提示
demo对应博客地址:http://blog.csdn.net/u013100574/article/details/53129554
资源推荐
资源详情
资源评论
收起资源包目录
IntentService+retrofit2.0下载文件、更新APP(项目一部分demo) (122个子文件)
IService.aidl 410B
ICallback.aidl 176B
gradlew.bat 2KB
fileSnapshots.bin 8.66MB
fileHashes.bin 787KB
taskArtifacts.bin 353KB
fileSnapshotsToTreeSnapshotsIndex.bin 107KB
localClassSetAnalysis.bin 59KB
localClassSetAnalysis.bin 25KB
localClassSetAnalysis.bin 25KB
localJarClasspathSnapshot.bin 21KB
localJarClasspathSnapshot.bin 21KB
localJarClasspathSnapshot.bin 20KB
.gitignore 127B
.gitignore 8B
.gitignore 8B
build.gradle 1KB
build.gradle 892B
build.gradle 521B
settings.gradle 55B
gradlew 5KB
RetrofitDownLoadExample.iml 13KB
ServiceExample.iml 11KB
ServiceDemo.iml 865B
gradle-wrapper.jar 52KB
DownLoadAppService.java 8KB
NetCode.java 6KB
MainActivity.java 5KB
BActivity.java 4KB
ResultAppInfo.java 3KB
MyIntentService2.java 2KB
GsonUtil.java 2KB
MyMessengerService.java 2KB
DeviceUtils.java 1KB
Network.java 1KB
MainActivity.java 1KB
MyService.java 1KB
MyBindService.java 1KB
MyIntentService.java 1007B
MyService1.java 943B
ExampleInstrumentedTest.java 762B
ExampleInstrumentedTest.java 760B
APi.java 699B
ExampleUnitTest.java 410B
ExampleUnitTest.java 409B
localJarClasspathSnapshot.lock 17B
localClassSetAnalysis.lock 17B
localJarClasspathSnapshot.lock 17B
localClassSetAnalysis.lock 17B
localJarClasspathSnapshot.lock 17B
localClassSetAnalysis.lock 17B
cache.properties.lock 17B
ic_launcher.png 10KB
ic_launcher.png 10KB
ic_launcher.png 8KB
ic_launcher.png 8KB
ic_launcher.png 5KB
ic_launcher.png 5KB
ic_launcher.png 3KB
ic_launcher.png 3KB
ic_launcher.png 2KB
ic_launcher.png 2KB
proguard-rules.pro 662B
proguard-rules.pro 662B
gradle.properties 747B
local.properties 504B
gradle-wrapper.properties 233B
cache.properties 37B
workspace.xml 448KB
misc.xml 2KB
AndroidManifest.xml 2KB
support_media_compat_25_0_0.xml 1KB
support_core_utils_25_0_0.xml 1KB
support_fragment_25_0_0.xml 1KB
support_core_ui_25_0_0.xml 1KB
support_compat_25_0_0.xml 1KB
dialog_loading.xml 1KB
appcompat_v7_25_0_0.xml 1KB
runner_0_5.xml 1KB
rules_0_5.xml 1KB
AndroidManifest.xml 948B
notification_contentview.xml 921B
exposed_instrumentation_api_publish_0_5.xml 912B
espresso_idling_resource_2_2_2.xml 885B
animated_vector_drawable_25_0_0.xml 836B
support_vector_drawable_25_0_0.xml 829B
b.xml 825B
espresso_core_2_2_2.xml 808B
gradle.xml 788B
activity_main.xml 787B
activity_main.xml 721B
compiler.xml 686B
modules.xml 580B
converter_scalars_2_1_0.xml 576B
javax_annotation_api_1_2.xml 569B
runConfigurations.xml 564B
hamcrest_integration_1_3.xml 561B
converter_gson_2_1_0.xml 561B
hamcrest_library_1_3.xml 540B
retrofit_2_1_0.xml 531B
共 122 条
- 1
- 2
资源评论
- qijuntan2017-12-07非常不错的demo
小火柴卖的小孩
- 粉丝: 11
- 资源: 4
上传资源 快速赚钱
- 我的内容管理 展开
- 我的资源 快来上传第一个资源
- 我的收益 登录查看自己的收益
- 我的积分 登录查看自己的积分
- 我的C币 登录后查看C币余额
- 我的收藏
- 我的下载
- 下载帮助
安全验证
文档复制为VIP权益,开通VIP直接复制
信息提交成功