如果应用程序是运行,如何检查前台服务?

How to check in foreground service if the app is running?

在我的应用程序中,我有前台服务,它的工作方式不同,具体取决于它所属的应用程序的存在。

用户可以切换到“最近”屏幕并将应用程序踢出内存。由于Applicationclass没有onDestroy方法,不知道是不是运行。

如果应用程序是 运行,有没有办法检查前台服务?

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

这是服务代码:

您的前台服务:

科特林:

class ForegroundService : Service() {

    companion object {
        // this can be used to check if the app is running or not
        @JvmField  var isAppInForeground: Boolean = true
    }

    ...

}

Java:

class ForegroundService extends Service {

    public static boolean isAppInForeground = 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
    }
}

Java:

AppKillService.java

public class AppKillService extends Service {
    @Override
    public IBinder onBind(Intent intent) {
        return null;
    }

    @Override
    public int onStartCommand(Intent intent, int flags, int startId) {
        // service is started, app is in foreground, set global variable
        ForegroundService.isAppInForeground = true;
        return START_NOT_STICKY;
    }

    @Override
    public void onTaskRemoved(Intent rootIntent) {
        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;
    }
}

在你的MainActivity中:

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))
    }
}