在接收推送通知时打开反应本机应用程序,无需单击通知

问题描述 投票:0回答:1

我想在设备收到推送通知时打开反应本机应用程序。

我已经使用此代码打开应用程序,其工作正常,仅低于 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 则不然,并且没有收到任何警告和错误

android react-native android-intent android-activity android-lifecycle
1个回答
0
投票

1.您应该显示通知而不是启动意图,并在pendingIntent上分配活动。

尝试下面的代码:

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());
    }
}

2.确保为 Android 8 及更高版本设置通知渠道。

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);
}

3.
POST_NOTIFICATIONS
Andorid 13 及以上版本的权限

<manifest ...>
    <uses-permission android:name="android.permission.POST_NOTIFICATIONS"/>
    <application ...>
        ...
    </application>
</manifest>

遵循以上几点即可解决您的问题。

© www.soinside.com 2019 - 2024. All rights reserved.