我想跟踪一个应用程序,即“com.facebook.katana”,我已经有了它的包名,现在我的问题是,我要调用我的应用程序并在该应用程序(“com.facebook. katana”)打开,好吧,让我们直说吧,我正在制作一个应用程序储物柜,但我只想锁定这个应用程序(“com.facebook.katana”)!我会做其他事情,但只需要在该应用程序启动时帮助启动我的 Activity ! 提前致谢!
我目前正在使用这段代码:
ActivityManager mActivityManager = (ActivityManager) getSystemService(Context.ACTIVITY_SERVICE);
List<ActivityManager.RunningTaskInfo> RunningTask = mActivityManager.getRunningTasks(1);
ActivityManager.RunningTaskInfo ar = RunningTask.get(0);
String activityOnTop = ar.topActivity.getClassName ();
最佳答案
TL;DR;
您必须创建一个 Service定期检查哪个是前景 Activity
以及它是否属于带有 ActivityManager 的 com.facebook.katana
.
如果是,启动你的储物柜 Activity
。
你的代码没问题,只要把它放在我上面描述的服务中即可。
请注意,如果您的目标是 Oreo+,则必须将其作为前台服务。
LR
因此,在 Android 中,当您想要定期执行某项工作但又不想让您的应用程序出现在屏幕顶部时(这意味着您的应用程序处于后台或什至未启动),您有多种选择,这称为 scheduling tasks .
我在这里为您提供的选项是服务
,出于多种原因,您每次都可以阅读我链接的文档。
为此,创建一个这样的服务:
class ForegroundScanService : Service() {
val handler = Handler(Looper.getMainLooper())
override fun onBind(intent: Intent?): IBinder? {
return null
}
override fun onStartCommand(intent: Intent?, flags: Int, startId: Int): Int {
startForeground(1, createNotification())
checkApp()
// Ended
return START_STICKY
}
fun checkApp() {
// Detect if the target app is on top, if yes invoke your app with an intent if it hasn't been done already
if(appIsDetected()) {
startYourApp()
}
// Ask the system to restart us, there are many ways to do this, each one will impact the battery in a different way
handler.postDelayed(object: Runnable() {
override fun run() {
checkApp()
}
}, 5000);
}
}
然后在您的 list 中声明它并从您的应用 Activity 中启动它。 由于该服务将存在并持续运行,“最佳”方式是使用 ForegroundService。如果您不这样做并选择使用 WorkManager 或 AlarmManager 或其他东西,这对电池来说更好,但重新启动时间有限。
虽然实现不是您选择的那个,但这应该可以解释它的工作方式。
顺便说一下,您可以找到有关 Handler here 的文档.
关于android - 如何在某些特定打开时调用我的应用程序并启动它,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/53959558/