有 Java 编程相关的问题?

你可以在下面搜索框中键入要查询的问题!

java如何在活动可见时运行函数?(onResume无法正常工作)

一旦Acitvity可见,我想启动一个前台服务。我通过重写onResume尝试了这一点,但当我编译并运行我的应用程序时,即使屏幕关闭,它也会被调用

如果屏幕关闭,如果我尝试启动前台服务,我会得到IllegalStateException

我将代码包装在一个try-catch块中。它基本上是有效的,但有时在屏幕显示之后,就在屏幕显示之前,它不会被调用

当用户每次看到我的活动时,怎么可能运行代码


共 (1) 个答案

  1. # 1 楼答案

    对于前台服务,从哪个回调活动开始并不重要,因为即使应用程序在后台工作,它们也可以工作

    如果启动前台服务而不调用startForeground方法,则可以获得IllegalStateException。确保您的服务代码包含与以下类似的代码:

    class ExampleService : Service() {
    
       override fun onStartCommand(intent: Intent?, flags: Int, startId: Int): Int {
            // prepare pending intent
            val pendingIntent = val pendingIntent: PendingIntent =
            Intent(this, ExampleActivity::class.java).let { notificationIntent ->
                PendingIntent.getActivity(this, 0, notificationIntent, 0)
            }
    
            // build notification to display while foreground service is running
            val notification = 
                NotificationCompat.Builder(context, "channel_id")
                   .setContentTitle("Title")
                   .setContentText("Text")
                   .setContentIntent(pendingIntent)
                   .setSmallIcon(R.drawable.small_icon)
                   .build()
    
            val notificationId = 42
    
            // call tell the system run your service as foreground service
            startForeground(notificationId, notification)
         
            // implement the business logic  
            ....
        }
       
    }
    

    你可以在这里找到更多关于前台服务的信息:https://developer.android.com/guide/components/foreground-services