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.8KB

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