简体   繁体   English

如何打开新活动并通过单击Firebase通知在textview上打印通知消息

[英]How open a new activity & print the notification message on a textview by clicking on firebase notification

I want make my firebase notifications clickable. 我想让我的Firebase通知可点击。 After clicking the notification, a new activity called HomeActivity will open where i want to show the notification message as a textview. 单击通知后,将打开一个名为HomeActivity的新活动,我想在其中将通知消息显示为textview。

I've added the notification & it is working well. 我已经添加了通知,并且运行良好。 But whenever i click the notification it goes back to the mainActivity & doesn't show the message in textview. 但是,每当我单击通知时,它都会返回到mainActivity,并且不会在textview中显示该消息。 I've tried some code but its not working. 我已经尝试了一些代码,但无法正常工作。

here is my code, 这是我的代码,

MyFirebaseInstanceService.class MyFirebaseInstanceService.class

public class MyFirebaseInstanceService extends FirebaseMessagingService {


@Override
public void onMessageReceived(RemoteMessage remoteMessage) {
    super.onMessageReceived(remoteMessage);
    shownotification(remoteMessage.getNotification().getTitle(),remoteMessage.getNotification().getBody());
    String click_action = remoteMessage.getNotification().getClickAction();
    Intent i = new Intent(click_action);
    Intent in = new Intent("intentKey");
            in.putExtra("key", remoteMessage);
    LocalBroadcastManager.getInstance(getApplicationContext()).sendBroadcast(in);

    Intent intent = new Intent("com.push.message.received");
    intent.putExtra("message", remoteMessage);// Add more data as per need
    sendBroadcast(intent);

}

private void shownotification(String title,String body){
        NotificationManager notificationManager = (NotificationManager)getSystemService(Context.NOTIFICATION_SERVICE);
        String NOTIFICATION_CHANNEL_ID = "com.example.theroos.simplifiedmsging02.test";

        if(Build.VERSION.SDK_INT >= Build.VERSION_CODES.O)
        {
            NotificationChannel notificationChannel = new NotificationChannel(NOTIFICATION_CHANNEL_ID, "Notification",NotificationManager.IMPORTANCE_DEFAULT);
            notificationChannel.setDescription("SIMPLIFIED");
            notificationChannel.setLightColor(Color.BLUE);
            notificationChannel.setVibrationPattern(new long[]{0,100,500,1000});
            notificationChannel.enableLights(true);
            //notificationChannel.createNotificationChannel(notificationChannel);

        }

        Intent activityintent = new Intent(this,HomeActivity.class);
        PendingIntent contentintent = PendingIntent.getActivity(this,0,activityintent,0);



        NotificationCompat.Builder notificationbuilder = new NotificationCompat.Builder(this,NOTIFICATION_CHANNEL_ID);

        notificationbuilder.setAutoCancel(true)
                .setDefaults(Notification.DEFAULT_ALL)
                .setWhen(System.currentTimeMillis())
                .setSmallIcon(R.drawable.ic_mode_comment_black_24dp)
                .setContentTitle(title)
                .setContentIntent(contentintent)
                .setContentText(body)
                .setColor(Color.BLUE)
                .setAutoCancel(true)
                .setContentInfo("Info");

        notificationManager.notify(new Random().nextInt(),notificationbuilder.build());




}

@Override
public void onNewToken(String token) {
    super.onNewToken(token);
    Log.d("TOKEN",token);
}

} }

HomeActivity.class HomeActivity.class

public class HomeActivity extends AppCompatActivity {

private Button signout_button;
private TextView message_textView;
FirebaseAuth mAuth;

private BroadcastReceiver activityReceiver = new BroadcastReceiver() {
    @Override
    public void onReceive(Context context, Intent intent) {
        TextView message_textview = (TextView) findViewById(R.id.message_textView);
        String message=intent.getStringExtra("message");
        message_textView.setText(message);
    }

};

@Override
protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.activity_home);
    signout_button = (Button) findViewById(R.id.signoutbutton);
    //message_textView = (TextView)findViewById(R.id.message_textView);

    //message_textView.setText(getIntent().getExtras().getString("body"));

    if (activityReceiver != null) {
        IntentFilter intentFilter = new  IntentFilter("ACTION_STRING_ACTIVITY");
        registerReceiver(activityReceiver, intentFilter);
    }

    LocalBroadcastManager.getInstance(HomeActivity.this).registerReceiver(
            activityReceiver, new IntentFilter("intentKey"));

    signout_button.setOnClickListener(new View.OnClickListener() {
        @Override
        public void onClick(View v) {
            FirebaseAuth.getInstance().signOut();
            startActivity(new Intent(HomeActivity.this, MainActivity.class));
            Toast.makeText(HomeActivity.this, "Successfully Signed Out", Toast.LENGTH_SHORT).show();
        }
    });
}

   }

I don't know what wrong i have did please help me. 我不知道我做错了什么,请帮助我。 Thank you in advance. 先感谢您。

There are some ways how you can achieve this. 有一些方法可以实现这一目标。 But there are lots of similar questions on stackoverflow. 但是关于stackoverflow也有很多类似的问题。

The method depends on your fcm notification payload. 该方法取决于您的fcm通知有效负载。 Please see this answer. 请参阅此答案。 You'll find all the things you're looking for. 您会找到所有想要的东西。

https://stackoverflow.com/a/40185654/7140884 https://stackoverflow.com/a/40185654/7140884

At first you shouldnt create notification and sendbroadcast message at the same time. 首先,您不应该同时创建通知和发送广播消息。 Try this: 尝试这个:

        public class MyFirebaseInstanceService extends FirebaseMessagingService {


    @Override
    public void onMessageReceived(RemoteMessage remoteMessage) {
        super.onMessageReceived(remoteMessage);
               NotificationManager notificationManager = (NotificationManager)getSystemService(Context.NOTIFICATION_SERVICE);
        String NOTIFICATION_CHANNEL_ID = "com.example.theroos.simplifiedmsging02.test";

        if(Build.VERSION.SDK_INT >= Build.VERSION_CODES.O)
        {
            NotificationChannel notificationChannel = new NotificationChannel(NOTIFICATION_CHANNEL_ID, "Notification",NotificationManager.IMPORTANCE_DEFAULT);
            notificationChannel.setDescription("SIMPLIFIED");
            notificationChannel.setLightColor(Color.BLUE);
            notificationChannel.setVibrationPattern(new long[]{0,100,500,1000});
            notificationChannel.enableLights(true);
            //notificationChannel.createNotificationChannel(notificationChannel);

        }

        Intent activityintent = new Intent(this,HomeActivity.class);
        PendingIntent contentintent = PendingIntent.getActivity(this,0,activityintent,0);

        NotificationCompat.Builder notificationbuilder = new NotificationCompat.Builder(this,NOTIFICATION_CHANNEL_ID);

        notificationbuilder.setAutoCancel(true)
                .setDefaults(Notification.DEFAULT_ALL)
                .setWhen(System.currentTimeMillis())
                .setSmallIcon(R.drawable.ic_mode_comment_black_24dp)
                .setContentTitle(title)
                .setContentIntent(contentintent)
                .setContentText(body)
                .setColor(Color.BLUE)
                .setAutoCancel(true)
                .setContentInfo("Info");

        notificationManager.notify(new Random().nextInt(),notificationbuilder.build());

    }
....

Then instead of PendingIntent.getActivity you can create PendingIntent.getBroadcast(YourBroadcastReceiver..) for broadcastreceiver which you should register in manifest: 然后,您可以为广播PendingIntent.getBroadcast(YourBroadcastReceiver..)器创建PendingIntent.getBroadcast(YourBroadcastReceiver..) ,而不是PendingIntent.getActivity ,您应该在清单中进行注册:

<receiver
    android:name="com.app.YourBroadcastReceiver"
    android:enabled="true"
    android:exported="true">
    <intent-filter>
        <action android:name="YourReceiverIntentFilter" />
    </intent-filter>
</receiver>

In YourBroadcastReceiver you should get pending intent and then send broadcast message to your local receiver in your activity. YourBroadcastReceiver您应该获得待处理的意图,然后在活动中将广播消息发送到本地接收器。

Hope it helps! 希望能帮助到你!

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM