Android 如果应用程序正在运行,如何签入前台服务?

Android 如果应用程序正在运行,如何签入前台服务?,android,service,foreground-service,Android,Service,Foreground Service,在我的应用程序中,我有一个前台服务,根据它所属应用程序的存在情况,它的工作方式有所不同 用户可以切换到最近的屏幕,并将应用程序从内存中踢出。由于Application类没有ondestory方法,我不知道它是否正在运行 如果应用程序正在运行,是否有方法签入前台服务 没有合适的方法可以做到这一点。您可以使用的一种解决方法是正常地从活动启动服务,并覆盖onTaskRemoved方法。当您的应用从“最近使用的应用”屏幕中删除时,将调用此方法。您可以在主服务类中设置全局静态变量,并在以后访问它们,以确定

在我的应用程序中,我有一个前台服务,根据它所属应用程序的存在情况,它的工作方式有所不同

用户可以切换到最近的屏幕,并将应用程序从内存中踢出。由于
Application
类没有
ondestory
方法,我不知道它是否正在运行


如果应用程序正在运行,是否有方法签入前台服务

没有合适的方法可以做到这一点。您可以使用的一种解决方法是正常地从活动启动服务,并覆盖
onTaskRemoved
方法。当您的应用从“最近使用的应用”屏幕中删除时,将调用此方法。您可以在主服务类中设置全局静态变量,并在以后访问它们,以确定应用程序是否被终止

这是服务代码:

您的前台服务:

科特林: 爪哇:
class ForegroundService扩展了服务{
公共静态布尔值isappingforeground=true;
}
用于检查应用程序状态的服务:

科特林:
AppKillService.kt

class AppKillService : Service() {
    override fun onBind(p0: Intent?): IBinder? {
        return null
    }

    override fun onStartCommand(intent: Intent?, flags: Int, startId: Int): Int {
        // service is started, app is in foreground, set global variable
        ForegroundService.isAppInForeground = true
        return START_NOT_STICKY
    }

    override fun onTaskRemoved(rootIntent: Intent?) {
        super.onTaskRemoved(rootIntent)
        // app is killed from recent apps screen, do your work here
        // you can set global static variable to use it later on
        // e.g.
        ForegroundService.isAppInForeground = false
    }
}
爪哇:
AppKillService.java

公共类AppKillService扩展服务{
@凌驾
公共IBinder onBind(意向){
返回null;
}
@凌驾
公共int onStartCommand(Intent Intent、int标志、int startId){
//服务启动,应用在前台,设置全局变量
ForegroundService.isAppingForeground=true;
返回开始时间不粘;
}
@凌驾
公共void onTaskRemoved(Intent rootIntent){
super.onTaskRemoved(rootIntent);
//应用程序已从最近的应用程序屏幕中删除,请在此处执行您的工作
//您可以设置全局静态变量,以便以后使用它
//例如。
ForegroundService.isappingforeground=false;
}
}
在您的
main活动中

您是否尝试从活动绑定到服务?@Pawel它的绑定正在检查
onBind
onUnbind
之间的状态不够精确?@Pawel刚刚尝试了您的建议。不幸的是,
onUnbind
在应用程序从最近的屏幕中被踢出时未被调用。@Pawel,当应用程序转到后台时将被调用。那个地方不适合我
class AppKillService : Service() {
    override fun onBind(p0: Intent?): IBinder? {
        return null
    }

    override fun onStartCommand(intent: Intent?, flags: Int, startId: Int): Int {
        // service is started, app is in foreground, set global variable
        ForegroundService.isAppInForeground = true
        return START_NOT_STICKY
    }

    override fun onTaskRemoved(rootIntent: Intent?) {
        super.onTaskRemoved(rootIntent)
        // app is killed from recent apps screen, do your work here
        // you can set global static variable to use it later on
        // e.g.
        ForegroundService.isAppInForeground = false
    }
}
class MainActivity : AppCompatActivity() {

    override fun onCreate(savedInstanceState: Bundle?) {
        super.onCreate(savedInstanceState)
        setContentView(R.layout.activity_main)

        // start your service like this
        startService(Intent(this, AppKillService::class.java))
    }
}