java如何在活动可见时运行函数?(onResume无法正常工作)
一旦Acitvity可见,我想启动一个前台服务。我通过重写onResume
尝试了这一点,但当我编译并运行我的应用程序时,即使屏幕关闭,它也会被调用
如果屏幕关闭,如果我尝试启动前台服务,我会得到IllegalStateException
我将代码包装在一个try-catch块中。它基本上是有效的,但有时在屏幕显示之后,就在屏幕显示之前,它不会被调用
当用户每次看到我的活动时,怎么可能运行代码
你可以在下面搜索框中键入要查询的问题!
一旦Acitvity可见,我想启动一个前台服务。我通过重写onResume
尝试了这一点,但当我编译并运行我的应用程序时,即使屏幕关闭,它也会被调用
如果屏幕关闭,如果我尝试启动前台服务,我会得到IllegalStateException
我将代码包装在一个try-catch块中。它基本上是有效的,但有时在屏幕显示之后,就在屏幕显示之前,它不会被调用
当用户每次看到我的活动时,怎么可能运行代码
# 1 楼答案
对于前台服务,从哪个回调活动开始并不重要,因为即使应用程序在后台工作,它们也可以工作
如果启动前台服务而不调用
startForeground
方法,则可以获得IllegalStateException
。确保您的服务代码包含与以下类似的代码:你可以在这里找到更多关于前台服务的信息:https://developer.android.com/guide/components/foreground-services