没有合适的方法来做到这一点。一个解决方法是从你的活动中正常启动服务,并重写 onTaskRemoved
方法。当你的应用程序从最近的应用程序屏幕中删除时,将调用此方法。您可以在主服务类中设置全局静态变量,并稍后访问它们以确定应用程序是否被杀死。
以下是服务代码:
您的前台服务:
Kotlin:
class ForegroundService : Service() {
companion object {
@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 {
ForegroundService.isAppInForeground = true
return START_NOT_STICKY
}
override fun onTaskRemoved(rootIntent: Intent?) {
super.onTaskRemoved(rootIntent)
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) {
ForegroundService.isAppInForeground = true;
return START_NOT_STICKY;
}
@Override
public void onTaskRemoved(Intent rootIntent) {
super.onTaskRemoved(rootIntent);
ForegroundService.isAppInForeground = false;
}
}
在你的 MainActivity
中:
class MainActivity : AppCompatActivity() {
override fun onCreate(savedInstanceState: Bundle?) {
super.onCreate(savedInstanceState)
setContentView(R.layout.activity_main)
startService(Intent(this, AppKillService::class.java))
}
}
onBind
和onUnbind
之间检查状态不够精确吗? - undefinedonUnbind
方法没有被调用。 - undefined