如何进行通知单击的特定活动



有几个通知,然后单击我要转到特定活动的通知。假设出现奖励通知,单击将获得奖励性,而新朋友则添加了新朋友,然后单击NewFriend Notification将转向友好列表,无论该应用在前景还是背景中。

,但就我而言,如果出现任何通知,则进行相同的活动而不是不同的活动。

private void handleDataMessage(String noti_title,String noti_message,String noti_click_action) {
    try {
        Intent intent = new Intent(this, RewardActivity.class);
        intent.addFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP);
        intent.putExtra("title", noti_title);
        ByteArrayOutputStream _bs = new ByteArrayOutputStream();
        //image.compress(Bitmap.CompressFormat.PNG, 50, _bs);
        //intent.putExtra("img", image);
        intent.putExtra("msg", noti_message);
        intent.putExtra("click_action", noti_click_action);
        PendingIntent pendingIntent = PendingIntent.getActivity(this, 0 /* Request code */, intent,
                PendingIntent.FLAG_ONE_SHOT);
        Uri defaultSoundUri = RingtoneManager.getDefaultUri(RingtoneManager.TYPE_NOTIFICATION);
        NotificationCompat.Builder notificationBuilder = new
                NotificationCompat.Builder(this, "Default")
                //.setLargeIcon(R.mipmap.ic_launcher)/*Notification icon image*/
                .setSmallIcon(R.mipmap.ic_launcher)
                //.setStyle(new NotificationCompat.BigPictureStyle().bigPicture(image))/*Notification with Image*/
                .setAutoCancel(true)
                .setSound(defaultSoundUri)
                .setPriority(Notification.PRIORITY_HIGH)
                .setChannelId("Default")
                .setVibrate(new long[]{1000, 1000})
                .setContentIntent(pendingIntent);
        notificationBuilder.setContentTitle(noti_title);
        notificationBuilder.setContentText(noti_message);
        notificationBuilder.setAutoCancel(true);
        NotificationManager notificationManager =
                (NotificationManager) getSystemService(Context.NOTIFICATION_SERVICE);
        notificationManager.notify(0 /* ID of notification */, notificationBuilder.build());

    } catch (Exception e) {
        Log.e(TAG, "Exception: " + e.getMessage());
    }
}

fcm会自动代表客户端应用显示消息到最终用户设备。当用户单击通知时,创建了两个条件

  1. 当您的应用在后台时,已发送通知。在这种情况下,将通知传递到设备的系统托盘上。用户点击通知,默认情况下打开应用启动器。

  2. 带有通知和数据有效载荷的消息,背景和前景。在这种情况下,通知已发送给设备的系统托盘和数据有效载荷以您的发射器活动意图的附加功能传递。

如果您想在应用程序在后台时打开所需的活动,并且通知仅包含通知,并且没有数据播放,则不适合。

但是,如果您想在应用程序在后台时打开所需的活动并且通知为数据plagload,则可以导航用户进行所需的活动。

当带有数据有效载荷的消息,背景和前景状态时,请参见下面的示例。

在我的AndroidManifest启动器活动中是飞溅性

<activity android:name=".activities.SplashActivity">
<intent-filter>
    <action android:name="android.intent.action.MAIN" />
    <category android:name="android.intent.category.LAUNCHER" />
</intent-filter>

您可以从Google FCM Tester上的Pushtry.com上测试通知。通过pushtry.com

发送时,这是播放数据的格式
{
  "to":"your_device_token",
  "data": {
      "title": "hello",
      "message": "test message",
  },
 "priority":"high"
}

myfirebasemessagingservice类:

public class MyFirebaseMessagingService extends FirebaseMessagingService {
    private static final String TAG = "FCM Service";
    private static int count = 0;
    @Override
    public void onNewToken(String s) {
        super.onNewToken(s);
        KeyManager.setSharedPreferenceString(getApplicationContext(), "fcm_token", s);
        Log.e(TAG, "onNewToken: " + s);
    }
    @Override
    public void onMessageReceived(RemoteMessage remoteMessage) {
//Here notification is recieved from server
        try {
            sendNotification(remoteMessage.getData().get("title"), remoteMessage.getData().get("message"));
        } catch (Exception e) {
            e.printStackTrace();
        }
    }
    private void sendNotification(String title, String messageBody) {
        Intent intent = new Intent(getApplicationContext(), SplashActivity.class);  
//you can use your launcher Activity insted of SplashActivity, But if the Activity you used here is not launcher Activty than its not work when App is in background.
        intent.addFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP);
//Add Any key-value to pass extras to intent
        intent.putExtra("pushnotification", "yes");
        PendingIntent pendingIntent = PendingIntent.getActivity(this, 0, intent, PendingIntent.FLAG_ONE_SHOT);
        Uri defaultSoundUri = RingtoneManager.getDefaultUri(RingtoneManager.TYPE_NOTIFICATION);
        NotificationManager mNotifyManager = (NotificationManager) getSystemService(Context.NOTIFICATION_SERVICE);
//For Android Version Orio and greater than orio.
        if (android.os.Build.VERSION.SDK_INT >= android.os.Build.VERSION_CODES.O) {
            int importance = NotificationManager.IMPORTANCE_LOW;
            NotificationChannel mChannel = new NotificationChannel("Sesame", "Sesame", importance);
            mChannel.setDescription(messageBody);
            mChannel.enableLights(true);
            mChannel.setLightColor(Color.RED);
            mChannel.enableVibration(true);
            mChannel.setVibrationPattern(new long[]{100, 200, 300, 400, 500, 400, 300, 200, 400});
            mNotifyManager.createNotificationChannel(mChannel);
        }
//For Android Version lower than orio.
        NotificationCompat.Builder mBuilder = new NotificationCompat.Builder(this, "Seasame");
        mBuilder.setContentTitle(title)
                .setContentText(messageBody)
                .setSmallIcon(R.mipmap.ic_launcher_sesame)
                .setLargeIcon(BitmapFactory.decodeResource(getResources(), R.mipmap.ic_launcher_sesame))
                .setAutoCancel(true)
                .setSound(defaultSoundUri)
                .setColor(Color.parseColor("#FFD600"))
                .setContentIntent(pendingIntent)
                .setChannelId("Sesame")
                .setPriority(NotificationCompat.PRIORITY_LOW);
        mNotifyManager.notify(count, mBuilder.build());
        count++;
    }
}

现在,当您在背景条件下收到推送通知并单击通知时,将发送到通知设备的系统托盘和附加功能传递给您的启动器活动。检查启动器活动是带有附加功能或空的,而不是导航用户进行所需的活动。

如果您想显示您的活动仅登录用户,而不是以下内容如下:

public class SplashActivity extends AppCompatActivity {
    @Override
    protected void attachBaseContext(Context newBase) {
        super.attachBaseContext(CalligraphyContextWrapper.wrap(newBase));
    }
    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_splash);
        try {
            if (KeyManager.getSharedPreferenceBoolean(SplashActivity.this, "isLoggedIn", false)) {
                if (getIntent().hasExtra("pushnotification")) {
                    Intent intent = new Intent(this, YourDesiredActivity.class);
                    startActivity(intent);
                    finish();
                } else {
                    CheckLogin();
                }
            } else {
                Intent i = new Intent(SplashActivity.this, LoginActivity.class);
                startActivity(i);
                finish();
            }
        } catch (Exception e) {
            CheckLogin();
            e.printStackTrace();
        }
    }
    private void CheckLogin() {
        if (KeyManager.getSharedPreferenceBoolean(SplashActivity.this, "isLoggedIn", false)) {
            Intent i = new Intent(SplashActivity.this, MainActivity.class);
            startActivity(i);
        } else {
            new Handler().postDelayed(new Runnable() {
                @Override
                public void run() {
                    Intent i = new Intent(SplashActivity.this, LoginActivity.class);
                    startActivity(i);
                    finish();
                }
            }, 2500);
        }
    }
}

逻辑在splashactivty中,根据条件在不同活动中导航用户。

当用户在不单击pushnotification的情况下以普通流量打开应用程序时,getIntent((。hasextra(" pushnotification"(为null,因此命令会捕获block and checklogin((方法检查是否已经登录。但是通过单击pushnotification输入的用户,然后getIntent((。hasextra(" pushnotification"(不是null,他将进行所需的活动。

我遇到了相同的问题,经过文档后,这两个步骤对我有用。

  1. 定义应用程序的活动层次结构
  2. 并使用了TaskStackBuilder。我缺少的。
TaskStackBuilder stackBuilder = TaskStackBuilder.create(this);
stackBuilder.addNextIntentWithParentStack(resultIntent);

完成代码:

private void createNotificationChannel() {
    if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.O) {
        NotificationChannel serviceChannel = new NotificationChannel(
                "Foreground_Service_Channel_Id",
                "Foreground_Service_Channel_Name",
                NotificationManager.IMPORTANCE_DEFAULT
        );
        NotificationManager manager = getApplicationContext().getSystemService(NotificationManager.class);
        manager.createNotificationChannel(serviceChannel);
    }
}
private void showNotification()
{
    Intent notificationIntent = new Intent(context, YOUR_ACTIVITY.class);
    TaskStackBuilder stackBuilder = TaskStackBuilder.create(this);
    stackBuilder.addNextIntentWithParentStack(notificationIntent);
    PendingIntent resultPendingIntent =
            stackBuilder.getPendingIntent(0, PendingIntent.FLAG_UPDATE_CURRENT);
    if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.O) {
        createNotificationChannel();
        Notification.Builder builder = new Notification.Builder(context, "Foreground_Service_Channel_Id")
                .setSmallIcon(R.drawable.ic_mode_night_24)
                .setContentTitle("SAMPLE_TEXT_TITLE")
                .setContentIntent(resultPendingIntent)
                .setStyle(new Notification.InboxStyle()
                        .setSummaryText("SAMPLE_TEXT"))
                .setSound(RingtoneManager.getDefaultUri(RingtoneManager.TYPE_NOTIFICATION))
                .setOngoing(true)
                .setAutoCancel(false);
        Notification notification = builder.build();
        startForeground(ID, notification);
    } else {
        NotificationCompat.Builder builder = new NotificationCompat.Builder(context)
                .setSmallIcon(R.drawable.ic_mode_night_24)
                .setContentTitle("SAMPLE_TEXT_TITLE")
                .setContentIntent(resultPendingIntent)
                .setPriority(NotificationCompat.PRIORITY_DEFAULT)
                .setSound(RingtoneManager.getDefaultUri(RingtoneManager.TYPE_NOTIFICATION))
                .setOngoing(true)
                .setAutoCancel(false);
        builder.setContentIntent(resultPendingIntent);
        Notification notification = builder.build();
        startForeground(ID, notification);
    }
}

最新更新