As the title says i want to use the FCM to send a payload and load a bitmap to use it in the Notification Big picture. I tried this method (Code is below) to get the image, but it didn't worked. Any help is much appreciated
Thank you
String imageUrl;
/**
* Called when message is received.
*
* #param remoteMessage Object representing the message received from Firebase Cloud Messaging.
*/
// [START receive_message]
#Override
public void onMessageReceived(RemoteMessage remoteMessage) {
// TODO(developer): Handle FCM messages here.
// If the application is in the foreground handle both data and notification messages here.
// Also if you intend on generating your own notifications as a result of a received FCM
// message, here is where that should be initiated. See sendNotification method below.
Intent intent = new Intent(this, MainActivity.class);
intent.addFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP);
PendingIntent pendingIntent = PendingIntent.getActivity(this, 0 /* Request code */, intent,
PendingIntent.FLAG_ONE_SHOT);
if (remoteMessage.getData().size() > 0) {
imageUrl = remoteMessage.getData().toString();
}
Uri defaultSoundUri = RingtoneManager.getDefaultUri(RingtoneManager.TYPE_NOTIFICATION);
Notification.Builder notificationBuilder = new Notification.Builder(this)
.setSmallIcon(R.drawable.ic_launcher)
.setContentTitle("Glaze")
.setContentText(remoteMessage.getNotification().getBody())
.setAutoCancel(true)
.setSound(defaultSoundUri)
.setLargeIcon(getBitmap(imageUrl))
.setStyle(new Notification.BigPictureStyle().bigPicture(getBitmap(imageUrl)))
.setContentIntent(pendingIntent);
NotificationManager notificationManager =
(NotificationManager) getSystemService(Context.NOTIFICATION_SERVICE);
notificationManager.notify(0 /* ID of notification */, notificationBuilder.build());
Log.d(TAG, "From: " + remoteMessage.getFrom());
Log.d(TAG, "Notification Message Body: " + remoteMessage.getNotification().getBody());
}
// [END receive_message]
public static Bitmap getBitmap(String src) {
try {
URL url = new URL(src);
HttpURLConnection connection = (HttpURLConnection) url.openConnection();
connection.setDoInput(true);
connection.connect();
InputStream input = connection.getInputStream();
Bitmap myBitmap = BitmapFactory.decodeStream(input);
return myBitmap;
} catch (IOException e) {
e.printStackTrace();
return null;
}
}
You need to use NotificationCompat.BigPictureStyle for a big picture layout. Also you'll have to post the notification after you load the bitmap from the url.
Related
I'm using Firebase cloudmessaging for my Android application notifications, So my issue is when I send a notification if the user dismisses the notification the next notification that I send if clicked is opening the the first notification that have been dismissed so even if I send the third notification and the user dismissed both first and second notifications, if clicked the third one it's going to open the first notification. I'm using Firebase cloud messaging with data and sending the (title, excerpt, image, link). in the notification bar everything is cool and correct but when clicked the link is changed and the webview is going to open the first notification.
public class MyFirebaseMessagingService extends FirebaseMessagingService {
private static final String TAG = "MyFirebaseMsgService";
// [START receive_message]
#Override
public void onMessageReceived(RemoteMessage remoteMessage) {
Log.d(TAG, "From: " + remoteMessage.getFrom());
// Check if message contains a data payload.
if (remoteMessage.getData().size() > 0) {
Log.d(TAG, "Message data payload: " + remoteMessage.getData());
sendNotification(remoteMessage.getData().get("title"), remoteMessage.getData().get("body"),
Integer.parseInt(remoteMessage.getData().get("topic")), remoteMessage.getData().get("link"), remoteMessage.getData().get("imageUrl"), Integer.parseInt(remoteMessage.getData().get("id")));
if (/* Check if data needs to be processed by long running job */ true) {
// For long-running tasks (10 seconds or more) use Firebase Job Dispatcher.
scheduleJob();
} else {
// Handle message within 10 seconds
handleNow();
}
}
// Check if message contains a notification payload.
if (remoteMessage.getNotification() != null) {
Log.d(TAG, "Message Notification Body: " + remoteMessage.getNotification().getBody());
sendNotification(remoteMessage.getNotification().getTitle(), remoteMessage.getNotification().getBody(),
0, " ", " ", 0);
}
}
// [END receive_message]
/**
* Schedule a job using FirebaseJobDispatcher.
*/
private void scheduleJob() {
// [START dispatch_job]
FirebaseJobDispatcher dispatcher = new FirebaseJobDispatcher(new GooglePlayDriver(this));
Job myJob = dispatcher.newJobBuilder()
.setService(MyJobService.class)
.setTag("my-job-tag")
.build();
dispatcher.schedule(myJob);
// [END dispatch_job]
}
/**
* Handle time allotted to BroadcastReceivers.
*/
private void handleNow() {
Log.d(TAG, "Short lived task is done.");
}
/**
* Create and show a simple notification containing the received FCM message.
*
* #param messageBody FCM message body received.
*/
#TargetApi(Build.VERSION_CODES.O)
private void sendNotification(String messageTitle, String messageBody, int topic, String link, String imageUrl, int id) {
PendingIntent pendingIntent;
if (topic == 1){
Intent intent = new Intent(this, WebActivity.class);
// Create the TaskStackBuilder and add the intent, which inflates the back stack
TaskStackBuilder stackBuilder = TaskStackBuilder.create(this);
stackBuilder.addNextIntentWithParentStack(intent);
intent.addFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP);
intent.putExtra("link", link);
intent.putExtra("title", messageTitle);
// Get the PendingIntent containing the entire back stack
pendingIntent =
stackBuilder.getPendingIntent(0, PendingIntent.FLAG_ONE_SHOT);
}else{
Intent intent = new Intent(this, MainActivity.class);
intent.addFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP);
intent.putExtra("link", link);
intent.putExtra("topic", topic);
pendingIntent = PendingIntent.getActivity(this, 0 /* Request code */, intent,
PendingIntent.FLAG_ONE_SHOT);
}
String channelId = getString(R.string.default_notification_channel_id);
InputStream in;
Bitmap myBitmap = null;
try {
URL url = new URL(imageUrl);
HttpURLConnection connection = (HttpURLConnection) url.openConnection();
connection.setDoInput(true);
connection.connect();
in = connection.getInputStream();
myBitmap = BitmapFactory.decodeStream(in);
} catch (MalformedURLException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
NotificationCompat.Builder notificationBuilder =
new NotificationCompat.Builder(this, channelId)
.setPriority(NotificationManager.IMPORTANCE_DEFAULT)
.setChannelId(channelId)
.setSmallIcon(R.drawable.ic_stat_name)
.setLargeIcon(myBitmap)
.setContentTitle(messageTitle)
.setContentText(messageBody)
.setColor(ContextCompat.getColor(getApplicationContext(), R.color.colorAccent))
.setAutoCancel(true)
.setStyle(new NotificationCompat.BigTextStyle().bigText(messageTitle))
.setStyle(new NotificationCompat.BigPictureStyle().bigPicture(myBitmap))
.setGroupSummary(true)
.setGroup(String.valueOf(topic))
.setContentIntent(pendingIntent);
NotificationManager notificationManager =
(NotificationManager) getSystemService(Context.NOTIFICATION_SERVICE);
// Since android Oreo notification channel is needed.
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.O) {
CharSequence name = getString(R.string.channel_name);
String description = "The Channel";
int importance = NotificationManager.IMPORTANCE_DEFAULT;
NotificationChannel channel = new NotificationChannel(channelId, name, importance);
channel.setDescription(description);
channel.setShowBadge(true);
// Register the channel with the system; you can't change the importance
// or other notification behaviors after this
notificationManager = getSystemService(NotificationManager.class);
notificationManager.createNotificationChannel(channel);
notificationManager.createNotificationChannelGroup(new NotificationChannelGroup(String.valueOf(topic), "Articles"));
}
notificationManager.notify(id /* ID of notification */, notificationBuilder.build());
}
}
The expected result is if the user dismissed the first notification, And for the second notification if clicked, the webview opens the second information send from the notification.
So after alot of research I found out that I have to update my intent with PendingIntent.FLAG_UPDATE_CURRENT and changed the request code for the intent every time a new intent is created, that's the new code for any one had this issue in the future:
PendingIntent pendingIntent;
if (topic == 1){
Intent intent = new Intent(this, WebActivity.class);
// Create the TaskStackBuilder and add the intent, which inflates the back stack
TaskStackBuilder stackBuilder = TaskStackBuilder.create(this);
stackBuilder.addNextIntentWithParentStack(intent);
intent.putExtra("link", link);
intent.putExtra("title", messageTitle);
intent.setAction("actionstring" + System.currentTimeMillis());
// Get the PendingIntent containing the entire back stack
pendingIntent =
stackBuilder.getPendingIntent(id, PendingIntent.FLAG_UPDATE_CURRENT);
}else{
Intent intent = new Intent(this, MainActivity.class);
intent.addFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP);
intent.putExtra("link", link);
intent.putExtra("topic", topic);
pendingIntent = PendingIntent.getActivity(this, 0 /* Request code */, intent,
PendingIntent.FLAG_ONE_SHOT);
}
I am newbie to android and learning new things,I am working on FCM push notification,I want to implement Big picture style push notifications,I have implemented it successfully,even i am getting notification along with message but i am facing a problem that in push notification image is not loading,can anyone help me to figure it out?
my service is as below.
MyFirebaseMessagingServiceTemp extends FirebaseMessagingService {
String store_id, img_url, msg;
private static final String TAG = "FirebaseMessageService";
Bitmap bitmap;
/**
* Called when message is received.
*
* #param remoteMessage Object representing the message received from Firebase Cloud Messaging.
*/
#Override
public void onMessageReceived(RemoteMessage remoteMessage) {
/*
There are two types of messages data messages and notification messages. Data messages are handled
here in onMessageReceived whether the app is in the foreground or background. Data messages are the type
traditionally used with GCM. Notification messages are only received here in onMessageReceived when the app
is in the foreground. When the app is in the background an automatically generated notification is displayed.
When the user taps on the notification they are returned to the app. Messages containing both notification
and data payloads are treated as notification messages. The Firebase console always sends notification
messages. For more see: https://firebase.google.com/docs/cloud-messaging/concept-options
*/
Log.d(TAG, "From: " + remoteMessage.getFrom());
// Check if message contains a data payload.
if (remoteMessage.getData().size() > 0) {
Log.d(TAG, "Message data payload: " + remoteMessage.getData());
JSONObject job = new JSONObject(remoteMessage.getData());
img_url = job.optString("img_url");
}
// Check if message contains a notification payload.
if (remoteMessage.getNotification() != null) {
Log.d(TAG, "Message Notification Body: " + remoteMessage.getNotification().getBody());
msg = remoteMessage.getNotification().getBody().toString();
}
//The message which i send will have keys named [message, image, AnotherActivity] and corresponding values.
//You can change as per the requirement.
//message will contain the Push Message
// String message = remoteMessage.getData().get("message");
//imageUri will contain URL of the image to be displayed with Notification
// String imageUri = remoteMessage.getData().get("img_url");
//If the key AnotherActivity has value as True then when the user taps on notification, in the app AnotherActivity will be opened.
//If the key AnotherActivity has value as False then when the user taps on notification, in the app MainActivity will be opened.
String TrueOrFlase = remoteMessage.getData().get("AnotherActivity");
//To get a Bitmap image from the URL received
bitmap = getBitmapfromUrl(img_url);
sendNotification(msg, bitmap);
}
/**
* Create and show a simple notification containing the received FCM message.
*/
private void sendNotification(String messageBody, Bitmap image) {
Intent intent = new Intent(this, SlashActivity.class);
intent.addFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP);
// intent.putExtra("AnotherActivity", TrueOrFalse);
PendingIntent pendingIntent = PendingIntent.getActivity(this, 0 /* Request code */, intent,
PendingIntent.FLAG_ONE_SHOT);
Log.d("====message body===>", messageBody);
Uri defaultSoundUri = RingtoneManager.getDefaultUri(RingtoneManager.TYPE_NOTIFICATION);
NotificationCompat.Builder notificationBuilder = new NotificationCompat.Builder(this)
.setLargeIcon(image)/*Notification icon image*/
.setSmallIcon(R.drawable.ic_launcher)
.setContentTitle(getResources().getString(R.string.app_name))
.setContentText(messageBody)
.setStyle(new NotificationCompat.BigPictureStyle()
.bigPicture(image))/*Notification with Image*/
.setAutoCancel(true)
.setSound(defaultSoundUri)
.setContentIntent(pendingIntent);
NotificationManager notificationManager =
(NotificationManager) getSystemService(Context.NOTIFICATION_SERVICE);
notificationManager.notify(0 /* ID of notification */, notificationBuilder.build());
}
/*
*To get a Bitmap image from the URL received
* */
public Bitmap getBitmapfromUrl(String imageUrl) {
try {
URL url = new URL(imageUrl);
HttpURLConnection connection = (HttpURLConnection) url.openConnection();
connection.setDoInput(true);
connection.connect();
InputStream input = connection.getInputStream();
Bitmap bitmap = BitmapFactory.decodeStream(input);
return bitmap;
} catch (Exception e) {
// TODO Auto-generated catch block
e.printStackTrace();
return null;
}
}
}
I have tried to notify a notification with ringtone. I tried many code but its doesn't work .
i want to play a default ringtone when i send a notification .
notification is proper sent by me ..
but there is no sound in mobile .
My Code is
public class MyFirebaseMessagingService extends FirebaseMessagingService {
private static final String TAG = "FCMPlugin";
/**
* Called when message is received.
*
* #param remoteMessage Object representing the message received from Firebase Cloud Messaging.
*/
// [START receive_message]
#Override
public void onMessageReceived(RemoteMessage remoteMessage) {
// TODO(developer): Handle FCM messages here.
// If the application is in the foreground handle both data and notification messages here.
// Also if you intend on generating your own notifications as a result of a received FCM
// message, here is where that should be initiated. See sendNotification method below.
Log.d(TAG, "==> MyFirebaseMessagingService onMessageReceived");
if( remoteMessage.getNotification() != null){
Log.d(TAG, "\tNotification Title: " + remoteMessage.getNotification().getTitle());
Log.d(TAG, "\tNotification Message: " + remoteMessage.getNotification().getBody());
}
Map<String, Object> data = new HashMap<String, Object>();
data.put("wasTapped", false);
for (String key : remoteMessage.getData().keySet()) {
Object value = remoteMessage.getData().get(key);
Log.d(TAG, "\tKey: " + key + " Value: " + value);
data.put(key, value);
}
Log.d(TAG, "\tNotification Data: " + data.toString());
FCMPlugin.sendPushPayload( data );
//sendNotification(remoteMessage.getNotification().getTitle(), remoteMessage.getNotification().getBody(), remoteMessage.getData());
}
// [END receive_message]
/**
* Create and show a simple notification containing the received FCM message.
*
* #param messageBody FCM message body received.
*/
private void sendNotification(String title, String messageBody, Map<String, Object> data) {
Intent intent = new Intent(this, FCMPluginActivity.class);
intent.addFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP);
for (String key : data.keySet()) {
intent.putExtra(key, data.get(key).toString());
}
PendingIntent pendingIntent = PendingIntent.getActivity(this, 0 /* Request code */, intent,
PendingIntent.FLAG_ONE_SHOT);
Uri defaultSoundUri= RingtoneManager.getDefaultUri(RingtoneManager.TYPE_NOTIFICATION);
NotificationCompat.Builder notificationBuilder = new NotificationCompat.Builder(this)
.setSmallIcon(getApplicationInfo().icon)
.setContentTitle(title)
.setContentText(messageBody)
.setAutoCancel(true)
.setSound(defaultSoundUri)
.setContentIntent(pendingIntent);
NotificationManager notificationManager =
(NotificationManager) getSystemService(Context.NOTIFICATION_SERVICE);
notificationManager.notify(0 /* ID of notification */, notificationBuilder.build());
}
}
If you are trying this on an emulator it would not work because, if I'm not mistaken, it does not have a default ringtone set at:
content://settings/system/ringtone
Have you tried testing
Uri defaultSoundUri= RingtoneManager.getDefaultUri(RingtoneManager.TYPE_NOTIFICATION);
NotificationCompat.Builder notificationBuilder = new NotificationCompat.Builder(this)
.setSmallIcon(getApplicationInfo().icon)
.setContentTitle(title)
.setContentText(messageBody)
.setAutoCancel(true)
.setSound(defaultSoundUri)
.setContentIntent(pendingIntent);
On an actual device?
Check Whether your app is in the background. If the app is in the background the onMessageReceived function is not called hence no ringtone.
This question already has an answer here:
Send URL in push notification Firebase
(1 answer)
Closed 6 years ago.
My application is currently receiving Text , Image and both as a push notification from Firebase console. I want to send URL too as a notification from my Firebase console to the app user.On clicking the notification user shall be redirected to the specific url i.e. www.facebook.com .How can i do this in following code?
Kindly see the image thats what i want
Image From firebase notification console
public class MyFirebaseMessagingService extends FirebaseMessagingService {
private static final String TAG = "FirebaseMessageService";
Bitmap bitmap;
/**
* Called when message is received.
*
* #param remoteMessage Object representing the message received from Firebase Cloud Messaging.
*/
#Override
public void onMessageReceived(RemoteMessage remoteMessage) {
// There are two types of messages data messages and notification messages. Data messages are handled
// here in onMessageReceived whether the app is in the foreground or background. Data messages are the type
// traditionally used with GCM. Notification messages are only received here in onMessageReceived when the app
// is in the foreground. When the app is in the background an automatically generated notification is displayed.
// When the user taps on the notification they are returned to the app. Messages containing both notification
// and data payloads are treated as notification messages. The Firebase console always sends notification
// messages. For more see: https://firebase.google.com/docs/cloud-messaging/concept-options
//
Log.d(TAG, "From: " + remoteMessage.getFrom());
// Check if message contains a data payload.
if (remoteMessage.getData().size() > 0) {
Log.d(TAG, "Message data payload: " + remoteMessage.getData());
}
// Check if message contains a notification payload.
if (remoteMessage.getNotification() != null) {
Log.d(TAG, "Message Notification Body: " + remoteMessage.getNotification().getBody());
}
//The message which i send will have keys named [message, image, AnotherActivity] and corresponding values.
//You can change as per the requirement.
//message will contain the Push Message
String message = remoteMessage.getData().get("message");
//imageUri will contain URL of the image to be displayed with Notification
String imageUri = remoteMessage.getData().get("image");
//If the key AnotherActivity has value as True then when the user taps on notification, in the app AnotherActivity will be opened.
//If the key AnotherActivity has value as False then when the user taps on notification, in the app MainActivity will be opened.
String TrueOrFlase = remoteMessage.getData().get("AnotherActivity");
//To get a Bitmap image from the URL received
bitmap = getBitmapfromUrl(imageUri);
sendNotification(message, bitmap, TrueOrFlase);
}
/**
* Create and show a simple notification containing the received FCM message.
*/
private void sendNotification(String messageBody, Bitmap image, String TrueOrFalse) {
Intent intent = new Intent(this, MainActivity.class);
intent.addFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP);
intent.putExtra("AnotherActivity", TrueOrFalse);
PendingIntent pendingIntent = PendingIntent.getActivity(this, 0 /* Request code */, intent,
PendingIntent.FLAG_ONE_SHOT);
Uri defaultSoundUri = RingtoneManager.getDefaultUri(RingtoneManager.TYPE_NOTIFICATION);
NotificationCompat.Builder notificationBuilder = new NotificationCompat.Builder(this)
.setLargeIcon(image)/*Notification icon image*/
.setSmallIcon(R.drawable.firebase_icon)
.setContentTitle(messageBody)
.setStyle(new NotificationCompat.BigPictureStyle()
.bigPicture(image))/*Notification with Image*/
.setAutoCancel(true)
.setSound(defaultSoundUri)
.setContentIntent(pendingIntent);
NotificationManager notificationManager =
(NotificationManager) getSystemService(Context.NOTIFICATION_SERVICE);
notificationManager.notify(0 /* ID of notification */, notificationBuilder.build());
}
/*
*To get a Bitmap image from the URL received
* */
public Bitmap getBitmapfromUrl(String imageUrl) {
try {
URL url = new URL(imageUrl);
HttpURLConnection connection = (HttpURLConnection) url.openConnection();
connection.setDoInput(true);
connection.connect();
InputStream input = connection.getInputStream();
Bitmap bitmap = BitmapFactory.decodeStream(input);
return bitmap;
} catch (Exception e) {
// TODO Auto-generated catch block
e.printStackTrace();
return null;
}
}
}
This is the code that i have implemented in my app for pushing link with data
public class MyFirebaseMessagingService extends FirebaseMessagingService {
Bitmap bitmap;
#Override
public void onMessageReceived(RemoteMessage remoteMessage) {
String message = remoteMessage.getData().get("message");
//imageUri will contain URL of the image to be displayed with Notification
String imageUri = remoteMessage.getData().get("image");
String link=remoteMessage.getData().get("link");
//To get a Bitmap image from the URL received
bitmap = getBitmapfromUrl(imageUri);
sendNotification(message, bitmap,link);
}
/**
* Create and show a simple notification containing the received FCM message.
*/
private void sendNotification(String messageBody, Bitmap image, String link) {
Intent intent = new Intent(this, MainActivity.class);
intent.addFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP);
intent.putExtra("LINK",link);
PendingIntent pendingIntent = PendingIntent.getActivity(this, 0 /* Request code */, intent,
PendingIntent.FLAG_ONE_SHOT);
Uri defaultSoundUri = RingtoneManager.getDefaultUri(RingtoneManager.TYPE_NOTIFICATION);
NotificationCompat.Builder notificationBuilder = new NotificationCompat.Builder(this)
.setLargeIcon(image)/*Notification icon image*/
.setSmallIcon(R.drawable.icon)
.setContentTitle(messageBody)
.setStyle(new NotificationCompat.BigPictureStyle()
.bigPicture(image))/*Notification with Image*/
.setAutoCancel(true)
.setSound(defaultSoundUri)
.setContentIntent(pendingIntent);
NotificationManager notificationManager =
(NotificationManager) getSystemService(Context.NOTIFICATION_SERVICE);
notificationManager.notify(0 /* ID of notification */, notificationBuilder.build());
}
public Bitmap getBitmapfromUrl(String imageUrl) {
try {
URL url = new URL(imageUrl);
HttpURLConnection connection = (HttpURLConnection) url.openConnection();
connection.setDoInput(true);
connection.connect();
InputStream input = connection.getInputStream();
Bitmap bitmap = BitmapFactory.decodeStream(input);
return bitmap;
} catch (Exception e) {
// TODO Auto-generated catch block
e.printStackTrace();
return null;
}
}}
And this is MainActivity to open link in my WebView or other browser depand on your requirement through intents.
if (getIntent().getExtras() != null) {
if (getIntent().getStringExtra("LINK")!=null) {
Intent i=new Intent(this,WebViewActivity.class);
i.putExtra("link",getIntent().getStringExtra("LINK"));
MainActivity.this.startActivity(i);
finish();
}}
Now in WebViewActivity get link and load url in WebView
WebView webView = (WebView) findViewById(R.id.webView);
Intent i = getIntent();
String url = i.getStringExtra("link");
webView.loadUrl(url);
Is it possible to send an audio file as a push notification in android ? What i want to do is that the user can record his voice as a message and then that message should be delivered to all the users with that app as a push notification . is it possible ?
According to below document, CGM / C2DM / Push Notification can send only 4KB data, So, you can not send audio files via push notification,
http://developer.android.com/guide/google/gcm/c2dm.html
"Apps can use "messages with payload" to deliver messages of up to 4 Kb"
But you can send http url of any audio file, in mobile app will receive audio file link via cgm message and download audio file using http connection.
The other way to do it, is use a module that has already implemented this for you. Technically you do the exact same thing that is described here, however with a single API call to providers like mBlox (http://developer.mblox.com), you'll be able to post your content and the devices you want to target, the hosting of the content, and the translation to a URL are being done for you, as well as sending the actual push notification.
Again, technically, it's the same as previous answers, however, for your personal integration it might be a quicker way to get to market.
There is a Way, we can send a audio url in data from FCM. After that we can parse and sent to another activity.
In FIREBASE SERVICE
JSONObject object = null;
try {
String data = remoteMessage.getData().toString();
Map<String, String> params = remoteMessage.getData();
object = new JSONObject(params);
} catch (Exception e) {
Log.e("FCM err 1", e.getMessage());
}
sendNotification(this, remoteMessage.getNotification().getBody(), remoteMessage.getNotification().getTitle(), remoteMessage.getNotification().getClickAction(), object);
PUSH NOTIFICATION FUNCTION
public static void sendNotification(Context context, String Message, String Title, String ClickAction, JSONObject object) {
NotificationManager notificationManager = (NotificationManager) context.getSystemService(Context.NOTIFICATION_SERVICE);
final String CHANNEL_ID = "KRB";
if (Build.VERSION.SDK_INT >= 26) { // Build.VERSION_CODES.O
NotificationChannel mChannel = new NotificationChannel(CHANNEL_ID, "KRB_channel", NotificationManager.IMPORTANCE_HIGH);
notificationManager.createNotificationChannel(mChannel);
}
// intent = Home
Intent intent = new Intent(ClickAction);
try {
Log.e("FCMurl", object.getString("url"));
Log.e("FCMtype", object.getString("type"));
intent.putExtra("url", object.getString("url"));
intent.putExtra("type", object.getString("type"));
intent.addFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP);
} catch (Exception e) {
// Toast.makeText(context, e.getMessage(), Toast.LENGTH_SHORT).show();
Log.e("FCM err", e.getMessage());
}
PendingIntent pendingIntent = PendingIntent.getActivity(context, 0 /* Request code */, intent, PendingIntent.FLAG_UPDATE_CURRENT);
Uri defaultSoundUri = RingtoneManager.getDefaultUri(RingtoneManager.TYPE_NOTIFICATION);
NotificationCompat.Builder notificationBuilder = new NotificationCompat.Builder(context, CHANNEL_ID)
.setSmallIcon(R.drawable.icon_logo)
.setColor(Color.parseColor("#531E6C")) // small icon background color
.setLargeIcon(BitmapFactory.decodeResource(context.getResources(), R.drawable.icon_sfach))
.setContentTitle(Title)
.setContentText(Message)
.setAutoCancel(true)
.setSound(defaultSoundUri)
.setPriority(Notification.PRIORITY_MAX)
.setDefaults(Notification.DEFAULT_ALL)
.setContentIntent(pendingIntent);
notificationManager.notify(0 /* ID of notification */, notificationBuilder.build());
}
In activity
Intent intent = getIntent();
Bundle bundle = intent.getExtras();
String url;
if(bundle != null){
url = bundle.getString("url");
MediaPlayer mediaplayer = new MediaPlayer();
try {
mediaplayer.setDataSource(url);
mediaplayer.setAudioStreamType(AudioManager.STREAM_MUSIC);
mediaplayer.prepareAsync();
mediaplayer.setOnPreparedListener(new MediaPlayer.OnPreparedListener() {
#Override
public void onPrepared(MediaPlayer mp) {
mediaplayer.start();
}
});
} catch (IOException e) {
e.printStackTrace();
}
}