我有一个
ForegroundService
需要一点时间才能运行。同时,用户可能会在应用程序运行时将其移至后台,例如按主页按钮或进入其他应用程序。当 ForegroundService
到达“触发器”时,它会尝试开始一个新的意图。如果应用程序在前台,这很好用,但如果它在后台,则不起作用。目标是当达到“触发器”时,应用程序将返回前台,以便用户可以在新意图中提供所需的输入。为了尝试这样做,我添加了标志 FLAG_ACTIVITY_NEW_TASK
和 FLAG_ACTIVITY_SINGLE_TOP
,因为它们看起来可以完成此操作。但是该应用程序不会返回到前台。这是可以做到的吗?
以下是有问题的代码的相关部分:
MainActivity.kt
...
private fun startService() {
val serviceIntent = Intent(this, ForegroundService::class.java)
ContextCompat.startForegroundService(this, serviceIntent)
}
...
ForegroundService.kt
...
//When trigger is reached, start the new activity and bring app to foreground if it was moved to background
private fun startNewActivity() {
//First two lines are to shut down the foreground service since it has reached a trigger and is complete.
super.onDestroy()
stopSelf()
//Start the new intent
val startNewIntent = Intent(this, NewIntent:: class.java)
startNewIntent.flags = Intent.FLAG_ACTIVITY_NEW_TASK or Intent.FLAG_ACTIVITY_SINGLE_TOP //Assumption was these flags would bring app to foreground
startActivity(startNewIntent)
}
...
PendingIntent
而不是普通的Intent
;当前台服务结束时(当你的触发器被触发时),你可以使用 send()
方法发送这个未决的意图
ForegroundService.kt
...
//When trigger is reached, start the new activity and bring app to foreground if it was moved to background
private fun startNewActivity() {
//First two lines are to shut down the foreground service since it has reached a trigger and is complete.
super.onDestroy()
stopSelf()
//Start the new intent
val startNewIntent = Intent(this, NewIntent:: class.java)
val pendingIntent = PendingIntent.getActivity(
this, 0, startNewIntent,
PendingIntent.FLAG_UPDATE_CURRENT
or PendingIntent.FLAG_ONE_SHOT
)
try {
pendingIntent.send() // this should start `NewIntent` activity
} catch (e: CanceledException) {
e.printStackTrace()
}
}
...
如果您使用的是android 10及以上版本,则需要申请
android.permission.SYSTEM_ALERT_WINDOW
权限。这些可以使用以下方式授予。
// Check if the permission is granted
if (Settings.canDrawOverlays(this)) {
// Permission is granted, start your service
startService(new Intent(this, FloatingViewService.class));
} else {
// Permission is not granted, ask the user to enable it
Intent intent = new Intent(Settings.ACTION_MANAGE_OVERLAY_PERMISSION,
Uri.parse("package:" + getPackageName()));
startActivityForResult(intent, REQUEST_CODE);
}
// Handle the result of the user's action
@Override
protected void onActivityResult(int requestCode, int resultCode, Intent data) {
if (requestCode == REQUEST_CODE) {
// Check if the permission is granted
if (Settings.canDrawOverlays(this)) {
// Permission is granted, start your service
startService(new Intent(this, FloatingViewService.class));
} else {
// Permission is denied, show a message
Toast.makeText(this, "Please enable overlay permission", Toast.LENGTH_SHORT).show();
}
}
}
https://developer.android.com/reference/android/Manifest.permission#SYSTEM_ALERT_WINDOW