Article Directory
foreword
Recently, I am writing a function to open after a click notification is issued Broadcast
and Broadcast Receiver
some things are processed in it . Activity
There is no problem when debugging, but it cannot be opened when the notification is clicked after the app is packaged Activity
. The following debug information can be seen in Logcat
:Indirect notification activity start (trampoline) from xx blocked
about the question
After testing, it is found that the method of broadcast receiver has been successfully triggered , but the problem is that it cannot be opened onReceive
when the notification is clicked .间接地
Activity
After consulting the relevant information, Android 12
I think that the application of the target platform has some behavior changes. Among them, the restriction notification trampoline makes it impossible to open indirectly Activity
.
Notification trampoline: When a user interacts with a notification, some apps respond to a notification tap by launching an app component such as , which ultimately launches an activity that the user ultimately sees and interacts with.
Broadcast
This application component is called the notification trampoline.
How to solve
train of thought
I built one that is not perceived by the user Activity
, and opens this directly when the notification is tapped 跳板Activity
. Process data, send broadcasts, start services, etc. in 跳板Activity
the onCreate
method, and finally start the one you want to open Activity
. After performing all the above operations, call finish
the method to end this跳板Activity
accomplish
- Create a new empty one
Activity
(do not checkGenerate a Layout File
)
AndroidManifest.xml
configure inActivity
_
<activity
android:name=".TrampolineActivity"
android:excludeFromRecents="true"
android:exported="false"
android:theme="@android:style/Theme.Translucent.NoTitleBar"
android:label="TrampolineActivity" />
TrampolineActivity
Write business code in
package xxx;
import static xxx.NOTIFICATION_PRESS_ACTION;
import androidx.appcompat.app.AppCompatActivity;
import android.content.Intent;
import android.os.Bundle;
public class TrampolineActivity extends AppCompatActivity {
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
// 编写你的代码,发送 Broadcast 等
Intent mainActivityIntent = new Intent(this, MainActivity.class);
mainActivityIntent.setFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP);
startActivity(mainActivityIntent); // 启动要打开的Activity
finish(); // 结束跳板Activity
}
}
- set
Notification
upContentIntent
Intent intent = new Intent(context, TrampolineActivity.class);
PendingIntent pendingIntent = PendingIntent.getActivity(context, gatheringEventItem.getId(), intent, PendingIntent.FLAG_UPDATE_CURRENT | PendingIntent.FLAG_IMMUTABLE);
Notification notification = new NotificationCompat.Builder(context, NOTIFICATION_CHANNEL_ID)
.setContentTitle("通知标题")
.setContentText("通知内容")
.setContentIntent(pendingIntent)
.setAutoCancel(true)
.build();