import android.app.ActivityManager;
import android.app.DownloadManager;
import android.content.BroadcastReceiver;
import android.content.Context;
import android.content.Intent;
import android.content.IntentFilter;
import android.database.Cursor;
import android.net.Uri;
import android.os.Environment;
import android.support.v4.content.FileProvider;
import android.widget.Toast;
import com.example.simpledemo.R;
import com.example.simpledemo.base.BaseActivity;
import com.example.simpledemo.util.Utils;
import java.io.File;
import java.io.IOException;
import java.util.List;
import static android.content.Context.ACTIVITY_SERVICE;
public class DownloadUtils {
/**
* 下载器
*/
private DownloadManager downloadManager;
private Context mContext;
/**
* 下载的ID
*/
private long downloadId;
/**
* apk保存路径
*/
private String pathStr;
public DownloadUtils(Context context, String url, String name) {
this.mContext = context;
downloadApk(url, name);
}
//下载apk
private void downloadApk(String url, String name) {
//设置下载的路径
File file = new File(mContext.getExternalFilesDir(Environment.DIRECTORY_DOWNLOADS), name);
pathStr = file.getAbsolutePath();
if (file.exists()) {
installApk();
} else {
Toast.makeText(mContext, "开始下载,请在通知栏中查看进度。。。", Toast.LENGTH_SHORT).show();
//创建下载任务
DownloadManager.Request request = new DownloadManager.Request(Uri.parse(url));
//设置允许使用的网络类型,这里是移动网络和wifi都可以
request.setAllowedNetworkTypes(DownloadManager.Request.NETWORK_MOBILE | DownloadManager.Request.NETWORK_WIFI);
//在通知栏中显示,默认就是显示的(下载完也显示)
request.setNotificationVisibility(DownloadManager.Request.VISIBILITY_VISIBLE_NOTIFY_COMPLETED);
//设置下载标题
request.setTitle(mContext.getString(R.string.app_name));
request.setDescription("我是描述");
//显示在下载界面,即下载后的文件在系统下载管理里显示
request.setVisibleInDownloadsUi(true);
request.setDestinationUri(Uri.fromFile(file));
//获取DownloadManager
if (downloadManager == null) {
downloadManager = (DownloadManager) mContext.getSystemService(Context.DOWNLOAD_SERVICE);
}
//将下载请求加入下载队列,加入下载队列后会给该任务返回一个long型的id,通过该id可以取消任务,重启任务、获取下载的文件等等
if (downloadManager != null) {
downloadId = downloadManager.enqueue(request);
}
//注册广播接收者,监听下载状态
mContext.registerReceiver(receiver, new IntentFilter(DownloadManager.ACTION_DOWNLOAD_COMPLETE));
}
}
/**
* 广播监听下载的各个状态
*/
private BroadcastReceiver receiver = new BroadcastReceiver() {
@Override
public void onReceive(Context context, Intent intent) {
checkStatus();
}
};
/**
* 检查下载状态
*/
private void checkStatus() {
DownloadManager.Query query = new DownloadManager.Query();
//通过下载的id查找
query.setFilterById(downloadId);
Cursor cursor = downloadManager.query(query);
if (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:
//正在下载
break;
case DownloadManager.STATUS_SUCCESSFUL:
//下载完成安装APK
if (Utils.isAppBackground(mContext)) {
Toast.makeText(mContext, mContext.getString(R.string.app_name) + "下载完成,请到通知栏点击安装", Toast.LENGTH_SHORT).show();
setTopApp();
}
installApk();
cursor.close();
break;
case DownloadManager.STATUS_FAILED:
//下载失败
Toast.makeText(mContext, "下载失败", Toast.LENGTH_SHORT).show();
cursor.close();
mContext.unregisterReceiver(receiver);
break;
default:
break;
}
}
}
/**
* 安装apk
*/
private void installApk() {
setPermission(pathStr);
Intent intent = new Intent();
intent.setAction(Intent.ACTION_VIEW);
// 由于没有在Activity环境下启动Activity,设置下面的标签
intent.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
//Android 7.0以上要使用FileProvider
File file = new File(pathStr);
//参数1 上下文, 参数2 Provider主机地址 和配置文件中保持一致 参数3 共享的文件
Uri apkUri = FileProvider.getUriForFile(mContext, mContext.getPackageName() + ".fileprovider", file);
//添加这一句表示对目标应用临时授权该Uri所代表的文件
intent.addFlags(Intent.FLAG_GRANT_READ_URI_PERMISSION);
intent.setDataAndType(apkUri, "application/vnd.android.package-archive");
mContext.startActivity(intent);
((BaseActivity) mContext).finish();
}
/**
* 修改文件权限
*/
private void setPermission(String absolutePath) {
String command = "chmod 777 " + absolutePath;
Runtime runtime = Runtime.getRuntime();
try {
runtime.exec(command);
} catch (IOException e) {
e.printStackTrace();
}
}
/**
* 当本应用位于后台时,则将它切换到最前端
*/
public void setTopApp() {
//获取ActivityManager
ActivityManager activityManager = (ActivityManager) mContext.getSystemService(ACTIVITY_SERVICE);
//获得当前运行的task(任务)
List<ActivityManager.RunningTaskInfo> taskInfoList = activityManager.getRunningTasks(100);
for (ActivityManager.RunningTaskInfo taskInfo : taskInfoList) {
//找到本应用的 task,并将它切换到前台
if (taskInfo.topActivity.getPackageName().equals(mContext.getPackageName())) {
activityManager.moveTaskToFront(taskInfo.id, 0);
break;
}
}
}
}
Utils:
/**
* App 是否处于后台
*
* @param context
* @return
*/
public static boolean isAppBackground(Context context) {
ActivityManager activityManager = (ActivityManager) context.getSystemService(Context.ACTIVITY_SERVICE);
List<ActivityManager.RunningAppProcessInfo> appProcesses = activityManager.getRunningAppProcesses();
for (ActivityManager.RunningAppProcessInfo appProcess : appProcesses) {
if (appProcess.processName.equals(context.getPackageName())) {
if (appProcess.importance != ActivityManager.RunningAppProcessInfo.IMPORTANCE_FOREGROUND) {
return true;
} else {
return false;
}
}
}
return false;
}
// 检测是否有写的权限
public static void verifyStoragePermissions(Activity activity) {
try {
//检测是否有写的权限
int permission = ActivityCompat.checkSelfPermission(activity,
"android.permission.WRITE_EXTERNAL_STORAGE");
if (permission != PackageManager.PERMISSION_GRANTED) {
// 没有写的权限,去申请写的权限,会弹出对话框
ActivityCompat.requestPermissions(activity, PERMISSIONS_STORAGE, REQUEST_EXTERNAL_STORAGE);
}
} catch (Exception e) {
e.printStackTrace();
}
}
使用:
//通知栏下载apk
String url = "http://dldir1.qq.com/dlomg/weishi/weishi_guanwang.apk";
String fileName = "weishi_guanwang.apk";
new DownloadUtils(MainActivity.this, url, fileName);