Android开发service download manager

释放双眼,带上耳机,听听看~!
单例模式-->
public class DownManager1 extends Observable implements Observer, IDownLoad {
private static String TAG = DownManager1.class.getSimpleName();
private static DownloadManager downloadManager;
private Context mContext;
private long downloadId;
File file;
private ApkDownLoadEvent.installInfoBean installInfoBean;
private DownListener mListener;
public SimpleBinder mBinder;
//下载任务接收
@Subscribe
public void getDownEvent(ApkDownLoadEvent event) {
switch (event.getStateType()) {
case ApkDownLoadEvent.onApkDownStartCommend:
Log.e(TAG + "DownService", "=======收到下载event=====" + event.getInstallInfoBean().getDownUrl() + "///" + event.getInstallInfoBean().getPosition());
downApk(event.getInstallInfoBean().getDownUrl(), event.getInstallInfoBean().getPosition());
break;
}
}
@Override
public void downLoad(Context context, String url) {
}
private static DownManager1 sInstance;
private static final Object sLock = new Object();
public static DownManager1 getInstance(Context context) {
synchronized (sLock) {
if (null == sInstance) {
sInstance = new DownManager1(context);
}
}
return sInstance;
}
public DownManager1(Context context) {
mContext = context.getApplicationContext();
installInfoBean = new ApkDownLoadEvent.installInfoBean();
InstalledHelper.getInstance(context).addObserver(this);
CommonEventBus.getEventBus().register(this);
}
@Override
public void addObserver(Observer observer) {
super.addObserver(observer);
if (countObservers() > 0) {
}
}
@Override
public void deleteObserver(Observer observer) {
super.deleteObserver(observer);
if (countObservers() == 0) {
InstalledHelper.getInstance(mContext).deleteObserver(this);
CommonEventBus.getEventBus().unregister(this);
}
}
public class SimpleBinder extends Binder {
public DownManager1 getService() {
return DownManager1.this;
}
}
//监听应用安装
@Override
public void update(Observable observable, Object data) {
if (observable instanceof InstalledHelper) {
InstalledData installedData = (InstalledData) data;
if (data instanceof InstalledData) {
if (installedData.isInstalled()) {
installInfoBean.setPackName(((InstalledData) data).getPackageName());
CommonEventBus.getEventBus().post(new ApkDownLoadEvent(ApkDownLoadEvent.onApkInstallFinish, installInfoBean));
PackageManager packageManager = mContext.getPackageManager();
Intent intent1 = new Intent(Intent.ACTION_MAIN);
intent1.addCategory(Intent.CATEGORY_LAUNCHER);
intent1.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
intent1 = packageManager.getLaunchIntentForPackage(installInfoBean.getPackName());
mContext.startActivity(intent1);
installInfoBean.setPackName(installInfoBean.getPackName());
CommonEventBus.getEventBus().post(new ApkDownLoadEvent(ApkDownLoadEvent.onApkOpened, installInfoBean));
if (mListener != null) {
mListener.onApkOpened(installInfoBean.getPackName());
}
//                    EventBus.getDefault().post(new EventDownload(EventDownload.DONE, installInfoBean.getPackName()));
}
}
} else if (observable instanceof DownLoadHelper) {
DownedData downedData = (DownedData) data;
if (data instanceof DownedData) {
if (downedData.isDowned()) {
checkStatus(mContext);
}
}
}
}
@SuppressLint("NewApi")
public void downApk(String url, int listPos) {
DownLoadHelper.getInstance(mContext).addObserver(this);
file = new File(mContext.getExternalFilesDir(Environment.DIRECTORY_DOWNLOADS), System.currentTimeMillis() + ".apk");
Log.e("C52_Down" + TAG, "========file======" + file.getAbsolutePath() + "========downApk======" + url + "====pos====" + listPos);
DownloadManager.Request request = new DownloadManager.Request(Uri.parse(url));
request.setNotificationVisibility(DownloadManager.Request.VISIBILITY_VISIBLE);
request.setTitle("应用下载中");
request.setDescription("应用下载中...");
request.setVisibleInDownloadsUi(true);
request.setDestinationUri(Uri.fromFile(file));
if (downloadManager == null)
downloadManager = (DownloadManager) mContext.getSystemService(Context.DOWNLOAD_SERVICE);
//将下载请求加入下载队列,加入下载队列后会给该任务返回一个long型的id,通过该id可以取消任务,重启任务、获取下载的文件等等
if (downloadManager != null) {
downloadId = downloadManager.enqueue(request);
installInfoBean.setDownLoadId(downloadId);
installInfoBean.setApkPath(file.getAbsolutePath());
installInfoBean.setPosition(listPos);
CommonEventBus.getEventBus().post(new ApkDownLoadEvent(ApkDownLoadEvent.onApkDownStart, installInfoBean));
if (mListener != null) {
mListener.onAapkStartDown(downloadId, listPos, file.getAbsolutePath());
}
}
}
private void checkStatus(Context context) {
try {
DownloadManager.Query query = new DownloadManager.Query();
//通过下载的id查找
query.setFilterById(downloadId);
Cursor cursor = downloadManager.query(query);
if (cursor != null && cursor.moveToFirst()) {
int status = cursor.getInt(cursor.getColumnIndex(DownloadManager.COLUMN_STATUS));
switch (status) {
//下载暂停
case DownloadManager.STATUS_PAUSED:
break;
//下载延迟
case DownloadManager.STATUS_PENDING:
break;
//正在下载
case DownloadManager.STATUS_RUNNING:
Log.e(TAG, "dwonLoadId-->" + downloadId + "  正在下载" + getDownloadPercent(downloadId));
getDownloadPercent(downloadId);
break;
case DownloadManager.STATUS_FAILED:
CommonEventBus.getEventBus().post(new ApkDownLoadEvent(ApkDownLoadEvent.onApkDownError, installInfoBean));
if (mListener != null) {
mListener.onApkDownError();
}
Toast.makeText(mContext, "下载失败", Toast.LENGTH_SHORT).show();
cursor.close();
break;
case DownloadManager.STATUS_SUCCESSFUL:
installInfoBean.setDownLoadId(downloadId);
CommonEventBus.getEventBus().post(new ApkDownLoadEvent(ApkDownLoadEvent.onApkDownFinish, installInfoBean));
if (mListener != null) {
mListener.onAdpkDowned(downloadId);
}
Log.e(TAG, "dwonLoadId-->" + downloadId + "  下载完成" + getDownloadPercent(downloadId));
ApkUtils.installApk(file.getAbsolutePath(), context);
cursor.close();
DownLoadHelper.getInstance(mContext).deleteObserver(this);
break;
default:
break;
}
}
} catch (Exception e) {
e.printStackTrace();
}
}
public static int getDownloadPercent(long downloadId) {
try {
DownloadManager.Query query = new DownloadManager.Query().setFilterById(downloadId);
if (downloadManager != null) {
Cursor c = downloadManager.query(query);
if (c != null && c.moveToFirst()) {
int downloadBytesIdx = c.getColumnIndexOrThrow(
DownloadManager.COLUMN_BYTES_DOWNLOADED_SO_FAR);
int totalBytesIdx = c.getColumnIndexOrThrow(
DownloadManager.COLUMN_TOTAL_SIZE_BYTES);
long totalBytes = c.getLong(totalBytesIdx);
long downloadBytes = c.getLong(downloadBytesIdx);
return (int) (downloadBytes * 100 / totalBytes);
}
}
} catch (Exception e) {
e.printStackTrace();
}
return 0;
}
@Override
public void setOnDownListener(DownListener apkListener) {
this.mListener = apkListener;
}
public static boolean checkAppInstalled(Context context, String pkgName) {
if (pkgName == null || pkgName.isEmpty()) {
return false;
}
final PackageManager packageManager = context.getPackageManager();
List<PackageInfo> info = packageManager.getInstalledPackages(0);
if (info == null || info.isEmpty()) {
return false;
}
for (int i = 0; i < info.size(); i++) {
if (pkgName.equals(info.get(i).packageName)) {
return true;
}
}
return false;
}
}
--->service
try {
Intent intent = new Intent(getContext(), DownManager.class);
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.O) {
getContext().startForegroundService(intent);
}
getContext().startService(intent);
//  getContext().bindService(intent, conn, Service.BIND_AUTO_CREATE);
} catch (Exception e) {
}
public class DownManager extends Service implements Observer, IDownLoad {
private static String TAG = DownManager.class.getSimpleName();
private static DownloadManager downloadManager;
private Context mContext;
private long downloadId;
private int listPos = 0;
File file;
private ApkDownLoadEvent.installInfoBean installInfoBean;
private DownListener mListener;
public SimpleBinder mBinder;
//下载任务接收
@Subscribe
public void getDownEvent(ApkDownLoadEvent event) {
switch (event.getStateType()) {
case ApkDownLoadEvent.onApkDownStartCommend:
Log.e(TAG + "DownService", "=======收到下载event=====" + event.getInstallInfoBean().getDownUrl() + "///" + event.getInstallInfoBean().getPosition());
downApk(event.getInstallInfoBean().getDownUrl(), event.getInstallInfoBean().getPosition());
break;
}
}
@Override
public void downLoad(Context context, String url) {
}
@Override
public void onCreate() {
super.onCreate();
mBinder = new SimpleBinder();
mContext = this;
installInfoBean = new ApkDownLoadEvent.installInfoBean();
InstalledHelper.getInstance(this).addObserver(this);
CommonEventBus.getEventBus().register(this);
Log.e(TAG + "DownService", "=======onCreate======");
//String url = "http://imtt.dd.qq.com/16891/apk/6EAF79D82F2629293A11ACC85B0F537D.apk?fsname=com.tencent.qqlive_7.7.0.20412_20412.apk&csr=9ee4";
//downApk(url);
}
@Override
public IBinder onBind(Intent intent) {
if (mBinder != null) {
return mBinder;
}
return null;
}
public class SimpleBinder extends Binder {
public DownManager getService() {
return DownManager.this;
}
}
public DownManager() {
super();
}
public class DownloadBinder extends Binder {
/**
* 返回当前服务的实例       
*/
public DownManager getService() {
return DownManager.this;
}
}
//监听应用安装
@Override
public void update(Observable observable, Object data) {
if (observable instanceof InstalledHelper) {
InstalledData installedData = (InstalledData) data;
if (data instanceof InstalledData) {
if (installedData.isInstalled()) {
installInfoBean.setPackName(((InstalledData) data).getPackageName());
CommonEventBus.getEventBus().post(new ApkDownLoadEvent(ApkDownLoadEvent.onApkInstallFinish, installInfoBean));
PackageManager packageManager = getPackageManager();
Intent intent1 = new Intent(Intent.ACTION_MAIN);
intent1.addCategory(Intent.CATEGORY_LAUNCHER);
intent1.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
intent1 = packageManager.getLaunchIntentForPackage(installInfoBean.getPackName());
mContext.startActivity(intent1);
installInfoBean.setPackName(installInfoBean.getPackName());
CommonEventBus.getEventBus().post(new ApkDownLoadEvent(ApkDownLoadEvent.onApkOpened, installInfoBean));
if (mListener != null) {
mListener.onApkOpened(installInfoBean.getPackName());
}
//                    EventBus.getDefault().post(new EventDownload(EventDownload.DONE, installInfoBean.getPackName()));
}
}
} else if (observable instanceof DownLoadHelper) {
DownedData downedData = (DownedData) data;
if (data instanceof DownedData) {
if (downedData.isDowned()) {
checkStatus(mContext);
}
}
}
}
@SuppressLint("NewApi")
public void downApk(String url, int listPos) {
DownLoadHelper.getInstance(this).addObserver(this);
file = new File(mContext.getExternalFilesDir(Environment.DIRECTORY_DOWNLOADS), System.currentTimeMillis() + ".apk");
Log.e("C52_Down" + TAG, "========file======" + file.getAbsolutePath() + "========downApk======" + url + "====pos====" + listPos);
DownloadManager.Request request = new DownloadManager.Request(Uri.parse(url));
request.setNotificationVisibility(DownloadManager.Request.VISIBILITY_VISIBLE);
request.setTitle("应用下载中");
request.setDescription("应用下载中...");
request.setVisibleInDownloadsUi(true);
request.setDestinationUri(Uri.fromFile(file));
if (downloadManager == null)
downloadManager = (DownloadManager) mContext.getSystemService(Context.DOWNLOAD_SERVICE);
//将下载请求加入下载队列,加入下载队列后会给该任务返回一个long型的id,通过该id可以取消任务,重启任务、获取下载的文件等等
if (downloadManager != null) {
downloadId = downloadManager.enqueue(request);
installInfoBean.setDownLoadId(downloadId);
installInfoBean.setApkPath(file.getAbsolutePath());
installInfoBean.setPosition(listPos);
CommonEventBus.getEventBus().post(new ApkDownLoadEvent(ApkDownLoadEvent.onApkDownStart, installInfoBean));
if (mListener != null) {
mListener.onAapkStartDown(downloadId, listPos, file.getAbsolutePath());
}
}
}
private void checkStatus(Context context) {
try {
DownloadManager.Query query = new DownloadManager.Query();
//通过下载的id查找
query.setFilterById(downloadId);
Cursor cursor = downloadManager.query(query);
if (cursor != null && cursor.moveToFirst()) {
int status = cursor.getInt(cursor.getColumnIndex(DownloadManager.COLUMN_STATUS));
switch (status) {
//下载暂停
case DownloadManager.STATUS_PAUSED:
break;
//下载延迟
case DownloadManager.STATUS_PENDING:
break;
//正在下载
case DownloadManager.STATUS_RUNNING:
Log.e(TAG, "dwonLoadId-->" + downloadId + "  正在下载" + getDownloadPercent(downloadId));
getDownloadPercent(downloadId);
break;
case DownloadManager.STATUS_FAILED:
CommonEventBus.getEventBus().post(new ApkDownLoadEvent(ApkDownLoadEvent.onApkDownError, installInfoBean));
if (mListener != null) {
mListener.onApkDownError();
}
Toast.makeText(mContext, "下载失败", Toast.LENGTH_SHORT).show();
cursor.close();
break;
case DownloadManager.STATUS_SUCCESSFUL:
installInfoBean.setDownLoadId(downloadId);
CommonEventBus.getEventBus().post(new ApkDownLoadEvent(ApkDownLoadEvent.onApkDownFinish, installInfoBean));
if (mListener != null) {
mListener.onAdpkDowned(downloadId);
}
Log.e(TAG, "dwonLoadId-->" + downloadId + "  下载完成" + getDownloadPercent(downloadId));
ApkUtils.installApk(file.getAbsolutePath(), context);
cursor.close();
DownLoadHelper.getInstance(this).deleteObserver(this);
break;
default:
break;
}
}
}catch (Exception e){
e.printStackTrace();
}
}
public static int getDownloadPercent(long downloadId) {
try {
DownloadManager.Query query = new DownloadManager.Query().setFilterById(downloadId);
if (downloadManager != null) {
Cursor c = downloadManager.query(query);
if (c != null && c.moveToFirst()) {
int downloadBytesIdx = c.getColumnIndexOrThrow(
DownloadManager.COLUMN_BYTES_DOWNLOADED_SO_FAR);
int totalBytesIdx = c.getColumnIndexOrThrow(
DownloadManager.COLUMN_TOTAL_SIZE_BYTES);
long totalBytes = c.getLong(totalBytesIdx);
long downloadBytes = c.getLong(downloadBytesIdx);
return (int) (downloadBytes * 100 / totalBytes);
}
}
} catch (Exception e) {
e.printStackTrace();
}
return 0;
}
@Override
public void setOnDownListener(DownListener apkListener) {
this.mListener = apkListener;
}
public static boolean checkAppInstalled(Context context, String pkgName) {
if (pkgName == null || pkgName.isEmpty()) {
return false;
}
final PackageManager packageManager = context.getPackageManager();
List<PackageInfo> info = packageManager.getInstalledPackages(0);
if (info == null || info.isEmpty()) {
return false;
}
for (int i = 0; i < info.size(); i++) {
if (pkgName.equals(info.get(i).packageName)) {
return true;
}
}
return false;
}
@Override
public void onDestroy() {
super.onDestroy();
InstalledHelper.getInstance(this).deleteObserver(this);
CommonEventBus.getEventBus().unregister(this);
}
}

人已赞赏
Android文章

Android开发BroadCastReceiver

2020-3-24 11:18:26

Android文章

Android Studio 更改程序包名

2020-3-24 11:49:33

个人中心
购物车
优惠劵
今日签到
有新私信 私信列表
有新消息 消息中心
搜索