如何在前台服务中检查应用是否正在运行?

3

我在我的应用程序中有一个前台服务,其工作方式取决于其所属的应用程序是否存在。

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

在前台服务中有没有一种方法可以检查应用程序是否正在运行?

答案:最初的回答是没有一种可靠的方式来检查应用程序是否在运行中。该应用程序可能已经被销毁或被杀死了。您可以考虑使用其他方法来实现您的需求,例如使用广播机制或更改应用程序的架构以便更好地管理应用程序的状态。


你尝试过从你的活动中绑定到服务吗? - undefined
@Pawel 它已经绑定了 - undefined
onBindonUnbind之间检查状态不够精确吗? - undefined
@Pawel刚刚尝试了你的建议。不幸的是,当应用程序从最近的屏幕中被踢出时,onUnbind方法没有被调用。 - undefined
@Pawel,当应用程序进入后台时会调用它。这对我来说不是正确的位置。 - undefined
1个回答

3

没有合适的方法来做到这一点。一个解决方法是从你的活动中正常启动服务,并重写 onTaskRemoved 方法。当你的应用程序从最近的应用程序屏幕中删除时,将调用此方法。您可以在主服务类中设置全局静态变量,并稍后访问它们以确定应用程序是否被杀死。

以下是服务代码:

您的前台服务:

Kotlin:

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;

}

您的应用状态检查服务:

Kotlin:

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

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接