I am trying to develop java server to send push notification in my app.
I succeed to send a notification but I have two problems ...
The message text not appear in status bar (only the name of the application is displayed)
When i click on the notification in the status bar nothing happens (not opening the application)
This is my code of the java server:
//ArrayList<String> userGcmList = new ArrayList<String>();
ArrayList<String> userRegIdGcmList = new ArrayList<String>();
//my phone
userRegIdGcmList.add("***********");
int numverOfDevicesRegisterd = userRegIdGcmList.size();
try {
//AI KEY
Sender sender = new Sender("*****************");
// use this line to send message with payload data
Message message = new Message.Builder()
.collapseKey("1")
.timeToLive(3)
.delayWhileIdle(true)
.addData("message", "Text in the status bar does not appear")
.build();
// Use this for multicast messages
MulticastResult result = sender.send(message, userRegIdGcmList, numverOfDevicesRegisterd);
sender.send(message, userRegIdGcmList, numverOfDevicesRegisterd);
System.out.println(result.toString());
if (result.getResults() != null) {
int canonicalRegId = result.getCanonicalIds();
if (canonicalRegId != 0) {
}
} else {
int error = result.getFailure();
System.out.println(error);
}
} catch (Exception e) {
e.printStackTrace();
}
I open the port 5228 on my router but it does not change...
and the source in my app :
/**
* Issues a notification to inform the user that server has sent a message.
*/
private static void generateNotification(Context context, String message) {
long when = System.currentTimeMillis();
NotificationManager notificationManager = (NotificationManager) context.getSystemService(Context.NOTIFICATION_SERVICE);
Notification notification = new Notification(R.drawable.ic_launcher, message, when);
notification.defaults |= Notification.DEFAULT_SOUND;
notification.flags |= Notification.FLAG_AUTO_CANCEL;
String title = context.getString(R.string.app_name);
Intent notificationIntent = new Intent(context, LauncherActivity.class);
// set intent so it does not start a new activity
notificationIntent.setFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP | Intent.FLAG_ACTIVITY_SINGLE_TOP);
PendingIntent intent = PendingIntent.getActivity(context, 0, notificationIntent, 0);
notification.setLatestEventInfo(context, title, message, intent);
notification.flags |= Notification.FLAG_AUTO_CANCEL;
notificationManager.notify(0, notification);
}
refer this http://www.androidhive.info/2012/10/android-push-notifications-using-google-cloud-messaging-gcm-php-and-mysql/ class name:GCMIntentService
Related
How to get full content of notification in Lolipop or above devices.
I am unable to get notification detail like buttons and icons in notification with this.
#Override
public void onNotificationPosted(StatusBarNotification sbn) {
String pack = sbn.getPackageName();
String ticker ="";
if(sbn.getNotification().tickerText !=null) {
ticker = sbn.getNotification().tickerText.toString();
}
Bundle extras = sbn.getNotification().extras;
String title = extras.getString("android.title");
String text = extras.getCharSequence("android.text").toString();
Log.i("Package",pack);
Log.i("Ticker",ticker);
Log.i("Title",title);
Log.i("Text",text);
Intent msgs = new Intent("Msg");
msgs.putExtra("package", pack);
msgs.putExtra("ticker", ticker);
msgs.putExtra("title", title);
msgs.putExtra("text", text);
LocalBroadcastManager.getInstance(context).sendBroadcast(msgs);
}
As I have seen you did not create your notification. You need a notification builder just after your notification is received in your application.
Hence in the receiver of your broadcast, you need to create the notification to be shown in your status bar like the following.
// Inside your broadcast receiver
int notificationID = new Random().nextInt();
Intent intent = new Intent(mContext, YourHomeActivity.class);
intent.addFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP);
PendingIntent pendingIntent = PendingIntent.getActivity(mContext, notificationID, intent, PendingIntent.FLAG_ONE_SHOT);
Uri defaultSoundUri = RingtoneManager.getDefaultUri(RingtoneManager.TYPE_NOTIFICATION);
NotificationCompat.Builder notificationBuilder = new NotificationCompat.Builder(mContext)
.addAction(R.drawable.ic_prev, "BUTTON 1", myIntentToButtonOneScreen)
.addAction(R.drawable.ic_pause, "BUTTON 2", myIntentToButtonTwoScreen) // #1
.addAction(R.drawable.ic_next, "BUTTON 3", myIntentToButtonThreeScreen)
.setSmallIcon(R.drawable.ic_notification)
.setContentTitle(title)
.setContentText(message)
.setAutoCancel(true)
.setSound(defaultSoundUri)
.setContentIntent(pendingIntent);
if (result != null)
notificationBuilder.setLargeIcon(result);
NotificationManager notificationManager =
(NotificationManager) mContext.getSystemService(Context.NOTIFICATION_SERVICE);
notificationManager.notify(notificationID, notificationBuilder.build());
This is just a sample code which might not work. But this is just to give you an idea. Please follow this developer documentation for better understanding.
Update
Based on the comment asking for the notification listener service, here's sample code on how you can listen to notification that was sent to your mobile. Considering you have used Firebase cloud messaging.
public class FCMListenerService extends FirebaseMessagingService {
private FCMNotificationResponse mFcmNotificationResponse;
private RemoteMessage.Notification notification;
private Map data;
private String from;
#Override
public void onMessageReceived(RemoteMessage message) {
parseRemoteMessage(message);
}
private void parseRemoteMessage(RemoteMessage message) {
from = message.getFrom();
data = message.getData();
notification = message.getNotification();
Logger.logD("Message", "From: " + from);
// Check if message contains a data payload.
if (data.size() > 0) {
Logger.logD("Data", "Message data payload: " + data.toString());
setNotificationResponseFromData(data);
}
createNotification(this, notification.getTitle(), notification.getBody(), mFcmNotificationResponse.getIcon());
}
// Here you parse the JSON body received from notification
private void setNotificationResponseFromData(Map data) {
Gson gson = new Gson();
JsonElement jsonElement = gson.toJsonTree(data);
mFcmNotificationResponse = gson.fromJson(jsonElement, FCMNotificationResponse.class);
}
private void createNotification(Context context, String title, String message, String imageUrl) {
new CreateNotificationAsyncTask(context, title,
message, imageUrl).executeOnExecutor(AsyncTask.THREAD_POOL_EXECUTOR);
}
}
onMessageReceived function is called when a notification is received. Then you need to parse your data and then create the notification accordingly.
How could I get the Notification Title of the notification ?
Here's my code :
-From Notification Service :
resultIntent= new Intent(NotificationService.this, StartNAFromNS.class);
resultIntent.putExtra(Intent.EXTRA_TITLE, underestood_name.replace("__", " "));
-From StartNAFromNS :
String text = this.getIntent().getStringExtra(Intent.EXTRA_TITLE);
When doing this with only 1 notification, I get the correct title. However, if my application sends 2 notifications, I will get the title of the second notification.
How could I get the proper notification title ?
By extending NotificationListenerService and using its onNotificationPosted method in our class we will be able to get notification title, text and package name. Using notification package we get its app icon, app name and many more.
public class MyNotification extends NotificationListenerService {
Context context;
#Override
public void onCreate() {
super.onCreate();
context = getApplicationContext();
}
#Override
public void onNotificationPosted(StatusBarNotification sbn) {
// We can read notification while posted.
for (StatusBarNotification sbm : MyNotification.this.getActiveNotifications()) {
String title = sbm.getNotification().extras.getString("android.title");
String text = sbm.getNotification().extras.getString("android.text");
String package_name = sbm.getPackageName();
Log.v("Notification title is:", title);
Log.v("Notification text is:", text);
Log.v("Notification Package Name is:", package_name);
}
}
}
Notification id should be unique within your application.
If a notification with the same id has already been posted by your
application and has not yet been canceled, it will be replaced by the
updated information.
NotificationManager notiManager = (NotificationManager) mContext.getSystemService(Context.NOTIFICATION_SERVICE);
notiManager.notify(UNIQUE_ID, notification);
If you are using PendingIntent.getActivity() method, use different requestCode for different notification:
Intent resultIntent= new Intent(NotificationService.this, StartNAFromNS.class);
resultIntent.putExtra(Intent.EXTRA_TITLE, underestood_name.replace("__", " "));
PendingIntent pI = PendingIntent.getActivity(mContext, REQUEST_CODE, resultIntent, PendingIntent.FLAG_UPDATE_CURRENT);
Hope this will help!
This code properly working for the fcm. We can send a message and title from the fcm console or server. The notification received by the registered mobile app.
#Override
public void onMessageReceived (String from, Bundle data) {
//Getting the message from the bundle
long dateTime = data.getLong("google.sent_time");
Bundle notificationBundle = data.getBundle("notification");
String message = notificationBundle.getString("body");
String title = notificationBundle.getString("title");
//Displaying a notiffication with the message
sendNotification(title, message);
}
//The following method is generating a notification and displaying the notification
private void sendNotification(String title, String message) {
Intent intent = new Intent(this, MainActivity.class);
intent.putExtra("message", message);
intent.addFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP);
int requestCode = 0;
PendingIntent pendingIntent = PendingIntent.getActivity(this, requestCode, intent, PendingIntent.FLAG_ONE_SHOT);
NotificationCompat.Builder noBuilder = new NotificationCompat.Builder(this)
.setContentTitle(title)
.setContentText(message)
.setAutoCancel(true)
.setContentIntent(pendingIntent);
if (Build.VERSION.SDK_INT >= 21)
noBuilder.setSmallIcon(R.mipmap.ic_launcher);
else
noBuilder.setSmallIcon(R.mipmap.ic_launcher_small);
NotificationManager notificationManager = (NotificationManager) getSystemService(Context.NOTIFICATION_SERVICE);
notificationManager.notify(0, noBuilder.build()); //0 = ID of notification
}
hey all i'm making an application where the user's can send gcm messages to each other
the application is working very good and when i send a gcm message the receiver get it as a notification
and when the receiver click it it opens the homepage.class but the problem is that
when he click on the notification the Broadcast receiver does not receive it and doesn't make change's to the EditText, On the other hand if the receiver was using homepage.class when the message was received it make change's to the EditText (Working)
what could be the problem ???
some methods from my GCMIntentService
#Override
private static void generateNotification(Context context, String message) {
int icon = R.drawable.ic_launcher;
long when = System.currentTimeMillis();
NotificationManager notificationManager = (NotificationManager)
context.getSystemService(Context.NOTIFICATION_SERVICE);
Notification notification = new Notification(icon, message, when);
String title = context.getString(R.string.app_name);
Intent notificationIntent = new Intent(context, HomePage.class);
// set intent so it does not start a new activity
notificationIntent.setFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP |
Intent.FLAG_ACTIVITY_SINGLE_TOP);
PendingIntent intent =
PendingIntent.getActivity(context, 0, notificationIntent, 0);
notification.setLatestEventInfo(context, title, message, intent);
notification.flags |= Notification.FLAG_AUTO_CANCEL;
// Play default notification sound
notification.defaults |= Notification.DEFAULT_SOUND;
// Vibrate if vibrate is enabled
notification.defaults |= Notification.DEFAULT_VIBRATE;
notificationManager.notify(0, notification);
}
#Override
protected void onMessage(Context context, Intent intent) {
String message = intent.getExtras().getString("message");
// notifies user
aController.displayMessageOnScreen(context, message);
generateNotification(context, message);
}
void displayMessageOnScreen(Context context, String message) {
Intent intent = new Intent("com.ms.gp.wefamily.DISPLAY_MESSAGE");
intent.putExtra("message", message);
// Send Broadcast to Broadcast receiver with message
context.sendBroadcast(intent);
}
and this is the code of my BroadcastReceiver
#Override
private final BroadcastReceiver mHandleMessageReceiver = new BroadcastReceiver() {
public void onReceive(Context context, Intent intent) {
String newMessage = intent.getExtras().getString("message");
// Display message on the screen
Familyname.setText(newMessage);
}
};
please if anyone knows the answer tell me (Sorry for bad English)
Make sure you register the receiver on its parent activity. Once it's properly registered have it handle the received bundle. Pay attention to the sent value tags.
My application is receiving GCM notifications. I have different type of notifications and at some point the user can have more than one notification in the status bar. However I need to know which one exactly he clicked on. In the GCM onMessage Im setting them with
NotificationManager manager = (NotificationManager) getSystemService(NOTIFICATION_SERVICE);
manager.notify(Integer.parseInt(notification_id), notification);
I need to get that notification_id after the click on the notification. I am pretty sure that's something simple but I couldnt find any info about it.
Here are the onMessage from GCMIntentService
#Override
protected void onMessage(Context context, Intent data) {
String content_title;
String content_text;
String event_id;
String content_info;
String url;
String match_id;
// Message from PHP server
content_title = data.getStringExtra("content_title");
content_text = data.getStringExtra("content_text");
content_info = data.getStringExtra("content_info") + "'";
event_id = data.getStringExtra("event_id");
match_id = data.getStringExtra("match_id");
url = data.getStringExtra("url");
NOTIFICATION_URL = url;
// Open a new activity called GCMMessageView
Intent intent = new Intent(this, GCMMessageView.class);
// Pass data to the new activity
intent.putExtra("message", content_title);
intent.putExtra("url", url);
// Starts the activity on notification click
PendingIntent pIntent = PendingIntent.getActivity(this, 0, intent,
PendingIntent.FLAG_UPDATE_CURRENT);
Options opts = new Options();
opts.inDither = true;
opts.inScaled = false;
/* Flag for no scalling */
// Create the notification with a notification builder
Notification notification = new NotificationCompat.Builder(this)
.setSmallIcon(drawable_small).setLargeIcon(drawable_big)
.setWhen(System.currentTimeMillis()).setTicker(content_title)
.setContentTitle(content_title).setContentInfo(content_info)
.setContentText(content_text).setContentIntent(pIntent)
.getNotification();
// Remove the notification on click
notification.ledARGB = 0xff00ff00;
notification.ledOnMS = 300;
notification.ledOffMS = 1000;
notification.flags |= Notification.FLAG_SHOW_LIGHTS;
notification.flags |= Notification.FLAG_AUTO_CANCEL;
NotificationManager manager = (NotificationManager) getSystemService(NOTIFICATION_SERVICE);
manager.notify(Integer.parseInt(match_id), notification);
try {
Uri notification2 = RingtoneManager
.getDefaultUri(RingtoneManager.TYPE_NOTIFICATION);
Ringtone r = RingtoneManager.getRingtone(getApplicationContext(),
notification2);
r.play();
} catch (Exception e) {
}
{
// Wake Android Device when notification received
PowerManager pm = (PowerManager) context
.getSystemService(Context.POWER_SERVICE);
final PowerManager.WakeLock mWakelock = pm.newWakeLock(
PowerManager.FULL_WAKE_LOCK
| PowerManager.ACQUIRE_CAUSES_WAKEUP, "GCM_PUSH");
mWakelock.acquire();
// Timer before putting Android Device to sleep mode.
Timer timer = new Timer();
TimerTask task = new TimerTask() {
public void run() {
mWakelock.release();
}
};
timer.schedule(task, 5000);
}
}
And there`s the on click
String msg;
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
Intent intent = getIntent();
if (intent.hasExtra("url"))
msg = intent.getExtras().getString("url");
Log.e("URL", msg);
setContentView(R.layout.activity_main);
Intent browserIntent = new Intent(Intent.ACTION_VIEW, Uri.parse(msg
+ "?device_id="
+ GCMIntentService.DEVICE_REGISTRATION_ID.toString()));
startActivity(browserIntent);
// Toast.makeText(getApplicationContext(),
// GCMIntentService.DEVICE_REGISTRATION_ID, Toast.LENGTH_LONG).show();
}
You can go through the below code, You have to ser Notification object as per your need.
String appname = context.getResources().getString(R.string.app_name);
NotificationManager notificationManager = (NotificationManager) context
.getSystemService(Context.NOTIFICATION_SERVICE);
int currentapiVersion = android.os.Build.VERSION.SDK_INT;
Notification notification;
Intent intent = new Intent(context, NotificationActivity.class);
intent.addFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP | Intent.FLAG_ACTIVITY_NEW_TASK);
intent.putExtra("message", YOUR_DATA);
int requestID = (int) System.currentTimeMillis();
PendingIntent contentIntent = PendingIntent.getActivity(context, requestID,
intent, 0);
if (currentapiVersion < android.os.Build.VERSION_CODES.HONEYCOMB) {
notification = new Notification(icon, message, when);
notification.setLatestEventInfo(context, appname, message,
contentIntent);
notification.flags = Notification.FLAG_AUTO_CANCEL;
notificationManager.notify((int) when, notification);
} else {
NotificationCompat.Builder builder = new NotificationCompat.Builder(
context);
notification = builder.setContentIntent(contentIntent)
.setSmallIcon(icon).setTicker(appname).setWhen(when)
.setAutoCancel(true).setContentTitle(appname)
.setContentText(message).build();
notificationManager.notify((int) when, notification);
}
When user click on any notification, it will re-direct to NotificationActivity class.
In this activity, in OnCreate() method you can get your data that is set.
Intent intent = getIntent();
if (intent.hasExtra("message"))
String msg = intent.getExtras().getString("message");
I think it will help.
I 'm working application to receive message but i want to appear notification when receive message
please, how is work it
PendingIntent pi = PendingIntent.getActivity(getApplicationContext(), 0, new Intent(getApplicationContext(), Player.class).setFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP | Intent.FLAG_ACTIVITY_SINGLE_TOP), PendingIntent.FLAG_UPDATE_CURRENT);
notification = new Notification();
notification.tickerText = "App Name";
notification.icon = R.drawable.icon;
notification.flags |= Notification.FLAG_ONGOING_EVENT;
try {
notification.setLatestEventInfo(getApplicationContext(), "App Name", "AppName~ ", pi);
} catch (Exception e) {
e.printStackTrace();
}
startForeground(01, notification);