Android12,真机红米K50G,在成功启动ForegroundService后,启动activity无效。
并且在Android10的虚拟机上能够正常启动activity
public class ForegroundService extends Service {
private static final String TAG = "May";
@Nullable
@Override
public IBinder onBind(Intent intent) {
return null;
}
@Override
public int onStartCommand(Intent intent, int flags, int startId) {
NotificationChannel channel = new NotificationChannel(Constants.WIDGET_NOTIFY_ID,
Constants.WIDGET_NOTIFY_NAME,
NotificationManager.IMPORTANCE_DEFAULT);
((NotificationManager) getSystemService(Context.NOTIFICATION_SERVICE))
.createNotificationChannel(channel);
Notification notification = new NotificationCompat.Builder(this, Constants.WIDGET_NOTIFY_ID)
.build();
startForeground(Constants.CONSTANTS_1, notification);
Log.e(TAG, "onStartCommand: ");
Intent gotoCreate = new Intent();
gotoCreate.setClass(this, MainActivity.class);
gotoCreate.putExtra(Constants.GOTO_CREATE, true);
gotoCreate.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK|Intent.FLAG_ACTIVITY_MULTIPLE_TASK|Intent.FLAG_ACTIVITY_CLEAR_TASK);
startActivity(gotoCreate);
stopForeground(Service.STOP_FOREGROUND_REMOVE);
onDestroy();
return super.onStartCommand(intent, flags, startId);
}
@Override
public void onCreate() {
super.onCreate();
Log.e(TAG, "onCreate: " );
}
@Override
public void onDestroy() {
super.onDestroy();
Log.e(TAG, "onDestroy: ");
stopForeground(Service.STOP_FOREGROUND_REMOVE);
}
}
结果,服务正常启动后,能运行到startActivity();但是,手机没有响应,即没有启动这个activity。
虚拟机上能够正常跳转到MainActivity。
两个手机测试时都没有响应报错。
尝试过给与悬浮窗权限,更改不同的intent flag。但是真机中跳转都无效
真机能和虚拟机一样跳转到相应Activity
在 Android 10 或更高版本上运行的应用只有在满足以下一项或多项条件时,才能启动 Activity:
应用具有可见窗口,例如前台 Activity。
应用在前台任务的返回栈中拥有 Activity。
应用在 Recents 屏幕上现有任务的返回栈中拥有 Activity。