Can we create rest services for sending a notification to Android app without using Firebase Cloud Messaging / Google Cloud Messaging or other cloud messenger tool? If yes, how's that possible? I have searched for the same but couldn't get the appropriate result. The result I get in that REST services are combined with cloud messenger tool, but I want to create services through which I could easily send notification without open Cloud Messenger console.
code to handle data from php
private void handleNotification(String message) {
Log.e(TAG, "===========================messaging 4=======" );
if (!NotificationUtils.isAppIsInBackground(getApplicationContext())) {
Intent intent= new Intent(this,MainActivity.class);
intent.putExtra("message",message);
intent.putExtra("imageUrl",imageUrl);
intent.putExtra("time_stamp",timeStamp);
intent.setFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP);
LocalBroadcastManager.getInstance(this).sendBroadcast(intent);
final PendingIntent pendingIntent = PendingIntent.getActivity(
this, 0, intent, PendingIntent.FLAG_ONE_SHOT);
Uri notificationSound= RingtoneManager.getDefaultUri(RingtoneManager.TYPE_NOTIFICATION);
NotificationCompat.Builder notifiBuilder=new NotificationCompat.Builder(this)
.setSmallIcon(R.mipmap.ic_launcher)
.setContentTitle("NOTIFICATION !!")
.setContentText(message)
.setAutoCancel(true)
.setSound(notificationSound)
.setContentIntent(pendingIntent) ;
NotificationManager notificationManager=
( NotificationManager) getSystemService(Context.NOTIFICATION_SERVICE);
notificationManager.notify(0,notifiBuilder.build());
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();*/
}
}
private void handleDataMessage(JSONObject json) {
Log.e(TAG, "===========================messaging 4=======" );
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);
if (!NotificationUtils.isAppIsInBackground(getApplicationContext())) {
// app is in foreground, broadcast the push message
Intent intent= new Intent(this,MainActivity.class);
intent.setFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP);
LocalBroadcastManager.getInstance(this).sendBroadcast(intent);
final PendingIntent pendingIntent = PendingIntent.getActivity(
this, 0, intent, PendingIntent.FLAG_ONE_SHOT);
Uri notificationSound= RingtoneManager.getDefaultUri(RingtoneManager.TYPE_NOTIFICATION);
NotificationCompat.Builder notifiBuilder=new NotificationCompat.Builder(this)
.setSmallIcon(R.mipmap.ic_launcher)
.setContentTitle("NOTIFICATION data message!!")
.setContentText(message)
.addAction(R.mipmap.ic_accept,"ACCEPT",pendingIntent)
.addAction(R.mipmap.ic_decline,"DECLINE",pendingIntent)
.setAutoCancel(true)
.setSound(notificationSound)
.setContentIntent(pendingIntent) ;
NotificationManager notificationManager=
( NotificationManager) getSystemService(Context.NOTIFICATION_SERVICE);
notificationManager.notify(0,notifiBuilder.build());
Intent pushNotification = new Intent(Config.PUSH_NOTIFICATION);
pushNotification.putExtra("message", message);
LocalBroadcastManager.getInstance(this).sendBroadcast(pushNotification);
// play notification sound
} else {
// app is in background, show the notification in notification tray
Intent resultIntent = new Intent(getApplicationContext(), MainActivity.class);
resultIntent.putExtra("message", message);
// check for image attachment
if (TextUtils.isEmpty(imageUrl)) {
showNotificationMessage(getApplicationContext(), title, message, resultIntent);
} else {
// image is present, show notification with image
showNotificationMessageWithBigImage(getApplicationContext(), title, message, resultIntent, imageUrl);
}
}
} catch (JSONException e) {
Log.e(TAG, "Json Exception: " + e.getMessage());
} catch (Exception e) {
Log.e(TAG, "Exception: " + e.getMessage());
}
}
This can be a longer and tough process
Create a background service in your app which keeps on checking your webserver for new messages after every certain interval(May be seconds or Minutes).
This service is liable to be killed or cleaned by the Android OS. Hence, you may need to register an AlarmManager which invokes the Services at the intervals.
The background service, will call a webserver API along with a unique ID (May be device ID or some Access Token)
On your webserver, you can create an API which, on receiving a request from the device, using the passed UniqueID, checks if there is any message or not. If there is a message, it responds back with the data.
On the App, on receiving the data from the webserver, you can do the needful.
A similar process is used by FCM/GCM. But it guarantees the notification, as the GooglePlayServices is always running in Android in the background.
This procedure can make you do what you want to a certain extent, but, as aforesaid, can be difficult and challenging.
Since GCM uses simple TCP connection you can do it by urself.
All you need is single TCP Server and TCP client on every device you need.
Will be almost the same, but it will consume more battery.
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.
#Override
public void onMessageReceived(String from, Bundle data) {
dbhelper = DatabaseHelper.getInstance(this);
sharedPreferences = PreferenceManager.getDefaultSharedPreferences(this);
String message = data.getString("message");
Log.d(TAG, "From: " + from);
Log.d(TAG, "Message: " + message);
if (from.startsWith("/topics/teta")) {
if (message != null) {
final Alert alert = new Gson().fromJson(message, Alert.class);
Log.d(TAG, alert.getDesc() + " " + alert.getLink() + " " + alert.getTimeStamp() + " " + alert.getTitle());
dbhelper.addAlertsToDB(alert, DatabaseHelper.NEW);
LocalBroadcastManager.getInstance(this).sendBroadcast(new Intent(AppPreferences.NEW_ALERT_RECIEVED));
boolean notifPref = sharedPreferences.getBoolean(AppPreferences.PREFERENCE_RECIEVE_NOTIFICATION, false);
if (notifPref) {
sendNotification("You Have A New Job Notification.", alert.getTitle());
Log.d(TAG, "Notifications turned " + notifPref + " ...User will be notified");
} else {
Log.d(TAG, "Notifications turned " + notifPref);
}
}
}
}
private void sendNotification(String message, String title) {
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_UPDATE_CURRENT);
NotificationCompat.Builder notificationBuilder = new NotificationCompat.Builder(this)
.setColor(ContextCompat.getColor(this, R.color.colorPrimary))
.setSmallIcon(R.drawable.ic_notifications_active_white_24dp)
.setContentTitle(getResources().getString(R.string.app_name))
.setContentText(message)
.setSubText(title)
.setAutoCancel(true)
.setContentIntent(pendingIntent);
NotificationCompat.InboxStyle inboxStyle = new NotificationCompat.InboxStyle(notificationBuilder);
//Uri defaultSoundUri = RingtoneManager.getDefaultUri(RingtoneManager.TYPE_NOTIFICATION);
String strRingtonePreference = sharedPreferences.getString(AppPreferences.PREFERENCE_SOUND, "");
Uri defaultSoundUri = Uri.parse(strRingtonePreference);
notificationBuilder.setSound(defaultSoundUri);
boolean vibrate = sharedPreferences.getBoolean(AppPreferences.PREFERENCE_VIBRATE, false);
if (vibrate) {
long[] pattern = {0, 200};
notificationBuilder.setVibrate(pattern);
}
NotificationManager notificationManager =
(NotificationManager) getSystemService(Context.NOTIFICATION_SERVICE);
notificationManager.notify(0 /* ID of notification */, notificationBuilder.build());
}
So my problem is to notify user about new messages without annoying him if the user has not already checked the old notification in status bar. I am not able to persist notification id and notification builder.
My server sends new alerts in a continuous stream of 5-10 alerts at once, but each item arrives separately asynchronously often one after other with a split second difference.
So it becomes very annoying for the user since he has not dismissed/viewed the old one.
I wish to update the content of previous notification in the status bar without notifying user....just like Gmail does.
First, add an ID to each notification. It can be a hashcode of the message title for example.
Second, each time you want to post a notification, use 'getActiveNotifications()' to get the array of active notifications. And if you find one with an equal ID, update it passing the existing ID.
And, if you don't want the sound, vibration and ticker to be played again, use the 'setOnlyAlertOnce(true)' option.
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();
}
}