当我尝试从前台服务启动活动并且应用程序未处于前台状态并且也从最近的项目中删除时,我的应用程序将毫无例外地停止工作。但是当应用程序处于前台状态或打开主要活动时工作正常。
“在其他应用程序上绘制”权限也从应用程序设置授予。
我正在使用 oneplus 7 Pro,在 android 11、API 30 上运行。
请帮我!!
前台服务.java
public int onStartCommand(Intent intent, int flags, int startId) {
Notification notification = new NotificationCompat.Builder(this, CHANNEL_ID)
.setContentTitle("Content Title")
.setContentText("Content Text")
.setPriority(NotificationCompat.PRIORITY_DEFAULT)
.build();
startForeground(id, notification);
Intent activityIntent = new Intent(this, SecondActivity.class);
activityIntent.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
this.startActivity(activityIntent);
return START_STICKY;
}
SecondActivity.java
@RequiresApi(api = Build.VERSION_CODES.O_MR1)
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
final Window win = getWindow();
win.addFlags(WindowManager.LayoutParams.FLAG_DISMISS_KEYGUARD);
win.addFlags(WindowManager.LayoutParams.FLAG_KEEP_SCREEN_ON);
setTurnScreenOn(true);
setShowWhenLocked(true);
setContentView(R.layout.second_activity);
}
second_activity.xml
<?xml version="1.0" encoding="utf-8"?>
<androidx.constraintlayout.widget.ConstraintLayout
xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:tools="http://schemas.android.com/tools"
xmlns:app="http://schemas.android.com/apk/res-auto"
android:layout_width="match_parent"
android:layout_height="match_parent"
tools:context=".SecondActivity">
<TextView
android:id="@+id/textView"
android:layout_width="219dp"
android:layout_height="80dp"
android:text="SecondActivity"
android:textColor="#C50A0A"
android:textColorLink="#B11212"
android:textSize="30sp"
app:layout_constraintBottom_toBottomOf="parent"
app:layout_constraintEnd_toEndOf="parent"
app:layout_constraintStart_toStartOf="parent"
app:layout_constraintTop_toTopOf="parent" />
</androidx.constraintlayout.widget.ConstraintLayout>
AndroidManifest.xml
<manifest xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:tools="http://schemas.android.com/tools"
package="com.example.app">
<uses-permission android:name="android.permission.FOREGROUND_SERVICE" />
<uses-permission android:name="android.permission.SYSTEM_ALERT_WINDOW"/>
<application
android:allowBackup="true"
android:icon="@mipmap/ic_launcher"
android:label="@string/app_name"
android:roundIcon="@mipmap/ic_launcher_round"
android:supportsRtl="true"
android:theme="@style/Theme.BatteryApp">
<activity
android:name=".MainActivity"
android:label="@string/app_name"
android:theme="@style/Theme.BatteryApp.NoActionBar">
<intent-filter>
<action android:name="android.intent.action.MAIN" />
<category android:name="android.intent.category.LAUNCHER" />
</intent-filter>
</activity>
<activity android:name=".SecondActivity">
</activity>
<service android:name=".ForgroundService" />
</application>
谢谢!!