Skip to content

Commit af4f28f

Browse files
authored
port FCM snippets from quickstart-android (#351)
* add fcm snippets from quickstart-android to MainActivity * add fcm snippets from quickstart-android to MyFirebaseMessagingService
1 parent db50a75 commit af4f28f

File tree

5 files changed

+290
-14
lines changed

5 files changed

+290
-14
lines changed

messaging/app/build.gradle

Lines changed: 1 addition & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -30,6 +30,7 @@ dependencies {
3030
implementation 'com.google.firebase:firebase-analytics:21.0.0'
3131

3232
implementation "com.google.android.gms:play-services-auth:20.2.0"
33+
implementation 'androidx.work:work-runtime-ktx:2.7.1'
3334
}
3435

3536
apply plugin: 'com.google.gms.google-services'

messaging/app/src/main/java/com/google/firebase/example/messaging/MainActivity.java

Lines changed: 52 additions & 14 deletions
Original file line numberDiff line numberDiff line change
@@ -1,27 +1,18 @@
11
package com.google.firebase.example.messaging;
22

3-
import android.accounts.Account;
4-
import android.accounts.AccountManager;
53
import android.annotation.SuppressLint;
64
import android.os.Bundle;
5+
6+
import androidx.annotation.NonNull;
77
import androidx.appcompat.app.AppCompatActivity;
88
import android.util.Log;
9+
import android.widget.Toast;
910

10-
import com.google.android.gms.auth.GoogleAuthUtil;
11+
import com.google.android.gms.tasks.OnCompleteListener;
12+
import com.google.android.gms.tasks.Task;
1113
import com.google.firebase.messaging.FirebaseMessaging;
1214
import com.google.firebase.messaging.RemoteMessage;
1315

14-
import org.json.JSONArray;
15-
import org.json.JSONException;
16-
import org.json.JSONObject;
17-
18-
import java.io.IOException;
19-
import java.io.InputStream;
20-
import java.io.OutputStream;
21-
import java.net.HttpURLConnection;
22-
import java.net.URL;
23-
import java.util.Arrays;
24-
import java.util.Scanner;
2516
import java.util.concurrent.atomic.AtomicInteger;
2617

2718
@SuppressLint("MissingPermission")
@@ -32,6 +23,14 @@ public class MainActivity extends AppCompatActivity {
3223
@Override
3324
protected void onCreate(Bundle savedInstanceState) {
3425
super.onCreate(savedInstanceState);
26+
// [START handle_data_extras]
27+
if (getIntent().getExtras() != null) {
28+
for (String key : getIntent().getExtras().keySet()) {
29+
Object value = getIntent().getExtras().get(key);
30+
Log.d(TAG, "Key: " + key + " Value: " + value);
31+
}
32+
}
33+
// [END handle_data_extras]
3534
}
3635

3736
public void runtimeEnableAutoInit() {
@@ -64,4 +63,43 @@ public void sendUpstream() {
6463
// [END fcm_send_upstream]
6564
}
6665

66+
private void subscribeTopics() {
67+
// [START subscribe_topics]
68+
FirebaseMessaging.getInstance().subscribeToTopic("weather")
69+
.addOnCompleteListener(new OnCompleteListener<Void>() {
70+
@Override
71+
public void onComplete(@NonNull Task<Void> task) {
72+
String msg = "Subscribed";
73+
if (!task.isSuccessful()) {
74+
msg = "Subscribe failed";
75+
}
76+
Log.d(TAG, msg);
77+
Toast.makeText(MainActivity.this, msg, Toast.LENGTH_SHORT).show();
78+
}
79+
});
80+
// [END subscribe_topics]
81+
}
82+
83+
private void logRegToken() {
84+
// [START log_reg_token]
85+
FirebaseMessaging.getInstance().getToken()
86+
.addOnCompleteListener(new OnCompleteListener<String>() {
87+
@Override
88+
public void onComplete(@NonNull Task<String> task) {
89+
if (!task.isSuccessful()) {
90+
Log.w(TAG, "Fetching FCM registration token failed", task.getException());
91+
return;
92+
}
93+
94+
// Get new FCM registration token
95+
String token = task.getResult();
96+
97+
// Log and toast
98+
String msg = "FCM Registration token: " + token;
99+
Log.d(TAG, msg);
100+
Toast.makeText(MainActivity.this, msg, Toast.LENGTH_SHORT).show();
101+
}
102+
});
103+
// [END log_reg_token]
104+
}
67105
}
Lines changed: 100 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,100 @@
1+
package com.google.firebase.example.messaging;
2+
3+
import android.content.Context;
4+
import android.util.Log;
5+
6+
import androidx.annotation.NonNull;
7+
import androidx.work.OneTimeWorkRequest;
8+
import androidx.work.WorkManager;
9+
import androidx.work.Worker;
10+
import androidx.work.WorkerParameters;
11+
12+
import com.google.firebase.messaging.FirebaseMessagingService;
13+
import com.google.firebase.messaging.RemoteMessage;
14+
15+
public class MyFirebaseMessagingService extends FirebaseMessagingService {
16+
17+
private static final String TAG = "MyFirebaseMsgService";
18+
19+
// [START receive_message]
20+
@Override
21+
public void onMessageReceived(RemoteMessage remoteMessage) {
22+
// TODO(developer): Handle FCM messages here.
23+
// Not getting messages here? See why this may be: https://goo.gl/39bRNJ
24+
Log.d(TAG, "From: " + remoteMessage.getFrom());
25+
26+
// Check if message contains a data payload.
27+
if (remoteMessage.getData().size() > 0) {
28+
Log.d(TAG, "Message data payload: " + remoteMessage.getData());
29+
30+
if (/* Check if data needs to be processed by long running job */ true) {
31+
// For long-running tasks (10 seconds or more) use WorkManager.
32+
scheduleJob();
33+
} else {
34+
// Handle message within 10 seconds
35+
handleNow();
36+
}
37+
38+
}
39+
40+
// Check if message contains a notification payload.
41+
if (remoteMessage.getNotification() != null) {
42+
Log.d(TAG, "Message Notification Body: " + remoteMessage.getNotification().getBody());
43+
}
44+
45+
// Also if you intend on generating your own notifications as a result of a received FCM
46+
// message, here is where that should be initiated. See sendNotification method below.
47+
}
48+
// [END receive_message]
49+
50+
// [START on_new_token]
51+
/**
52+
* There are two scenarios when onNewToken is called:
53+
* 1) When a new token is generated on initial app startup
54+
* 2) Whenever an existing token is changed
55+
* Under #2, there are three scenarios when the existing token is changed:
56+
* A) App is restored to a new device
57+
* B) User uninstalls/reinstalls the app
58+
* C) User clears app data
59+
*/
60+
@Override
61+
public void onNewToken(@NonNull String token) {
62+
Log.d(TAG, "Refreshed token: " + token);
63+
64+
// If you want to send messages to this application instance or
65+
// manage this apps subscriptions on the server side, send the
66+
// FCM registration token to your app server.
67+
sendRegistrationToServer(token);
68+
}
69+
// [END on_new_token]
70+
71+
private void scheduleJob() {
72+
// [START dispatch_job]
73+
OneTimeWorkRequest work = new OneTimeWorkRequest.Builder(MyWorker.class)
74+
.build();
75+
WorkManager.getInstance(this).beginWith(work).enqueue();
76+
// [END dispatch_job]
77+
}
78+
79+
private void handleNow() {
80+
Log.d(TAG, "Short lived task is done.");
81+
}
82+
83+
private void sendRegistrationToServer(String token) {
84+
// TODO: Implement this method to send token to your app server.
85+
}
86+
87+
public static class MyWorker extends Worker {
88+
89+
public MyWorker(@NonNull Context context, @NonNull WorkerParameters workerParams) {
90+
super(context, workerParams);
91+
}
92+
93+
@NonNull
94+
@Override
95+
public Result doWork() {
96+
// TODO(developer): add long running task here.
97+
return Result.success();
98+
}
99+
}
100+
}

messaging/app/src/main/java/com/google/firebase/example/messaging/kotlin/MainActivity.kt

Lines changed: 49 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -1,5 +1,8 @@
11
package com.google.firebase.example.messaging.kotlin
22

3+
import android.os.Bundle
4+
import android.util.Log
5+
import android.widget.Toast
36
import androidx.appcompat.app.AppCompatActivity
47
import com.google.firebase.ktx.Firebase
58
import com.google.firebase.messaging.ktx.messaging
@@ -12,6 +15,18 @@ class MainActivity : AppCompatActivity() {
1215
private const val TAG = "MainActivity"
1316
}
1417

18+
override fun onCreate(savedInstanceState: Bundle?) {
19+
super.onCreate(savedInstanceState)
20+
// [START handle_data_extras]
21+
intent.extras?.let {
22+
for (key in it.keySet()) {
23+
val value = intent.extras?.get(key)
24+
Log.d(TAG, "Key: $key Value: $value")
25+
}
26+
}
27+
// [END handle_data_extras]
28+
}
29+
1530
fun runtimeEnableAutoInit() {
1631
// [START fcm_runtime_enable_auto_init]
1732
Firebase.messaging.isAutoInitEnabled = true
@@ -41,4 +56,38 @@ class MainActivity : AppCompatActivity() {
4156
})
4257
// [END fcm_send_upstream]
4358
}
59+
60+
fun subscribeTopics() {
61+
// [START subscribe_topics]
62+
Firebase.messaging.subscribeToTopic("weather")
63+
.addOnCompleteListener { task ->
64+
var msg = "Subscribed"
65+
if (!task.isSuccessful) {
66+
msg = "Subscribe failed"
67+
}
68+
Log.d(TAG, msg)
69+
Toast.makeText(baseContext, msg, Toast.LENGTH_SHORT).show()
70+
}
71+
// [END subscribe_topics]
72+
}
73+
74+
fun logRegToken() {
75+
// [START log_reg_token]
76+
Firebase.messaging.getToken().addOnCompleteListener { task ->
77+
if (!task.isSuccessful) {
78+
Log.w(TAG, "Fetching FCM registration token failed", task.exception)
79+
return@addOnCompleteListener
80+
}
81+
82+
// Get new FCM registration token
83+
val token = task.result
84+
85+
// Log and toast
86+
val msg = "FCM Registration token: $token"
87+
Log.d(TAG, msg)
88+
Toast.makeText(baseContext, msg, Toast.LENGTH_SHORT).show()
89+
}
90+
// [END log_reg_token]
91+
}
92+
4493
}
Lines changed: 88 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,88 @@
1+
package com.google.firebase.example.messaging.kotlin
2+
3+
import android.content.Context
4+
import android.util.Log
5+
import androidx.work.OneTimeWorkRequest
6+
import androidx.work.WorkManager
7+
import androidx.work.Worker
8+
import androidx.work.WorkerParameters
9+
import com.google.firebase.messaging.FirebaseMessagingService
10+
import com.google.firebase.messaging.RemoteMessage
11+
12+
class MyFirebaseMessagingService : FirebaseMessagingService() {
13+
14+
// [START receive_message]
15+
override fun onMessageReceived(remoteMessage: RemoteMessage) {
16+
// TODO(developer): Handle FCM messages here.
17+
// Not getting messages here? See why this may be: https://goo.gl/39bRNJ
18+
Log.d(TAG, "From: ${remoteMessage.from}")
19+
20+
// Check if message contains a data payload.
21+
if (remoteMessage.data.isNotEmpty()) {
22+
Log.d(TAG, "Message data payload: ${remoteMessage.data}")
23+
24+
if (/* Check if data needs to be processed by long running job */ true) {
25+
// For long-running tasks (10 seconds or more) use WorkManager.
26+
scheduleJob()
27+
} else {
28+
// Handle message within 10 seconds
29+
handleNow()
30+
}
31+
}
32+
33+
// Check if message contains a notification payload.
34+
remoteMessage.notification?.let {
35+
Log.d(TAG, "Message Notification Body: ${it.body}")
36+
}
37+
38+
// Also if you intend on generating your own notifications as a result of a received FCM
39+
// message, here is where that should be initiated. See sendNotification method below.
40+
}
41+
// [END receive_message]
42+
43+
// [START on_new_token]
44+
/**
45+
* Called if the FCM registration token is updated. This may occur if the security of
46+
* the previous token had been compromised. Note that this is called when the
47+
* FCM registration token is initially generated so this is where you would retrieve the token.
48+
*/
49+
override fun onNewToken(token: String) {
50+
Log.d(TAG, "Refreshed token: $token")
51+
52+
// If you want to send messages to this application instance or
53+
// manage this apps subscriptions on the server side, send the
54+
// FCM registration token to your app server.
55+
sendRegistrationToServer(token)
56+
}
57+
// [END on_new_token]
58+
59+
private fun scheduleJob() {
60+
// [START dispatch_job]
61+
val work = OneTimeWorkRequest.Builder(MyWorker::class.java)
62+
.build()
63+
WorkManager.getInstance(this)
64+
.beginWith(work)
65+
.enqueue()
66+
// [END dispatch_job]
67+
}
68+
69+
private fun handleNow() {
70+
Log.d(TAG, "Short lived task is done.")
71+
}
72+
73+
private fun sendRegistrationToServer(token: String?) {
74+
// TODO: Implement this method to send token to your app server.
75+
Log.d(TAG, "sendRegistrationTokenToServer($token)")
76+
}
77+
78+
companion object {
79+
private const val TAG = "MyFirebaseMsgService"
80+
}
81+
82+
internal class MyWorker(appContext: Context, workerParams: WorkerParameters) : Worker(appContext, workerParams) {
83+
override fun doWork(): Result {
84+
// TODO(developer): add long running task here.
85+
return Result.success()
86+
}
87+
}
88+
}

0 commit comments

Comments
 (0)