how to send push Notifications to other device in android? - android

Using this code, i am able to send a notification to my own device.
Intent intent = new Intent(getApplicationContext(), ContactDonor.class);
PendingIntent pi = PendingIntent.getActivity(getApplicationContext(), 0, intent, 0);
//display text
String body = "Please Click on this to accept!";
String title = bloodgroup+" Required";
Notification n = new Notification(R.drawable.ic_launcher, body , System.currentTimeMillis());
n.setLatestEventInfo(getApplicationContext(), title, body, pi);
n.defaults = Notification.DEFAULT_ALL;
nm.notify(uniqueID, n);
finish();
But now i have a screen where a person's details are displayed like:
Name: ...
email: ...
, and there is a message box and a Request Button , on the click of that button, he should receive a notification with that particular message. How can this particular thing be done?

It cannot be implemented by using PUSH notifications. PUSH notification is useful when there is server-client comm is implemented where server notifies the client about the event that has occurred on server side.
What you are trying to implement indirectly is server-client architecture, where your device will act as server. If you mould your current architecture to server-client you will be able to send notification to other device. In this case also, you don't need PUSH notifications, it will be a simple server-client communication.
For more info on PUSH please see: http://www.vogella.com/articles/AndroidCloudToDeviceMessaging/article.html#c2dm_sendmessage
You can also send SMS, but that will not solve your problem. According to me, there is no other solution that you can apply to send notification.

Related

Creating a local notification in response to a push notification (from firebase) in cordova/ionic

I'm building an application using Ionic Framework that implements a chat function similar to good-old facebook messenger, in that i want to notify users of a chat message, but if they view it elsewhere, i want to remove the notification from their home screen.
I'm using firebase as a back-end for push notifications (though that could be changed i suppose).
I know that you can't expire a remote notification, but i've been told you can expire + remove a local notification, so my question is - can i reliably receive a remote notification, create a local one, and display that, and then in response to a notification with a scope of 'expire' or 'remove', delete a local notification so that my users don't see a duplication of information?
Most plugins tend to detect the status of the app and add a remote notification to the homescreen with the info you've pushed by default, is there a way to avoid this?
Thanks guys.
EDIT:
- Local notifications: http://ionicframework.com/docs/native/local-notifications/
- Firebase cloud messaging: https://github.com/fechanique/cordova-plugin-fcm
As far as I can tell there're no plugins which accomplish all what you need. However..
can i reliably receive a remote notification, create a local one, and display that, and then in response to a notification with a scope of 'expire' or 'remove', delete a local notification so that my users don't see a duplication of information?
Most plugins tend to detect the status of the app and add a remote notification to the homescreen with the info you've pushed by default, is there a way to avoid this?
Yes, by using silent notifications and building the local notification by yourself.
For a project I'm working in, I modified the plugin cordova-plugin-fcm to add support for (local on demand) notifications dismiss/display, send multiple notifications to the cordova app, and some PRs that are not included yet. Also I build the notification by myself, to have full control of what is displayed. You can take a look at the code to get some ideas.
In brief it works like this:
Firstly, I send a "silent" push to the app, which is not displayed by Android:
{
"content_available": true, // IMPORTANT: For Apple -> content-available: 1, for firebase -> content_available: true
"priority": "high",
"to": "/topics/all", // or to a fcm token
"data"{
"title": "My title", // this implies that you display the notification by yourself
"body": "My body", // this implies that you display the notification by yourself
"type": "NEW_USER_MESSAGE", // only relevant to this project
"userId": "1", // only relevant to this project
"timestamp", "150000000"
}
}
Note: If the payload have the "notification": {} item, Android will display it on the system tray (if the app is in background).
https://firebase.google.com/docs/cloud-messaging/concept-options#notifications_and_data_messages
Secondly, when the push arrives to the app (in onMessageReceived()), I build the local notification, assigning it a TAG and an ID. This is the way you can use to dismiss it later.
For example, you could create a local notification with the TAG "NEW_USER_MESSAGE" and ID 1 (a constant indicating a state of the message, or the user ID for example). Also, Android will replace notifications with the same TAG and ID, so this is another way to automatically replace notifications (for example if you send a generic message, like "New update available").
public static String TYPE_NEW_USER_MESSAGE = "NEW_USER_MESSAGE";
public static String TYPE_USER_LEFT_ROOM = "USER_LEFT_ROOM";
NotificationManager notificationManager =
(NotificationManager) _ctx.getSystemService(Context.NOTIFICATION_SERVICE);
// based in the type of the message you've received, you can stylize the notification
if (type.equals( TYPE_USER_LEFT_ROOM )){
notificationBuilder.setColor(Color.RED);
notificationBuilder.setLights(Color.RED, 1000, 500);
}
else if (type.equals( TYPE_NEW_USER_MESSAGE )){
notificationBuilder.setColor(Color.BLUE);
notificationBuilder.setLights(Color.BLUE, 1000, 1000);
}
Notification n = notificationBuilder.build();
notificationManager.notify(type, userId, n);
One advantage of doing it in this way, is that you have full control of the notification to be displayed, so you can stylize it like you want.
If you want to discard expired messages, you can check out the elapsed time between the sent timestamp and the current timestamp:
java.util.Date now = new java.util.Date();
java.util.Date sent_timestamp = new java.util.Date( Long.valueOf(timestamp.toString()) );
final Long elapsed_time = ((now.getTime() - sent_timestamp.getTime()) / 1000);
Log.d(TAG, "New message. sent " + elapsed_time + "s ago");
Thirdly, when the user clicks on a notification Android will launch your app, and the plugin will send the payload of the push message to the cordova view (onNotificationReceived()).
Once your app is opened and you have received the push message, you can dismiss it adding a new action to the plugin:
onNotificationReceived(data){
if (data.wasTapped === true){
if (data.type === 'NEW_USER_MESSAGE'){
FCMPlugin.dismissNotification(NEW_USER_MESSAGE, 1);
}
}
}
The Android action:
else if (action.equals( ACTION_DISMISS_NOTIFICATION )) {
cordova.getThreadPool().execute(new Runnable() {
public void run() {
try{
Log.d(TAG, "FCMPlugin dismissNotificaton: " + args.getString(0)); //tag
NotificationManager nManager = (NotificationManager) mContext.getSystemService(Context.NOTIFICATION_SERVICE);
nManager.cancel(args.getString(0)/*NEW_USER_MESSAGE*/, args.getInt(1) /*1*/);
Log.d(TAG, "FCMPlugin dismissNotificaton() to remove: " + id); //tag
callbackContext.success();
}catch(Exception e){
callbackContext.error(e.getMessage());
}
}
});
https://github.com/TrustedCircles/cordova-plugin-fcm/blob/master/src/android/FCMPlugin.java#L286
And the method exposed to the cordova app:
// dismisses a notification by tag+id
FCMPlugin.prototype.dismissNotification = function( tag, userId, success, error ){
exec(success, error, "FCMPlugin", 'dismissNotification', [tag, userId]);
}
https://github.com/TrustedCircles/cordova-plugin-fcm/blob/master/www/FCMPlugin.js#L65
The only tricky bit with notifications in cordova/ionic is the JS part receiving the notification and triggering the Android code.
I used https://github.com/phonegap/phonegap-plugin-push library and its pretty straight forward.
There is a callback when notifications are received in JS(Cordova/Ionic), use this to render you notifications locally in Android.
P.S: Basel's answer tells you how to clear your notifications, so I decided to leave that bit out.

Sending notifications to all devices

I have an app in which markers can be added to the map using the Google Maps API, I'm trying to send a notification to all devices with the app installed when a new marker is added, this works for the device that is currently using the app but not my other device which does not have the app loaded, is there something else I have to do to register it with other devices?
Here is the code for connecting to the server and adding the marker, which calls the showNotification method:
try
{
HttpClient httpClient = new DefaultHttpClient();
HttpPost httpPost = new HttpPost("http://***.***.***.**/markerLocation/save.php");
httpPost.setEntity(new UrlEncodedFormEntity(nameValuePairs));
HttpResponse response = httpClient.execute(httpPost);
HttpEntity entity = response.getEntity();
is = entity.getContent();
String msg = "Data entered successfully";
//The method call that makes the alert notification
ShowNotification(name);
Toast.makeText(getApplicationContext(), msg, Toast.LENGTH_LONG).show();
}
and here is the code for creating the alert:
public void ShowNotification(String name)
{
// define sound URI, the sound to be played when there's a notification
Uri soundUri = RingtoneManager.getDefaultUri(RingtoneManager.TYPE_NOTIFICATION);
// intent triggered, you can add other intent for other actions
Intent intent = new Intent(GoogleMapsActivity.this, NotificationReceiver.class);
PendingIntent pIntent = PendingIntent.getActivity(GoogleMapsActivity.this, 0, intent, 0);
// this is it, we'll build the notification!
// in the addAction method, if you don't want any icon, just set the first param to 0
Notification mNotification = new Notification.Builder(this)
.setContentTitle(name)
.setContentText(name + " has added a marker in your area")
.setSmallIcon(R.drawable.ic_launcher)
.setContentIntent(pIntent)
.setSound(soundUri)
.addAction(0, "View", pIntent)
.addAction(0, "Remind", pIntent)
.build();
NotificationManager notificationManager = (NotificationManager) getSystemService(NOTIFICATION_SERVICE);
// If you want to hide the notification after it was selected, do the code below
mNotification.flags |= Notification.FLAG_AUTO_CANCEL;
notificationManager.notify(0, mNotification);
}
First you will need a Push service to warn other devices of your new marker, then you will need a BroadCastReceiver to receive the push message and emit the Notification on all devices that received it, I would love to explain this and write some example code for you but its widely explained in Android Docus so why reinvent the wheel?
Look at this page, it has everything u need:
Google Cloud Messaging GCM
I think you are not grasping how the two notifications type functions. The way you would do this is by storing on your server the device id of all your users that have requested to receive the notifications. Then you initiate the notification for all devices from the server not from the app. Notification initiated from the app are only to display a message on the device outside of our app's UI
Take a look at this: https://developer.android.com/google/gcm/index.html
What you need is some kind of support for push notifications, an obvious choice for Android is Google Cloud Messaging (GCM).
Since you have a server available, you could tailor the server-side yourself for managing which devices that receive the notifications (plenty of tutorials out there).
If you are in a hurry and just want to get stuff working, you can use parse.com. They allow you to send push messages to 1 mil unique devices (through GCM) for free. The upside here is that they make it easier to setup and filter which devices that should receive the notifications.

How to make push notification without internet

me and my colleague are trying to show "push notification" message in mobile device. Colleague is telling that it canĀ“t be done without Google Cloud Messaging but I think - why use any server for that?
We want something like this:
How our application will work is:
- user has app on background
- ajax request is made (request to our server)
- server response is: You have 1 new message
- message is showed in top strip on mobile.
Of course, the message can be showed without internet.. My GF had mobile app "Pou"... when he pooped notification was displayed... Just I dont get it why to use any Google service for that?
Can somebody direct me pls?
You should use Notification to show "push notification".
private void showNotification() {
Intent notificationIntent = new Intent(this, MainActivity.class);
NotificationCompat.Builder builder = new NotificationCompat.Builder(this)
.setSmallIcon(R.drawable.ic_launcher)
.setAutoCancel(true)
.setTicker(getString(R.string.notification_ticker_text))
.setContentText(getString(R.string.notification_content_text))
.setContentIntent(PendingIntent.getActivity(this, 0, notificationIntent, 0))
.setWhen(System.currentTimeMillis())
.setContentTitle(getString(R.string.app_name))
.setDefaults(Notification.DEFAULT_ALL);
Notification notification = builder.build();
((NotificationManager) this.getSystemService(NOTIFICATION_SERVICE)).notify(0, notification);
}

Get response after Android Wear Action

I'm trying to develop with Android Wear. I tried all the tutorial provided in the documentation, but now I want to try to do something smarter. I'm trying to get back the text that user says (with emulator written by computer keyboard), so I made it with this code:
protected void voiceNotification() {
// Crete intent for the response action
Intent replyIntent = new Intent(this, ReplyActivity.class);
// Adding intent to pending intent
PendingIntent replyPendingIntent = PendingIntent.getActivity(this, 0,
replyIntent, 0);
// Build the notification
NotificationCompat.Builder replyNotificationBuilder = new NotificationCompat.Builder(
this);
replyNotificationBuilder
.setSmallIcon(android.R.drawable.ic_btn_speak_now);
replyNotificationBuilder.setContentTitle("Messaggio");
replyNotificationBuilder.setContentText("Testo del messaggio");
replyNotificationBuilder.setContentIntent(replyPendingIntent);
replyNotificationBuilder.setNumber(++numMessages);
replyNotificationBuilder.setAutoCancel(true);
replyNotificationBuilder.setSound(RingtoneManager
.getDefaultUri(RingtoneManager.TYPE_NOTIFICATION));
replyNotificationBuilder.setVibrate(new long[] { 1000, 1000 });
replyNotificationBuilder.setTicker("Hai una nuova notifica!");
// Create remote input
RemoteInput remoteInput = new RemoteInput.Builder(EXTRA_VOICE_REPLY)
.setLabel(getResources().getString(R.string.reply_label))
.build();
// Create the wearable notification
Notification replyNotification = new WearableNotifications.Builder(replyNotificationBuilder)
.addRemoteInputForContentIntent(remoteInput)
.build();
// Get the instance of NotificationManagerCompat and send my notification
NotificationManagerCompat.from(this).notify(0, replyNotification);
}
With this code on the emulator I'm getting 2 views: one with the text of my notification and a second one in which I can answer to notification with voice (keyboard with emulator). It's working all good, but I want to know if it's possible to get the text I said (wrote with emulator) to do something in my application (I saw on the emulator display that after I said/wrote somethings it appears 2 button "Edit" and "Send", so I think that with button "Send" I can get the text in my application to do something). I try to find out something in the documentation, but I don't find nothing. I hope you can help me to get this text.
You'll need to implement a Broadcast-receiver that listens to the pendingIntent you defined - the reply from the user will be passed in an extra string you defined in the RemoteInput - in your case this would be EXTRA_VOICE_REPLY.
You might want to have a look at these two files someone posted on GitHub in order to understand what is going on.
http://git.io/emKcrw
http://git.io/_PRW_w

Android push notification opening a custom page

my question for you is the following: I have a web app written in HTML5, wrapped as a native Android app in order to use Google Push Notifications. Because my app is using many notifications for different reasons, I want to be able to say each time a notification is received, which page to be open, like adding a 'href' in the notification intent. Is this possible?
If I wasn't clear enough please let me know.
Thanks
You can define your own notification message content. The Message builder from Google supports key value pairs to be set by the sender of the notification.
See http://developer.android.com/reference/com/google/android/gcm/server/Message.html
Example:
Message message = new Message.Builder()
.addData("link1", "http://mypage1.com")
.addData("link2", "http://mypage2.com")
.build();
When you create the notification, use setContentIntent() to attach an Intent that has been constructed to visit the right webpage:
// assuming <this> is an Activity or other Context
Intent urlIntent = new Intent(Intent.ACTION_VIEW, Uri.parse(yourUrl));
PendingIntent urlPendingIntent = PendingIntent.getActivity(this, 0 urlIntent, 0);
Notification.Builder b = new Notification.Builder(this)
.setSmallIcon(...).setContentTitle(...).setContentText(...) // etc.
.setContentIntent(urlPendingIntent);
NotificationManager noMan
= (NotificationManager) getSystemService(NOTIFICATION_SERVICE);
noMan.notify(ID, b.build());
If you expect to have more than one of these in the notification panel at a time:
Reconsider. It's spammy to post more than one notification.
If you must, you'll need a separate ID (or separate tag) for each.

Categories

Resources