IntentService+Notifcation实现应用app后台下载完成后并安装(已适配8.0)

本文主要是介绍IntentService+Notifcation实现应用app后台下载完成后并安装(已适配8.0),希望对大家解决编程问题提供一定的参考价值,需要的开发者们随着小编来一起学习吧!

转载自IntentService+Notifcation实现应用app后台下载完成后并安装(已适配8.0)

现在已兼容8.0的通知栏显示,确保你的targetSdkVersion 是26或以上

以下为8.0的显示图片:

这里写图片描述

这里写图片描述

app的更新模块放在后台服务可以大大提高app的体验,采用IntentService这种google为我们封装好的用于执行服务中有网络操作的类并搭配Notification来实现一下(下载工具用的是自带的URLConnection,因为Retrofit+rxjava并没有提供进度的回调,网上也有很多改进的方案,可以自定义让retrofit+rxjava实现进度的回调,在此,没有采用)

效果图如下:(看了一下淘宝的更新,所以就成这样的界面了,)
这里写图片描述
代码:自定义的IntentService类

/*** 更新包下载安装服务*/
public class UpdateService extends IntentService {private static final int NOTIFY_DOWNLOAD= 0;private static final int NOTIFY_FINISH = 1;private static final String PENDING_INSTALL_ACTION = "gaoxin.com.inforindustry.click.toinstall";private Context mContext;private String apkUrl;public UpdateService() {super("UpdateService");}private NotificationUtils notificationUtils;private File  downapkfile;private Handler mHandler = new Handler(new Handler.Callback() {@Overridepublic boolean handleMessage(Message msg) {switch (msg.what){case 0://正在下载中RemoteViews contentView = notificationUtils.getNotification().contentView;contentView.setTextViewText(R.id.notify_tv, "更新包下载中...");contentView.setProgressBar(R.id.notify_progress_pb, 100, msg.arg1, false);contentView.setTextViewText(R.id.notify_progress_tv,msg.arg1+"%");// 更新UInotificationUtils.getManager().notify(NOTIFY_DOWNLOAD,notificationUtils.getNotification());break;case 1:notificationUtils.cancelNotification(NOTIFY_DOWNLOAD);createNotification(NOTIFY_FINISH);break;}return true;}});@Overrideprotected void onHandleIntent(Intent intent) {if (intent != null) {apkUrl = intent.getStringExtra("apkurl");handleActionFoo(apkUrl);}}private void handleActionFoo(String param1) {if(NetworkUtils.isConnected()){createNotification(NOTIFY_DOWNLOAD);try {DownApk(param1);} catch (Exception e) {e.printStackTrace();}}}//发送消息进行更新进度条public void sendMessage(int what,int mprogress) {Message msg0 = mHandler.obtainMessage();msg0.what = what;msg0.arg1 = mprogress;mHandler.sendMessage(msg0);}private void DownApk(String param1) {int oldProcess = 0;if (SDCardUtils.isSDCardEnable()){downapkfile = new File(Environment.getExternalStorageDirectory().getAbsolutePath()+"/industry.apk");try {URL url = new URL(param1.trim());HttpURLConnection connection  = (HttpURLConnection) url.openConnection();if (connection.getResponseCode() == 200){InputStream inputStream = connection.getInputStream();FileOutputStream fos = new FileOutputStream(downapkfile);//总长度int totalLength = connection.getContentLength();//已下载的长度int currentLength  = 0;byte[] bytes = new byte[512];connection.connect();int flag = 0;while (flag < 100){if (inputStream != null){int read = inputStream.read(bytes);if (read <= 0){sendMessage(1,0);break;}else {fos.write(bytes,0,read);currentLength += read;int mprogress = (int) ((currentLength*100)/totalLength);if(oldProcess <= mprogress-5 ){// 避免notifymanager ANR,每下载百分之5才进行通知一次oldProcess =mprogress;sendMessage(0, mprogress);}}}}fos.close();inputStream.close();}connection.disconnect();} catch (MalformedURLException e) {e.printStackTrace();} catch (IOException e) {e.printStackTrace();}}}private void createNotification(int notifyId) {switch (notifyId){case NOTIFY_DOWNLOAD:RemoteViews remoteViews = new RemoteViews(AppUtils.getAppPackageName(),R.layout.notify_custom_view_layout);remoteViews.setTextViewText(R.id.notify_tv,"正在下载...");remoteViews.setProgressBar(R.id.notify_progress_pb,100,0,false);remoteViews.setTextViewText(R.id.notify_progress_tv,"0%");notificationUtils.sendNotification(notifyId,"","",remoteViews,null);break;case NOTIFY_FINISH:Intent intent = new Intent(getApplicationContext(),NotificationBroadCast.class);intent.setAction(PENDING_INSTALL_ACTION);intent.putExtra("notifyId",NOTIFY_FINISH);PendingIntent pendingIntent = PendingIntent.getBroadcast(mContext,0,intent,PendingIntent.FLAG_ONE_SHOT);notificationUtils.sendNotification(notifyId,"点击安装","更新包已下载完成",null,pendingIntent);break;default:break;}}@Overridepublic void onCreate() {super.onCreate();mContext = this;//初始化通知窗口管理notificationUtils = new NotificationUtils(getApplicationContext());}
}
  • 1
  • 2
  • 3
  • 4
  • 5
  • 6
  • 7
  • 8
  • 9
  • 10
  • 11
  • 12
  • 13
  • 14
  • 15
  • 16
  • 17
  • 18
  • 19
  • 20
  • 21
  • 22
  • 23
  • 24
  • 25
  • 26
  • 27
  • 28
  • 29
  • 30
  • 31
  • 32
  • 33
  • 34
  • 35
  • 36
  • 37
  • 38
  • 39
  • 40
  • 41
  • 42
  • 43
  • 44
  • 45
  • 46
  • 47
  • 48
  • 49
  • 50
  • 51
  • 52
  • 53
  • 54
  • 55
  • 56
  • 57
  • 58
  • 59
  • 60
  • 61
  • 62
  • 63
  • 64
  • 65
  • 66
  • 67
  • 68
  • 69
  • 70
  • 71
  • 72
  • 73
  • 74
  • 75
  • 76
  • 77
  • 78
  • 79
  • 80
  • 81
  • 82
  • 83
  • 84
  • 85
  • 86
  • 87
  • 88
  • 89
  • 90
  • 91
  • 92
  • 93
  • 94
  • 95
  • 96
  • 97
  • 98
  • 99
  • 100
  • 101
  • 102
  • 103
  • 104
  • 105
  • 106
  • 107
  • 108
  • 109
  • 110
  • 111
  • 112
  • 113
  • 114
  • 115
  • 116
  • 117
  • 118
  • 119
  • 120
  • 121
  • 122
  • 123
  • 124
  • 125
  • 126
  • 127
  • 128
  • 129
  • 130
  • 131
  • 132
  • 133
  • 134
  • 135
  • 136
  • 137
  • 138
  • 139
  • 140
  • 141
  • 142
  • 143
  • 144

NotificationUtils,用来进行适配8.0系统

public class NotificationUtils extends ContextWrapper {private NotificationManager mManager;public static final String ANDROID_CHANNEL_ID = "com.gaoxin.industry.ANDROID";public static final String ANDROID_CHANNEL_NAME = "ANDROID CHANNEL";private Notification notification;public NotificationUtils(Context base) {super(base);if (Build.VERSION.SDK_INT >= 26){createChannels();}}@RequiresApi(api = Build.VERSION_CODES.O)public void createChannels() {// create android channelNotificationChannel androidChannel = new NotificationChannel(ANDROID_CHANNEL_ID,ANDROID_CHANNEL_NAME, NotificationManager.IMPORTANCE_DEFAULT);// Sets whether notifications posted to this channel should display notification lightsandroidChannel.enableLights(true);// Sets whether notification posted to this channel should vibrate.androidChannel.enableVibration(true);// Sets the notification light color for notifications posted to this channelandroidChannel.setLightColor(Color.GREEN);// Sets whether notifications posted to this channel appear on the lockscreen or notandroidChannel.setLockscreenVisibility(Notification.VISIBILITY_PRIVATE);getManager().createNotificationChannel(androidChannel);}public NotificationManager getManager() {if (mManager == null) {mManager = (NotificationManager) getSystemService(Context.NOTIFICATION_SERVICE);}return mManager;}@RequiresApi(api = Build.VERSION_CODES.O)public Notification.Builder getAndroidChannelNotification(String title,String content) {return new Notification.Builder(getApplicationContext(), ANDROID_CHANNEL_ID).setContentTitle(title).setContentText(content).setSmallIcon(android.R.drawable.stat_notify_more);}public NotificationCompat.Builder getNotification_25(String title, String content){return new NotificationCompat.Builder(getApplicationContext()).setContentTitle(title).setContentText(content).setSmallIcon(android.R.drawable.stat_notify_more);}public void sendNotification(int id,String title, String content, RemoteViews remoteViews, PendingIntent intent){if (Build.VERSION.SDK_INT>=26){notification = getAndroidChannelNotification(title, content).setCustomContentView(remoteViews).setContentIntent(intent).build();getManager().notify(id,notification);}else{notification = getNotification_25(title, content).setCustomContentView(remoteViews).setContentIntent(intent).build();getManager().notify(id,notification);}}public void cancelNotification(int id){getManager().cancel(id);}public Notification getNotification(){if (notification != null){return notification;}return null;}
}
  • 1
  • 2
  • 3
  • 4
  • 5
  • 6
  • 7
  • 8
  • 9
  • 10
  • 11
  • 12
  • 13
  • 14
  • 15
  • 16
  • 17
  • 18
  • 19
  • 20
  • 21
  • 22
  • 23
  • 24
  • 25
  • 26
  • 27
  • 28
  • 29
  • 30
  • 31
  • 32
  • 33
  • 34
  • 35
  • 36
  • 37
  • 38
  • 39
  • 40
  • 41
  • 42
  • 43
  • 44
  • 45
  • 46
  • 47
  • 48
  • 49
  • 50
  • 51
  • 52
  • 53
  • 54
  • 55
  • 56
  • 57
  • 58
  • 59
  • 60
  • 61
  • 62
  • 63
  • 64
  • 65
  • 66
  • 67
  • 68
  • 69
  • 70
  • 71
  • 72
  • 73
  • 74
  • 75

需要注意的点: Notification必须设置smallIcon这个属性,否则会报错,
如果是下载完成后不希望自动安装,而是点击后进行安装,可以使用PendingIntent这个类来进行触发,否则点击后是没有什么效果的,必须传递意图Intent

Android 8.0在安装应用的时候需要权限

8.0系统设置中不再提供是否允许安装未知来源的应用这个选项,所以在进行安装的时候,一定注意这个权限,否则会报错
其他注意事项:清单文件中必须包含provider

<provider
            android:name="android.support.v4.content.FileProvider"android:authorities="包名.fileprovider"android:exported="false"android:grantUriPermissions="true"><meta-data
                android:name="android.support.FILE_PROVIDER_PATHS"android:resource="@xml/file_paths" /></provider>
  • 1
  • 2
  • 3
  • 4
  • 5
  • 6
  • 7
  • 8
  • 9

res文件夹下建立xml文件夹
在xml中新建file_paths.xml文件,如下:

<?xml version="1.0" encoding="utf-8"?>
<paths><external-path
        name="external_storage_root"path="." />
</paths>
  • 1
  • 2
  • 3
  • 4
  • 5
  • 6

安装

 public static void installApp(final File file, final String authority) {if (!isFileExists(file)) return;Utils.getApp().startActivity(IntentUtils.getInstallAppIntent(file, authority, true));}
public static Intent getInstallAppIntent(final File file,final String authority,final boolean isNewTask) {if (file == null) return null;Intent intent = new Intent(Intent.ACTION_VIEW);Uri data;String type = "application/vnd.android.package-archive";if (Build.VERSION.SDK_INT < Build.VERSION_CODES.N) {data = Uri.fromFile(file);} else {intent.setFlags(Intent.FLAG_GRANT_READ_URI_PERMISSION);data = FileProvider.getUriForFile(Utils.getApp(), authority, file);}intent.setDataAndType(data, type);return getIntent(intent, isNewTask);}
  • 1
  • 2
  • 3
  • 4
  • 5
  • 6
  • 7
  • 8
  • 9
  • 10
  • 11
  • 12
  • 13
  • 14
  • 15
  • 16
  • 17
  • 18
  • 19
  • 20

布局也贴一下,根据自己的需求

<?xml version="1.0" encoding="utf-8"?>
<RelativeLayout
    xmlns:android="http://schemas.android.com/apk/res/android"android:layout_width="match_parent"android:layout_height="wrap_content"android:background="@color/white_alpha_6"><ImageView
        android:layout_width="wrap_content"android:layout_height="wrap_content"android:id="@+id/notify_download_iv"android:src="@mipmap/ic_launcher_round"android:layout_marginTop="12dp"android:layout_centerVertical="true"android:layout_marginRight="8dp"/><TextView
        android:layout_width="wrap_content"android:layout_height="wrap_content"android:id="@+id/notify_tv"android:textColor="@color/black"android:layout_marginTop="8dp"android:layout_toRightOf="@+id/notify_download_iv"android:text="正在下载..."/><ProgressBar
        android:layout_width="match_parent"android:layout_height="wrap_content"android:id="@+id/notify_progress_pb"style="?android:attr/progressBarStyleHorizontal"android:layout_below="@+id/notify_tv"android:layout_toRightOf="@+id/notify_download_iv"/><TextView
            android:layout_width="wrap_content"android:layout_height="wrap_content"android:textSize="12sp"android:textColor="@color/black"android:id="@+id/notify_progress_instruction_tv"android:layout_below="@+id/notify_progress_pb"android:text="客户端已经下载了"android:layout_toRightOf="@+id/notify_download_iv"/><TextView
            android:layout_width="wrap_content"android:layout_height="wrap_content"android:textSize="12sp"android:id="@+id/notify_progress_tv"android:textColor="@color/black"android:layout_toRightOf="@+id/notify_progress_instruction_tv"android:layout_below="@+id/notify_progress_pb"android:text="50%"/></RelativeLayout>
  • 1
  • 2
  • 3
  • 4
  • 5
  • 6
  • 7
  • 8
  • 9
  • 10
  • 11
  • 12
  • 13
  • 14
  • 15
  • 16
  • 17
  • 18
  • 19
  • 20
  • 21
  • 22
  • 23
  • 24
  • 25
  • 26
  • 27
  • 28
  • 29
  • 30
  • 31
  • 32
  • 33
  • 34
  • 35
  • 36
  • 37
  • 38
  • 39
  • 40
  • 41
  • 42
  • 43
  • 44
  • 45
  • 46
  • 47
  • 48
  • 49
  • 50
  • 51

启动服务:

 /*** 传入url*/Intent intent = new Intent(MainActivity.this,UpdateService.class);intent.putExtra("apkurl", updataVersionUrl);startService(intent);
  • 1
  • 2
  • 3
  • 4
  • 5
  • 6

下载完成后,点击事件的处理,采用了BroadCastReceiver方式

public class NotificationBroadCast extends BroadcastReceiver {private File downFile = new File(Environment.getExternalStorageDirectory().getAbsolutePath() + "/industry.apk");private static final String INSTALL_ACTION = "包名.click.toinstall";@Overridepublic void onReceive(Context context, Intent intent) {String action = intent.getAction();if (action.equals(INSTALL_ACTION)){int notifyId = intent.getIntExtra("notifyId", 0);NotificationManager manager = (NotificationManager) context.getSystemService(NOTIFICATION_SERVICE);manager.cancel(notifyId);if (FileUtils.isFileExists(downFile) && downFile.length() > 0) {AppUtils.installApp(downFile, "gaoxin.com.inforindustry.fileprovider");}}}
}
  • 1
  • 2
  • 3
  • 4
  • 5
  • 6
  • 7
  • 8
  • 9
  • 10
  • 11
  • 12
  • 13
  • 14
  • 15
  • 16
  • 17
  • 18
  • 19

最后不要忘记在清单文件中注册一下,

这篇关于IntentService+Notifcation实现应用app后台下载完成后并安装(已适配8.0)的文章就介绍到这儿,希望我们推荐的文章对编程师们有所帮助!



http://www.chinasem.cn/article/516342

相关文章

C++中零拷贝的多种实现方式

《C++中零拷贝的多种实现方式》本文主要介绍了C++中零拷贝的实现示例,旨在在减少数据在内存中的不必要复制,从而提高程序性能、降低内存使用并减少CPU消耗,零拷贝技术通过多种方式实现,下面就来了解一下... 目录一、C++中零拷贝技术的核心概念二、std::string_view 简介三、std::stri

C++高效内存池实现减少动态分配开销的解决方案

《C++高效内存池实现减少动态分配开销的解决方案》C++动态内存分配存在系统调用开销、碎片化和锁竞争等性能问题,内存池通过预分配、分块管理和缓存复用解决这些问题,下面就来了解一下... 目录一、C++内存分配的性能挑战二、内存池技术的核心原理三、主流内存池实现:TCMalloc与Jemalloc1. TCM

OpenCV实现实时颜色检测的示例

《OpenCV实现实时颜色检测的示例》本文主要介绍了OpenCV实现实时颜色检测的示例,通过HSV色彩空间转换和色调范围判断实现红黄绿蓝颜色检测,包含视频捕捉、区域标记、颜色分析等功能,具有一定的参考... 目录一、引言二、系统概述三、代码解析1. 导入库2. 颜色识别函数3. 主程序循环四、HSV色彩空间

Python UV安装、升级、卸载详细步骤记录

《PythonUV安装、升级、卸载详细步骤记录》:本文主要介绍PythonUV安装、升级、卸载的详细步骤,uv是Astral推出的下一代Python包与项目管理器,主打单一可执行文件、极致性能... 目录安装检查升级设置自动补全卸载UV 命令总结 官方文档详见:https://docs.astral.sh/

Python pip下载包及所有依赖到指定文件夹的步骤说明

《Pythonpip下载包及所有依赖到指定文件夹的步骤说明》为了方便开发和部署,我们常常需要将Python项目所依赖的第三方包导出到本地文件夹中,:本文主要介绍Pythonpip下载包及所有依... 目录步骤说明命令格式示例参数说明离线安装方法注意事项总结要使用pip下载包及其所有依赖到指定文件夹,请按照以

Python实现精准提取 PDF中的文本,表格与图片

《Python实现精准提取PDF中的文本,表格与图片》在实际的系统开发中,处理PDF文件不仅限于读取整页文本,还有提取文档中的表格数据,图片或特定区域的内容,下面我们来看看如何使用Python实... 目录安装 python 库提取 PDF 文本内容:获取整页文本与指定区域内容获取页面上的所有文本内容获取

基于Python实现一个Windows Tree命令工具

《基于Python实现一个WindowsTree命令工具》今天想要在Windows平台的CMD命令终端窗口中使用像Linux下的tree命令,打印一下目录结构层级树,然而还真有tree命令,但是发现... 目录引言实现代码使用说明可用选项示例用法功能特点添加到环境变量方法一:创建批处理文件并添加到PATH1

Java使用HttpClient实现图片下载与本地保存功能

《Java使用HttpClient实现图片下载与本地保存功能》在当今数字化时代,网络资源的获取与处理已成为软件开发中的常见需求,其中,图片作为网络上最常见的资源之一,其下载与保存功能在许多应用场景中都... 目录引言一、Apache HttpClient简介二、技术栈与环境准备三、实现图片下载与保存功能1.

canal实现mysql数据同步的详细过程

《canal实现mysql数据同步的详细过程》:本文主要介绍canal实现mysql数据同步的详细过程,本文通过实例图文相结合给大家介绍的非常详细,对大家的学习或工作具有一定的参考借鉴价值,需要的... 目录1、canal下载2、mysql同步用户创建和授权3、canal admin安装和启动4、canal

Nexus安装和启动的实现教程

《Nexus安装和启动的实现教程》:本文主要介绍Nexus安装和启动的实现教程,具有很好的参考价值,希望对大家有所帮助,如有错误或未考虑完全的地方,望不吝赐教... 目录一、Nexus下载二、Nexus安装和启动三、关闭Nexus总结一、Nexus下载官方下载链接:DownloadWindows系统根