123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161 |
- package com.example.fcm;
-
- import androidx.appcompat.app.AppCompatActivity;
-
- import android.annotation.SuppressLint;
- import android.app.NotificationChannel;
- import android.app.NotificationManager;
- import android.content.Context;
- import android.os.Build;
- import android.os.Bundle;
- import android.os.VibrationEffect;
- import android.os.Vibrator;
- import android.util.Log;
- import android.widget.Button;
- import android.widget.EditText;
- import android.widget.Toast;
- import com.android.volley.toolbox.JsonObjectRequest;
- import com.example.fcm.databinding.ActivityMainBinding;
- import com.google.firebase.iid.FirebaseInstanceId;
- import com.google.firebase.messaging.FirebaseMessaging;
-
- import org.json.JSONException;
- import org.json.JSONObject;
-
- import java.util.HashMap;
- import java.util.Map;
- import java.util.Objects;
-
-
- public class MainActivity extends AppCompatActivity {
-
- final private String FCM_API = "https://fcm.googleapis.com/fcm/send";
- final private String serverKey = "key=" + "AAAA446tEwQ:APA91bEAqpEFQ0ufbp9WSFIGV68P8kUgNlnKzuEHIcWLeS1YlMwJewRdnAGRae0VpDzriag7ZQbMUMPDiT-LD1kTXLQFM73C9DC13iN4nn9gEYCPVp4MN8JHFm20m1BxS8zWZcKDYFcz";
- final private String contentType = "application/json";
- final private String topic = "vibration";
- private static final String TAG = "MainActivity";
-
- String NOTIFICATION_TITLE;
- String NOTIFICATION_MESSAGE;
- String TOPIC;
-
- @Override
- protected void onCreate(Bundle savedInstanceState) {
- super.onCreate(savedInstanceState);
- ActivityMainBinding binding = ActivityMainBinding.inflate(getLayoutInflater());
- setContentView(binding.getRoot());
-
- Button buttonSend = findViewById(R.id.sendButton);
- EditText level = findViewById(R.id.level);
- EditText delay = findViewById(R.id.delay);
- EditText duration = findViewById(R.id.duration);
-
- if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.O) {
- // Create channel to show notifications.
- String channelId = getString(R.string.default_notification_channel_id);
- String channelName = getString(R.string.default_notification_channel_name);
- NotificationManager notificationManager =
- getSystemService(NotificationManager.class);
- notificationManager.createNotificationChannel(new NotificationChannel(channelId,
- channelName, NotificationManager.IMPORTANCE_LOW));
- }
-
- // If a notification message is tapped, any data accompanying the notification
- // message is available in the intent extras. In this sample the launcher
- // intent is fired when the notification is tapped, so any accompanying data would
- // be handled here. If you want a different intent fired, set the click_action
- // field of the notification message to the desired intent. The launcher intent
- // is used when no click_action is specified.
- //
- // Handle possible data accompanying notification message.
- // [START handle_data_extras]
- if (getIntent().getExtras() != null) {
- for (String key : getIntent().getExtras().keySet()) {
- Object value = getIntent().getExtras().get(key);
- Log.d(TAG, "Key: " + key + " Value: " + value);
- }
- }
- // [END handle_data_extras]
-
- binding.subscribeButton.setOnClickListener(v -> {
- Log.d(TAG, "Subscribing to topic");
- // [START subscribe_topics]
- FirebaseMessaging.getInstance().subscribeToTopic(topic)
- .addOnCompleteListener(task -> {
- String msg = getString(R.string.msg_subscribed);
- if (!task.isSuccessful()) {
- msg = getString(R.string.msg_subscribe_failed);
- }
- Log.d(TAG, msg);
- Toast.makeText(MainActivity.this, msg, Toast.LENGTH_SHORT).show();
- });
- // [END subscribe_topics]
- });
-
- binding.logTokenButton.setOnClickListener(v -> {
- // Get token
- // [START retrieve_current_token]
- FirebaseInstanceId.getInstance().getInstanceId()
- .addOnCompleteListener(task -> {
- if (!task.isSuccessful()) {
- Log.w(TAG, "getInstanceId failed", task.getException());
- return;
- }
-
- // Get new Instance ID token
- String token = Objects.requireNonNull(task.getResult()).getToken();
-
- // Log and toast
- @SuppressLint({"StringFormatInvalid", "LocalSuppress"}) String msg = getString(R.string.msg_token_fmt, token);
- Log.d(TAG, msg);
- Toast.makeText(MainActivity.this, msg, Toast.LENGTH_SHORT).show();
- });
- // [END retrieve_current_token]
- });
-
- buttonSend.setOnClickListener(v -> {
- TOPIC = "/topics/" + topic; //topic must match with what the receiver subscribed to
- NOTIFICATION_TITLE = "Test values";
- NOTIFICATION_MESSAGE = "von Gregor";
-
- JSONObject notification = new JSONObject();
- JSONObject notifcationBody = new JSONObject();
- try {
- notifcationBody.put("title", NOTIFICATION_TITLE);
- notifcationBody.put("message", NOTIFICATION_MESSAGE);
- notifcationBody.put("level", level.getText().toString());
- notifcationBody.put("delay", delay.getText().toString());
- notifcationBody.put("duration", duration.getText().toString());
-
- notification.put("to", TOPIC);
- notification.put("data", notifcationBody);
- } catch (JSONException e) {
- Log.e(TAG, "onCreate: " + e.getMessage() );
- }
- sendNotification(notification);
- });
- }
-
- private void sendNotification(JSONObject notification) {
- JsonObjectRequest jsonObjectRequest = new JsonObjectRequest(FCM_API, notification,
- response -> {
- Log.i(TAG, "onResponse: " + response.toString());
- //edtTitle.setText("");
- //edtMessage.setText("");
- },
- error -> {
- Toast.makeText(MainActivity.this, "Request error", Toast.LENGTH_LONG).show();
- Log.i(TAG, "onErrorResponse: Didn't work");
- }){
- @Override
- public Map<String, String> getHeaders() {
- Map<String, String> params = new HashMap<>();
- params.put("Authorization", serverKey);
- params.put("Content-Type", contentType);
- return params;
- }
- };
- MySingleton.getInstance(getApplicationContext()).addToRequestQueue(jsonObjectRequest);
- }
-
- }
|