Skip to content

Instantly share code, notes, and snippets.

@supertopoz
Last active March 30, 2021 05:42
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save supertopoz/24ea4870e37d04fc5d77059af8379d51 to your computer and use it in GitHub Desktop.
Save supertopoz/24ea4870e37d04fc5d77059af8379d51 to your computer and use it in GitHub Desktop.
package com.simple.android_push_replies_only.fcm;
import android.app.Notification;
import android.app.NotificationChannel;
import android.app.NotificationManager;
import android.app.PendingIntent;
import android.content.Context;
import android.content.Intent;
import android.os.Build;
import android.util.Log;
import com.google.firebase.messaging.RemoteMessage;
import com.sendbird.android.SendBirdPushHandler;
import com.sendbird.android.SendBirdPushHelper;
import com.simple.android_push_replies_only.R;
import com.simple.android_push_replies_only.utils.RegisterSendbirdDeviceToken;
import org.json.JSONException;
import org.json.JSONObject;
import androidx.core.app.NotificationCompat;
import androidx.core.app.RemoteInput;
public class MyFirebaseMessagingService extends SendBirdPushHandler {
private static final String TAG = "ALWAYS PUSH" ;
//ALWAYS PUSH
@Override
protected boolean alwaysReceiveMessage() { return true; }
@Override
public void onNewToken(String token) {
RegisterSendbirdDeviceToken.sendToken(token);
}
/**
* Called when message is received.
*
* @param remoteMessage Object representing the message received from Firebase Cloud Messaging.
*/
// [START receive_message]
@Override
public void onMessageReceived(Context context, RemoteMessage remoteMessage) {
//ALWAYS PUSH - Check if message already arrived via Web-socket
Boolean arrivedWhenConnected = SendBirdPushHelper.isDuplicateMessage(remoteMessage);
Log.d(TAG, "Message already arrived via SDK?: " + arrivedWhenConnected);
String channelUrl = null;
try {
if (remoteMessage.getData().containsKey("sendbird")) {
JSONObject sendBird = new JSONObject(remoteMessage.getData().get("sendbird"));
JSONObject channel = (JSONObject) sendBird.get("channel");
channelUrl = (String) channel.get("channel_url");
//ALWAYS PUSH GET MessageId
long messageId = sendBird.getLong("message_id");
sendNotification(context, remoteMessage.getData().get("message"), channelUrl, messageId);
}
} catch (JSONException e) {
e.printStackTrace();
}
}
// [END receive_message]
/**
* Create and show a simple notification containing the received FCM message.
*
* @param messageBody FCM message body received.
* @param messageId
*/
public static void sendNotification(Context context, String messageBody, String channelUrl, long messageId) {
NotificationManager notificationManager = (NotificationManager) context.getSystemService(Context.NOTIFICATION_SERVICE);
final String CHANNEL_ID = "CHANNEL_ID";
if (Build.VERSION.SDK_INT >= 26) { // Build.VERSION_CODES.O
NotificationChannel mChannel = new NotificationChannel(CHANNEL_ID, "CHANNEL_NAME", NotificationManager.IMPORTANCE_HIGH);
notificationManager.createNotificationChannel(mChannel);
}
if (Build.VERSION.SDK_INT < Build.VERSION_CODES.KITKAT_WATCH) { return; }
//ALWAYS PUSH ---> Build Push Notification context UI
Log.d("ALWAYS PUSH:", "Build reply");
RemoteInput remoteInput = new RemoteInput.Builder(NotificationReceiver.KEY_TEXT)
.setLabel("Reply")
.build();
Intent replyIntent = new Intent(context, NotificationReceiver.class);
replyIntent.putExtra(NotificationReceiver.KEY_MSG_ID, messageId);
replyIntent.putExtra(NotificationReceiver.KEY_CHANNEL_URL, channelUrl);
PendingIntent replyPendingIntent = PendingIntent.getBroadcast(context.getApplicationContext(),
(int) messageId,
replyIntent,
PendingIntent.FLAG_UPDATE_CURRENT);
NotificationCompat.Action action =
new NotificationCompat.Action.Builder(R.drawable.ic_play,
"reply", replyPendingIntent)
.addRemoteInput(remoteInput)
.build();
NotificationCompat.Builder notificationBuilder = new NotificationCompat.Builder(context, CHANNEL_ID)
.setContentTitle(context.getResources().getString(R.string.app_name))
.setPriority(Notification.PRIORITY_MAX)
.setDefaults(Notification.DEFAULT_ALL)
//ALWAYS REPLY - Add Action
.addAction(action);
notificationBuilder.setContentText(messageBody);
notificationManager.notify(0 /* ID of notification */, notificationBuilder.build());
}
}
package com.simple.android_push_replies_only.fcm;
import android.app.Notification;
import android.app.RemoteInput;
import android.content.BroadcastReceiver;
import android.content.Context;
import android.content.Intent;
import android.os.Bundle;
import android.util.Log;
import com.sendbird.android.GroupChannel;
import com.sendbird.android.SendBird;
import com.sendbird.android.SendBirdException;
import com.sendbird.android.UserMessageParams;
import java.util.Timer;
import java.util.TimerTask;
import androidx.core.app.NotificationCompat;
import androidx.core.app.NotificationManagerCompat;
public class NotificationReceiver extends BroadcastReceiver {
public static final String KEY_TEXT = "KEY_TEXT";
public static final String KEY_MSG_ID = "KEY_MSG_ID";
public static final String KEY_CHANNEL_URL = "KEY_CHANNEL_URL";
private static final String USER_ID = "YOUR_USER_ID";
//ALWAYS PUSH
@Override
public void onReceive(final Context context, final Intent intent) {
if (android.os.Build.VERSION.SDK_INT >= android.os.Build.VERSION_CODES.KITKAT_WATCH) {
final PendingResult pendingResult = goAsync();
final Thread replyThread = new Thread(() -> {
Log.d("ALWAYS PUSH", "Prepare to log into Sendbird");
final Bundle remoteInput = RemoteInput.getResultsFromIntent(intent);
Log.d("ALWAYS PUSH", remoteInput.getString(KEY_TEXT));
if (null == remoteInput) return;
final long messageId = intent.getLongExtra(KEY_MSG_ID, 0L);
final String channelUrl = intent.getStringExtra(KEY_CHANNEL_URL);
final String userInput = remoteInput.getString(KEY_TEXT);
// Connect to Sendbird
SendBird.connect(USER_ID, (user, connectionException) -> {
Log.d("ALWAYS PUSH", "Connected to Sendbird in Push context");
if (null != connectionException) {
onDone(pendingResult);
}
GroupChannel.getChannel(channelUrl, (groupChannel, e) -> {
onChannelFound(context, pendingResult, groupChannel, e, userInput, messageId);
});
});
});
replyThread.start();
}
}
private static void onChannelFound(final Context context,
final PendingResult pendingResult,
final GroupChannel groupChannel,
final SendBirdException e,
final String userInput,
final long messageId) {
if (null != e || null == groupChannel) {
onDone(pendingResult);
return;
}
final UserMessageParams params = new UserMessageParams();
params.setMessage(userInput);
params.setParentMessageId(messageId);
// send message
groupChannel.sendUserMessage(params, (userMessage, e1) -> {
onMessageSent(context, pendingResult, messageId);
});
}
private static void onMessageSent(final Context context,
final PendingResult pendingResult,
final long messageId) {
final Notification repliedNotification = new NotificationCompat.Builder(context,
"CHANNEL_ID")
.setContentText("Reply sent")
.build();
NotificationManagerCompat.from(context).notify((int) messageId,
repliedNotification);
// disconnect
onDone(pendingResult);
}
private static void onDone(final PendingResult pendingResult) {
Log.d("ALWAYS PUSH", "Message sent but still connected to Sendbird");
new Timer().schedule(
new TimerTask(){
@Override
public void run(){
Log.d("ALWAYS PUSH", "Disconnected from Sendbird");
SendBird.disconnect(null);
//if you need some code to run when the delay expires
}
}, 10000);
pendingResult.finish();
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment