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();
}
}
Related
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;
}
}
}
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.
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);
Im building a ping feature for finding a lost phone through bluetooth. I need the phone to sound even though it is set to mute/silent like how the alarm usually works. I thought I could put the streamtype of my notification to AudioManager.STREAM_ALARM but its not working. It only sounds when the phones sound is on. This is how I set it:
NotificationCompat.Builder builder = new NotificationCompat.Builder(getApplicationContext());
builder.setSmallIcon(R.drawable.ic_spenwallet)
.setContentTitle("Ping")
.setContentText("Device is trying to find your phone.")
.setAutoCancel(false)
.setSound(sound, STREAM_ALARM)
.setVibrate(vibratePattern)
.addAction(cancelAction);
If I try :
Notification notification = builder.build();
notification.audioStreamType = AudioManager.STREAM_ALARM;
Im getting a warning from Android Studio that audioStreamType is deprecated. Is this the case? Any other way to make the notificaiton sound even though silent mode is on? (preferable also vibrate)
I got it working by creating a dedicated mediaplayer for the purpose but I don't think this should be needed. Heres how I did it anyway:
MediaPlayer mediaPlayer = new MediaPlayer();
final String packageName = getApplicationContext().getPackageName();
Uri sound = Uri.parse("android.resource://" + packageName + "/" + R.raw.ping_sound);
try {
mediaPlayer.setDataSource(this, sound);
} catch (IOException e) {
e.printStackTrace();
}
final AudioManager audioManager = (AudioManager) getSystemService(Context.AUDIO_SERVICE);
if (audioManager.getStreamVolume(AudioManager.STREAM_ALARM) != 0) {
mediaPlayer.setAudioStreamType(AudioManager.STREAM_ALARM);
mediaPlayer.setLooping(false);
try {
mediaPlayer.prepare();
} catch (IOException e) {
e.printStackTrace();
}
mediaPlayer.start();
}
Using builder.setSound(alarmSound, AudioManager.STREAM_AUDIO) was exactly what I needed to keep my alarm going! Perhaps your issue is with the R.raw.ping_sound sound sample that you are using. After trying a bunch of terrible implementations I found online for alarm notifications (which is where I found Settings.System.DEFAULT_RINGTONE_URI) I followed the official notification documentation and then used the NotificationCompat.Builder documentation for customization.
Here is my working alarm notification:
private void showNotification(){
// Setup Intent for when Notification clicked
Intent intent = new Intent(mContext, MedsActivity.class);
intent.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK | Intent.FLAG_ACTIVITY_CLEAR_TASK); // See https://developer.android.com/training/notify-user/navigation for better navigation
PendingIntent pendingIntent = PendingIntent.getActivity(mContext, 0, intent, 0);
// Setup Ringtone & Vibrate
Uri alarmSound = Settings.System.DEFAULT_RINGTONE_URI;
long[] vibratePattern = { 0, 100, 200, 300 };
// Setup Notification
String channelID = mContext.getResources().getString(R.string.channel_id_alarms);
NotificationCompat.Builder mBuilder = new NotificationCompat.Builder(mContext, channelID)
.setContentText(notificationMessage)
.setContentTitle(notificationTitle)
.setSmallIcon(R.mipmap.ic_launcher_round)
.setPriority(NotificationCompat.PRIORITY_DEFAULT)
.setCategory(NotificationCompat.CATEGORY_ALARM)
.setVisibility(NotificationCompat.VISIBILITY_PUBLIC)
.setContentIntent(pendingIntent)
.setSound(alarmSound, AudioManager.STREAM_ALARM)
.setOnlyAlertOnce(true)
.setVibrate(vibratePattern)
.setAutoCancel(true);
// Send Notification
NotificationManager manager = (NotificationManager) mContext.getSystemService(NOTIFICATION_SERVICE);
manager.notify(NOTIFICATION_ID, mBuilder.build());
}
I'm building an android app which supports push notifications using phonegap/cordova and this plugin. The plugin has an onMessage() method which is triggered whenever a push notification is received, this method returns a json object to my javascript plugin. However I want this method to return the json only when the notification on status bar is clicked.
This is my onMessage() method:
protected void onMessage(Context context, Intent intent) {
String message = "", title = "", type = "";
int msgctn = 0, schoolid = 0, studentid = 0, contentid = 0;
// Extract the payload from the message
Bundle extras = intent.getExtras();
if (extras != null) {
try
{
message = extras.getString("message");
title = extras.getString("title");
type = extras.getString("type");
msgctn = Integer.parseInt(extras.getString("msgctn"));
schoolid = Integer.parseInt(extras.getString("schoolid"));
studentid = Integer.parseInt(extras.getString("studentid"));
contentid = Integer.parseInt(extras.getString("contentid"));
JSONObject json;
json = new JSONObject().put("event", "message");
json.put("message", message);
json.put("type", type);
json.put("contentid", contentid);
json.put("schoolid", schoolid);
json.put("studentid", studentid);
GCMPlugin.sendJavascript( json );
// Send the MESSAGE to the Javascript application
}
catch( JSONException e)
{
Log.e(ME + ":onMessage", "JSON exception");
}
Intent notificationIntent = new Intent(context, App4.class);
notificationIntent.addFlags(Intent.FLAG_ACTIVITY_SINGLE_TOP);
PendingIntent contentIntent = PendingIntent.getActivity(context, 0, notificationIntent, 0);
NotificationCompat.Builder builder = new NotificationCompat.Builder(context)
.setContentText(message)
.setContentTitle(title)
.setSmallIcon(Build.VERSION.SDK_INT >= Build.VERSION_CODES.HONEYCOMB ? R.drawable.icon : android.R.drawable.ic_dialog_info)
.setAutoCancel(true)
.setContentIntent(contentIntent)
.setWhen(System.currentTimeMillis())
//.setDefaults(Notification.DEFAULT_ALL)
.setLights(-16711681, 2000, 1000)
.setNumber(msgctn)
.setSound(Uri.parse("android.resource://"+ getPackageName() + "/" + R.raw.notifsound));
Notification notification = builder.build();
NotificationManager notificationManager = getNotificationManager(context);
notificationManager.notify(1, notification);
}
I had to create a notification object in order to show it on status bar. When the notification is clicked it calls intent App4, this shows the index.html of my app, but I want to execute some javascript function or return some json object to my app using the payload. Maybe I can call other function to do this, not an intent but I'm new on android world and don't know how to do it.
Can anyone help me please?
What you can do is put the JSON data as extras in the notificationIntent Intent that you are creating. You can do this by calling the putExtras() method of your notificationIntent, or do it manually. Whichever way you do it you need to get the data you want into the notificationIntent as extras.
Then when your App4 activity starts you will need catch the Intent in either onNewIntent() or onCreate() and check to see if the Intent or Bundle has the extras that you want. If it does then you create the JSON object and pass it to your javascript application just like you did in the onMessage() method you pasted.
You will also have to remove the code that sends the JSON object to your javascript application in the onMessage() method.
I hope that helps, it should work but I'm away from my computer and can't actually test the code.