How to install an APK from Service

吃可爱长大的小学妹 提交于 2019-12-25 18:47:00

问题


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)

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

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


回答1:


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.

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.

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.



来源:https://stackoverflow.com/questions/42878709/how-to-install-an-apk-from-service

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!