如何从服务安装APK [英] How to install an APK from Service

查看:93
本文介绍了如何从服务安装APK的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个BroadcastReceiver,我从服务器上下载了一个apk,当我抓到动作DownloadManager.ACTION_DOWNLOAD_COMPLETE时,我使用

I have a BroadcastReceiver, I download an apk from the server, when I catch action DownloadManager.ACTION_DOWNLOAD_COMPLETE I install the apk using

activity.startActivityForResult(my_intent, REQUEST_CODE)

现在,我想将此逻辑移动到Service中,并同时安装apk,但是在服务中我没有Activity,可以将上下文转换为从getapplicationcontext()获得的Activity,但我可以捕获无法将上下文强制转换为com.android.Activity

Now I want to move this logic in a Service and also install the apk, but inside the service I don't have a Activity, I can to cast context to Activity obtained from getapplicationcontext(), but I catch the error that context can't be casted to com.android.Activity

如何从此服务运行apk安装?

How I can to run installation of apk from this Service?

推荐答案

对用户不利的方法是调用startActivity()而不是startActivityForResult().由于它会自动启动安装程序用户界面,因此它对用户不利,并且您的服务不知道用户在前台正在做什么.打扰用户不会使用户非常满意.

The user-hostile approach is to call startActivity() instead of startActivityForResult(). This is user-hostile as it automatically starts up an installer UI, and your service has no idea what the user is doing in the foreground. Interrupting the user will not make the user very happy.

一种与用户敌对的相关方法是从服务开始您自己的活动,然后您自己的活动将调用startActivityForResult().您可以使用Theme.Translucent.NoTitleBar,因此您自己的活动没有UI,但是,再次,您将启动安装程序活动,这将中断用户.

A related user-hostile approach is to start your own activity from the service, where your own activity then calls startActivityForResult(). You could use Theme.Translucent.NoTitleBar so your own activity has no UI, but, again, you will be starting the installer activity, which will interrupt the user.

用户友好的方法是在下载完成后提出Notification.要么将ACTION_INSTALL_PACKAGE Intent放入Notification本身,要么让通知开始您的活动,而活动又称为startActivityForResult().这样,用户可以在 user 想要的时候安装应用程序,而现在可能不是.

The user-friendly approach is to raise a Notification when the download is complete. Either put the ACTION_INSTALL_PACKAGE Intent in the Notification itself, or have the notification start your activity, which in turn calls startActivityForResult(). This allows the user to install the app when the user wants to, which may or may not be right now.

这篇关于如何从服务安装APK的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆