我想在设备收到推送通知时打开反应本机应用程序。
我已经使用此代码打开应用程序,其工作正常,仅低于 Android 10 版本。但不适用于更高版本的 Android 10。
public void onReceive(Context context, Intent intent) {
Log.d(TAG, "broadcast received for message");
Intent launchIntent = context.getPackageManager().getLaunchIntentForPackage("com.theDocSuiteDriver");
if (launchIntent != null) {
launchIntent.addFlags(Intent.FLAG_ACTIVITY_LAUNCHED_FROM_HISTORY);
context.startActivity(launchIntent);
}
}
此代码在发送推送通知时起作用。但对于更高版本的 android 10 则不然,并且没有收到任何警告和错误
尝试下面的代码:
public void onReceive(Context context, Intent intent) {
Log.d(TAG, "broadcast received for message");
Intent launchIntent = context.getPackageManager().getLaunchIntentForPackage("com.theDocSuiteDriver");
if (launchIntent != null) {
launchIntent.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK | Intent.FLAG_ACTIVITY_CLEAR_TASK);
PendingIntent pendingIntent = PendingIntent.getActivity(context, 0, launchIntent, PendingIntent.FLAG_UPDATE_CURRENT);
NotificationCompat.Builder builder = new NotificationCompat.Builder(context, "your_channel_id")
.setSmallIcon(R.drawable.notification_icon)
.setContentTitle("Notification Title")
.setContentText("Notification Text")
.setPriority(NotificationCompat.PRIORITY_DEFAULT)
.setContentIntent(pendingIntent)
.setAutoCancel(true);
NotificationManagerCompat notificationManager = NotificationManagerCompat.from(context);
notificationManager.notify(1, builder.build());
}
}
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.O) {
CharSequence name = "Channel Name";
String description = "Channel Description";
int importance = NotificationManager.IMPORTANCE_DEFAULT;
NotificationChannel channel = new NotificationChannel("your_channel_id", name, importance);
channel.setDescription(description);
NotificationManager notificationManager = context.getSystemService(NotificationManager.class);
notificationManager.createNotificationChannel(channel);
}
POST_NOTIFICATIONS
Andorid 13 及以上版本的权限<manifest ...>
<uses-permission android:name="android.permission.POST_NOTIFICATIONS"/>
<application ...>
...
</application>
</manifest>
遵循以上几点即可解决您的问题。