Add google-services.json file
Add file into maifest.xml
1 2 3 4 5 6 7 8 9 10 11 12 13 |
<!-- Firebase Notifications --> <service android:name=".service.MyFirebaseMessagingService"> <intent-filter> <action android:name="com.google.firebase.MESSAGING_EVENT" /> </intent-filter> </service> <service android:name=".service.MyFirebaseInstanceIDService"> <intent-filter> <action android:name="com.google.firebase.INSTANCE_ID_EVENT" /> </intent-filter> </service> <!-- ./Firebase Notifications --> |
Create Files
Config.php
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 |
public class Config { public static final String SHARED_PREF = "TOURING_COMPANIONS"; // global topic to receive app wide push notifications public static final String TOPIC_GLOBAL = "global"; // broadcast receiver intent filters public static final String REGISTRATION_COMPLETE = "registrationComplete"; public static final String PUSH_NOTIFICATION = "pushNotification"; // id to handle the notification in the notification tray public static final int NOTIFICATION_ID = 100; public static final int NOTIFICATION_ID_BIG_IMAGE = 101; } |
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 |
package com.touring.companions.service; import android.content.Intent; import android.content.SharedPreferences; import android.support.v4.content.LocalBroadcastManager; import android.util.Log; import com.google.firebase.iid.FirebaseInstanceId; import com.google.firebase.iid.FirebaseInstanceIdService; import com.touring.companions.utility.Config; public class MyFirebaseInstanceIDService extends FirebaseInstanceIdService { private static final String TAG = MyFirebaseInstanceIDService.class.getSimpleName(); @Override public void onTokenRefresh() { super.onTokenRefresh(); String refreshedToken = FirebaseInstanceId.getInstance().getToken(); // Saving reg id to shared preferences storeRegIdInPref(refreshedToken); // sending reg id to your server sendRegistrationToServer(refreshedToken); // Notify UI that registration has completed, so the progress indicator can be hidden. Intent registrationComplete = new Intent(Config.REGISTRATION_COMPLETE); registrationComplete.putExtra("token", refreshedToken); LocalBroadcastManager.getInstance(this).sendBroadcast(registrationComplete); } private void sendRegistrationToServer(final String token) { // sending gcm token to server Log.e(TAG, "sendRegistrationToServer: " + token); } private void storeRegIdInPref(String token) { SharedPreferences pref = getApplicationContext().getSharedPreferences(Config.SHARED_PREF, 0); SharedPreferences.Editor editor = pref.edit(); editor.putString("regId", token); editor.apply(); } } |
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 |
package com.touring.companions.service; import android.content.Context; import android.content.Intent; import android.database.Cursor; import android.support.v4.content.LocalBroadcastManager; import android.text.TextUtils; import android.util.Log; import android.widget.Toast; import com.google.firebase.messaging.FirebaseMessagingService; import com.google.firebase.messaging.RemoteMessage; import com.touring.companions.utility.Config; import com.touring.companions.activities.MoreInfoNotification; import com.touring.companions.dbhelper.DatabaseHelper; import com.touring.companions.utility.NotificationUtils; import com.touring.companions.utility.SqliteUtil; import org.json.JSONException; import org.json.JSONObject; public class MyFirebaseMessagingService extends FirebaseMessagingService { private static final String TAG = MyFirebaseMessagingService.class.getSimpleName(); private NotificationUtils notificationUtils; @Override public void onMessageReceived(RemoteMessage remoteMessage) { Log.e(TAG, "From: " + remoteMessage.getFrom()); if (remoteMessage == null) return; // Check if message contains a notification payload. if (remoteMessage.getNotification() != null) { Log.e(TAG, "Notification Body: " + remoteMessage.getNotification().getBody()); handleNotification(remoteMessage.getNotification().getBody()); } // Check if message contains a data payload. if (remoteMessage.getData().size() > 0) { Log.e(TAG, "Data Payload: " + remoteMessage.getData().toString()); try { JSONObject json = new JSONObject(remoteMessage.getData().toString()); handleDataMessage(json); } catch (Exception e) { Log.e(TAG, "Exception: " + e.getMessage()); } } } private void handleNotification(String message) { if (!NotificationUtils.isAppIsInBackground(getApplicationContext())) { // app is in foreground, broadcast the push message Intent pushNotification = new Intent(Config.PUSH_NOTIFICATION); pushNotification.putExtra("message", message); LocalBroadcastManager.getInstance(this).sendBroadcast(pushNotification); // play notification sound NotificationUtils notificationUtils = new NotificationUtils(getApplicationContext()); notificationUtils.playNotificationSound(); } else { // If the app is in background, firebase itself handles the notification } } private void handleDataMessage(JSONObject json) { Log.e(TAG, "push json: " + json.toString()); try { JSONObject data = json.getJSONObject("data"); String title = data.getString("title"); String message = data.getString("message"); // boolean isBackground = data.getBoolean("is_background"); String imageUrl = data.getString("image"); String timestamp = data.getString("timestamp"); // JSONObject payload = data.getJSONObject("payload"); Log.e(TAG, "title: " + title); Log.e(TAG, "message: " + message); // Log.e(TAG, "isBackground: " + isBackground); // Log.e(TAG, "payload: " + payload.toString()); Log.e(TAG, "imageUrl: " + imageUrl); // Log.e(TAG, "timestamp: " + timestamp); DatabaseHelper dataBaseHelper = new DatabaseHelper(getApplicationContext()); dataBaseHelper.insertData(title, message, timestamp); Cursor cursor = dataBaseHelper.getData(SqliteUtil.TABLE_NOTIFICATION); int idColumn = cursor.getColumnIndex("id"); int titleColumn = cursor.getColumnIndex("title"); int messageColumn = cursor.getColumnIndex("message"); cursor.moveToFirst(); // Verify that we have results if (cursor != null && (cursor.getCount() > 0)) { do { Log.d(TAG, "id " + cursor.getString(idColumn)); Log.d(TAG, "Title " + cursor.getString(titleColumn)); Log.d(TAG, "Message " + cursor.getString(messageColumn)); // Keep getting results as long as they exist } while (cursor.moveToNext()); } else { Toast.makeText(getApplicationContext(), "No Results to Show", Toast.LENGTH_SHORT).show(); } dataBaseHelper.close(); if (!NotificationUtils.isAppIsInBackground(getApplicationContext())) { // app is in foreground, broadcast the push message Intent pushNotification = new Intent(Config.PUSH_NOTIFICATION); pushNotification.putExtra("message", message); LocalBroadcastManager.getInstance(this).sendBroadcast(pushNotification); // play notification sound NotificationUtils notificationUtils = new NotificationUtils(getApplicationContext()); notificationUtils.playNotificationSound(); } else { // app is in background, show the notification in notification tray Intent resultIntent = new Intent(getApplicationContext(), MoreInfoNotification.class); resultIntent.putExtra("message", message); // check for image attachment if (TextUtils.isEmpty(imageUrl)) { showNotificationMessage(getApplicationContext(), title, message, timestamp, resultIntent); } else { // image is present, show notification with image showNotificationMessageWithBigImage(getApplicationContext(), title, message, timestamp, resultIntent, imageUrl); } } } catch (JSONException e) { Log.e(TAG, "Json Exception: " + e.getMessage()); } catch (Exception e) { Log.e(TAG, "Exception: " + e.getMessage()); } } /** * Showing notification with text only */ private void showNotificationMessage(Context context, String title, String message, String timeStamp, Intent intent) { notificationUtils = new NotificationUtils(context); intent.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK | Intent.FLAG_ACTIVITY_CLEAR_TASK); notificationUtils.showNotificationMessage(title, message, timeStamp, intent); } /** * Showing notification with text and image */ private void showNotificationMessageWithBigImage(Context context, String title, String message, String timeStamp, Intent intent, String imageUrl) { notificationUtils = new NotificationUtils(context); intent.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK | Intent.FLAG_ACTIVITY_CLEAR_TASK); notificationUtils.showNotificationMessage(title, message, timeStamp, intent, imageUrl); } } |
In activity
1 |
private BroadcastReceiver mRegistrationBroadcastReceiver; |
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 |
@Override protected void onResume() { super.onResume(); // register GCM registration complete receiver LocalBroadcastManager.getInstance(this).registerReceiver(mRegistrationBroadcastReceiver, new IntentFilter(Config.REGISTRATION_COMPLETE)); // register new push message receiver // by doing this, the activity will be notified each time a new message arrives LocalBroadcastManager.getInstance(this).registerReceiver(mRegistrationBroadcastReceiver, new IntentFilter(Config.PUSH_NOTIFICATION)); // clear the notification area when the app is opened NotificationUtils.clearNotifications(getApplicationContext()); } @Override protected void onPause() { LocalBroadcastManager.getInstance(this).unregisterReceiver(mRegistrationBroadcastReceiver); super.onPause(); } |
To receive Brodcast
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 |
mRegistrationBroadcastReceiver = new BroadcastReceiver() { @Override public void onReceive(Context context, Intent intent) { Log.d(TAG,"mRegistrationBroadcastReceiver: "); // checking for type intent filter if (intent.getAction().equals(Config.REGISTRATION_COMPLETE)) { // gcm successfully registered // now subscribe to `global` topic to receive app wide notifications FirebaseMessaging.getInstance().subscribeToTopic(Config.TOPIC_GLOBAL); displayFirebaseRegId(); } else if (intent.getAction().equals(Config.PUSH_NOTIFICATION)) { // new push notification is received String message = intent.getStringExtra("message"); Log.d(TAG,"Push notification: " + message); Toast.makeText(getApplicationContext(), "Push notification: " + message, Toast.LENGTH_LONG).show(); // txtMessage.setText(message); } } }; |
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 |
// Fetches reg id from shared preferences // and displays on the screen private void displayFirebaseRegId() { SharedPreferences pref = getApplicationContext().getSharedPreferences(Config.SHARED_PREF, 0); String regId = pref.getString("regId", null); Log.e(TAG, "Firebase reg id: " + regId); if (!TextUtils.isEmpty(regId)) { /* RegisterEmail registerEmail = new RegisterEmail(this); SharedPreferences prefs = getSharedPreferences(Config.MY_PREFS_NAME, Context.MODE_PRIVATE); String email = prefs.getString(SettingUtil.USER_EMAIL, SettingUtil.EMPTY); registerEmail.start(URLHelp.registerEmail(email, regId));*/ // txtRegId.setText("Firebase Reg Id: " + regId); } else { // txtRegId.setText("Firebase Reg Id is not received yet!"); } } |