You can not select more than 25 topics Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.

MainActivity.java 6.2KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149
  1. package com.example.fcm;
  2. import androidx.appcompat.app.AppCompatActivity;
  3. import android.annotation.SuppressLint;
  4. import android.app.NotificationChannel;
  5. import android.app.NotificationManager;
  6. import android.os.Build;
  7. import android.os.Bundle;
  8. import android.util.Log;
  9. import android.widget.Button;
  10. import android.widget.Toast;
  11. import com.android.volley.toolbox.JsonObjectRequest;
  12. import com.example.fcm.databinding.ActivityMainBinding;
  13. import com.google.firebase.iid.FirebaseInstanceId;
  14. import com.google.firebase.messaging.FirebaseMessaging;
  15. import org.json.JSONException;
  16. import org.json.JSONObject;
  17. import java.util.HashMap;
  18. import java.util.Map;
  19. import java.util.Objects;
  20. public class MainActivity extends AppCompatActivity {
  21. final private String FCM_API = "https://fcm.googleapis.com/fcm/send";
  22. final private String serverKey = "key=" + "AAAA446tEwQ:APA91bEAqpEFQ0ufbp9WSFIGV68P8kUgNlnKzuEHIcWLeS1YlMwJewRdnAGRae0VpDzriag7ZQbMUMPDiT-LD1kTXLQFM73C9DC13iN4nn9gEYCPVp4MN8JHFm20m1BxS8zWZcKDYFcz";
  23. final private String contentType = "application/json";
  24. private static final String TAG = "MainActivity";
  25. String NOTIFICATION_TITLE;
  26. String NOTIFICATION_MESSAGE;
  27. String TOPIC;
  28. @Override
  29. protected void onCreate(Bundle savedInstanceState) {
  30. super.onCreate(savedInstanceState);
  31. ActivityMainBinding binding = ActivityMainBinding.inflate(getLayoutInflater());
  32. setContentView(binding.getRoot());
  33. Button buttonSend = findViewById(R.id.sendButton);
  34. if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.O) {
  35. // Create channel to show notifications.
  36. String channelId = getString(R.string.default_notification_channel_id);
  37. String channelName = getString(R.string.default_notification_channel_name);
  38. NotificationManager notificationManager =
  39. getSystemService(NotificationManager.class);
  40. notificationManager.createNotificationChannel(new NotificationChannel(channelId,
  41. channelName, NotificationManager.IMPORTANCE_LOW));
  42. }
  43. // If a notification message is tapped, any data accompanying the notification
  44. // message is available in the intent extras. In this sample the launcher
  45. // intent is fired when the notification is tapped, so any accompanying data would
  46. // be handled here. If you want a different intent fired, set the click_action
  47. // field of the notification message to the desired intent. The launcher intent
  48. // is used when no click_action is specified.
  49. //
  50. // Handle possible data accompanying notification message.
  51. // [START handle_data_extras]
  52. if (getIntent().getExtras() != null) {
  53. for (String key : getIntent().getExtras().keySet()) {
  54. Object value = getIntent().getExtras().get(key);
  55. Log.d(TAG, "Key: " + key + " Value: " + value);
  56. }
  57. }
  58. // [END handle_data_extras]
  59. binding.subscribeButton.setOnClickListener(v -> {
  60. Log.d(TAG, "Subscribing to topic");
  61. // [START subscribe_topics]
  62. FirebaseMessaging.getInstance().subscribeToTopic("testForMDT")
  63. .addOnCompleteListener(task -> {
  64. String msg = getString(R.string.msg_subscribed);
  65. if (!task.isSuccessful()) {
  66. msg = getString(R.string.msg_subscribe_failed);
  67. }
  68. Log.d(TAG, msg);
  69. Toast.makeText(MainActivity.this, msg, Toast.LENGTH_SHORT).show();
  70. });
  71. // [END subscribe_topics]
  72. });
  73. binding.logTokenButton.setOnClickListener(v -> {
  74. // Get token
  75. // [START retrieve_current_token]
  76. FirebaseInstanceId.getInstance().getInstanceId()
  77. .addOnCompleteListener(task -> {
  78. if (!task.isSuccessful()) {
  79. Log.w(TAG, "getInstanceId failed", task.getException());
  80. return;
  81. }
  82. // Get new Instance ID token
  83. String token = Objects.requireNonNull(task.getResult()).getToken();
  84. // Log and toast
  85. @SuppressLint({"StringFormatInvalid", "LocalSuppress"}) String msg = getString(R.string.msg_token_fmt, token);
  86. Log.d(TAG, msg);
  87. Toast.makeText(MainActivity.this, msg, Toast.LENGTH_SHORT).show();
  88. });
  89. // [END retrieve_current_token]
  90. });
  91. buttonSend.setOnClickListener(v -> {
  92. TOPIC = "/topics/testForMDT"; //topic must match with what the receiver subscribed to
  93. NOTIFICATION_TITLE = "Test";
  94. NOTIFICATION_MESSAGE = "Gregor";
  95. JSONObject notification = new JSONObject();
  96. JSONObject notifcationBody = new JSONObject();
  97. try {
  98. notifcationBody.put("title", NOTIFICATION_TITLE);
  99. notifcationBody.put("message", NOTIFICATION_MESSAGE);
  100. notification.put("to", TOPIC);
  101. notification.put("data", notifcationBody);
  102. } catch (JSONException e) {
  103. Log.e(TAG, "onCreate: " + e.getMessage() );
  104. }
  105. sendNotification(notification);
  106. });
  107. }
  108. private void sendNotification(JSONObject notification) {
  109. JsonObjectRequest jsonObjectRequest = new JsonObjectRequest(FCM_API, notification,
  110. response -> {
  111. Log.i(TAG, "onResponse: " + response.toString());
  112. //edtTitle.setText("");
  113. //edtMessage.setText("");
  114. },
  115. error -> {
  116. Toast.makeText(MainActivity.this, "Request error", Toast.LENGTH_LONG).show();
  117. Log.i(TAG, "onErrorResponse: Didn't work");
  118. }){
  119. @Override
  120. public Map<String, String> getHeaders() {
  121. Map<String, String> params = new HashMap<>();
  122. params.put("Authorization", serverKey);
  123. params.put("Content-Type", contentType);
  124. return params;
  125. }
  126. };
  127. MySingleton.getInstance(getApplicationContext()).addToRequestQueue(jsonObjectRequest);
  128. }
  129. }