how to push message/notification to every subscriber of One Signal - android

i can push notification to a specific user using its id (notification key)
public class SendNotification {
public SendNotification(String message, String heading, String notificationKey){
try {
JSONObject notificationContent = new JSONObject(
"{'contents':{'en':'" + message + "'},"+
"'include_player_ids':['" + notificationKey + "']," +
"'headings':{'en': '" + heading + "'}}");
OneSignal.postNotification(notificationContent, null);
} catch (JSONException e) {
e.printStackTrace();
}
}
}
as in one signal documentation
https://documentation.onesignal.com/docs/sending-notifications
there we can push notification to everyone(all the subscribers)
how can i push notification to everyone using code as i can send to a single subscriber

Send to all Active Users with the included_segments key:
Update:
It seems like using include_player_ids does not require an API Key to send the message. However, using included_segments, does - "Requires your OneSignal App's REST API Key"
Have ammended the code below to include the app_id key.
public class SendNotification {
public SendNotification(String message, String heading, String notificationKey){
try {
JSONObject notificationContent = new JSONObject(
"{'app_id':\"YOUR_APP_ID\"," +
"'contents':{'en':'" + message + "'},"+
"'included_segments':[\"Active Users\"]," +
"'headings':{'en': '" + heading + "'}}");
OneSignal.postNotification(notificationContent, null);
} catch (JSONException e) {
e.printStackTrace();
}
}
}
https://documentation.onesignal.com/reference#section-example-code-create-notification

Related

Firebase onMessageReceived() not called in some devices with data payload when app is killed

I know when app is killed then we need to send data payload in order to send push notification and onMessageReceived() method will invoke.
But after reading more than 100 SO answers and articles I concluded that on many devices onMessageReceived() does not invoke once they killed even with data payload.
Still is there any way that I can show notification in those devices.
Use this method id FirebaseMessaging class
#Override
public boolean zzE(Intent intent) {
Log.e(TAG, "zzE");
Set<String> keys = intent.getExtras().keySet();
Log.e(TAG, "" + keys);
Iterator<String> it = keys.iterator();
while (it.hasNext()) {
Log.e(TAG, "zzE " + it.next());
}
for (String key : keys) {
try {
Log.e("uniq", " " + key + " " + intent.getExtras().get(key));
if (key.equals("data")) {
String cnt = intent.getExtras().get(key).toString();
Gson gson = new GsonBuilder().setPrettyPrinting().create();
NotificationModel model = gson.fromJson(cnt, NotificationModel.class);
int badgeCount = model.getCount();
Log.e("uniq", " badge count " + badgeCount);
ShortcutBadger.applyCount(this, badgeCount);
Log.e("uniq", " " + "end");
}
} catch (Exception e) {
Log.e("uniqbadge", "zzm Custom_FirebaseMessagingService" + e.getMessage());
}
}
return super.zzE(intent);
}
Use this method, I m showing bagde to my app icon through this method from firebase when app is in killed state. You can send your data through intent and open your desired activity.

How to get message from GCM message body in android?

I have an app in which server sends some push notification using GCM server, The implementation is done on both side but i am facing problem is that i can't get notification from message body, it is always showing me "null". But i can see message in messag body using debug.
String message = bundle.getString("message");
Log.e(TAG, "onMessageReceived::" + message);
Log.e(TAG, "from::" + from);
and message body is :-
Bundle[{google.sent_time=1497866966996, google.message_id=0:1497866967011288%466cbbd8466cbbd8, notification=Bundle[{priority=high, body=Your wallet has been credited with 1.000 point(s)., title=Wallet credited}], collapse_key=com.s.baty}]
Try ,
Bundle notificationData = bundle.getBundle("notification");
String body = notificationData.getString("body");
It received correct data only
String bodymessage = bundle.getString("body");
Problem is print message after converting Sting
Log.e(TAG, "onMessageReceived::" + message.toString());
You can receive message in onMessage() function of GCMIntentService implementing class. I have created a function for getting proper message and key.
#Override
protected void onMessage(Context context, Intent intent) {
dumpIntent(intent);
}
public void dumpIntent(Intent i) {
Bundle bundle = i.getExtras();
if (bundle != null) {
Set<String> keys = bundle.keySet();
Iterator<String> it = keys.iterator();
while (it.hasNext()) {
String key = it.next();
Log.e("Intent Data", "[" + key + "=" + bundle.get(key) + "]");
}
}
}
After that you will easily set message with NotificationManager.

Is it possible to use Javamail to receive mails in Android

I'm learning Javamail these days following this website:
http://www.tutorialspoint.com/javamail_api/
I test the sending & added some extra stuff because it was on Android & it worked!
But things have changed completely when I tried to follow receiving email Tutorial which makes me wonder..
Is it possible to make this code :
https://www.tutorialspoint.com/javamail_api/javamail_api_fetching_emails.htm
works on android but using XML interface?!
You can use the following code:
public static void receiveEmail(String pop3Host, String storeType, user, String password) {
try {
//1) get the session object
Properties properties = new Properties();
properties.put("mail.pop3.host", pop3Host);
Session emailSession = Session.getDefaultInstance(properties);
//2) create the POP3 store object and connect with the pop server
POP3Store emailStore = (POP3Store) emailSession.getStore(storeType);
emailStore.connect(user, password);
//3) create the folder object and open it
Folder emailFolder = emailStore.getFolder("INBOX");
emailFolder.open(Folder.READ_ONLY);
//4) retrieve the messages from the folder in an array and print it
Message[] messages = emailFolder.getMessages();
for (int i = 0; i < messages.length; i++) {
Message message = messages[i];
System.out.println("---------------------------------");
System.out.println("Email Number " + (i + 1));
System.out.println("Subject: " + message.getSubject());
System.out.println("From: " + message.getFrom()[0]);
System.out.println("Text: " + message.getContent().toString());
}
//5) close the store and folder objects
emailFolder.close(false);
emailStore.close();
} catch (NoSuchProviderException e) {
e.printStackTrace();
} catch (MessagingException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
call your method passing some parameters:
String host = "pop.gmail.com";//change accordingly
String mailStoreType = "pop3";
String username= "example#gmail.com";
String password= "xxxxx";//change accordingly
receiveEmail(host, mailStoreType, username, password);
Source: Steps for receiving the email using JavaMail API

com.google.apphosting.api.ApiProxy$CancelledException: The API call urlfetch.Fetch() was explicitly cancelled. Code 503 App Engine Backend Error

I am using Google App Engine as backend for GCM. It is working fine except below error:
{ "error": { "errors": [ {
"domain": "global",
"reason": "backendError",
"message": "com.google.apphosting.api.ApiProxy$CancelledException: The API call urlfetch.Fetch() was explicitly cancelled." } ],
"code": 503, "message":
"com.google.apphosting.api.ApiProxy$CancelledException: The API call
urlfetch.Fetch() was explicitly cancelled." } }
To find cause I searched urlfetch.Fetch() method in my entire code, but I dint find it.
Does anyone got this same error before? If so then please tell me how you resolved it?
For more info, I added below code to send push notification for more than 1000 users.
private List<RegistrationRecord> regIdTrim(List<RegistrationRecord> wholeList, final int start) {
List<RegistrationRecord> parts = wholeList.subList(start,(start+1000)> wholeList.size()? wholeList.size() : start+1000);
return parts;
}
/**
* Send to the first 1000 devices (You can modify this to send to any number of devices or a specific device)
*
* #param message The message to send
*/
public void sendMessage(#Named("message") String message) throws IOException {
int count = ofy().load().type(RegistrationRecord.class).count();
if(count<=1) {
List<RegistrationRecord> records = ofy().load().type(RegistrationRecord.class).limit(count).list();
sendMsg(records,message);
}else
{
int msgsDone=0;
List<RegistrationRecord> records = ofy().load().type(RegistrationRecord.class).list();
do {
List<RegistrationRecord> regIdsParts = regIdTrim(records, msgsDone);
msgsDone+=1000;
sendMsg(regIdsParts,message);
}while(msgsDone<count);
}
}
private void sendMsg(List<RegistrationRecord> records,#Named("message") String msgToSend) throws IOException {
if (msgToSend == null || msgToSend.trim().length() == 0) {
log.warning("Not sending msgToSend because it is empty");
return;
}
Sender sender = new Sender(API_KEY);
// Message msg = new Message.Builder().addData("msgToSend", msgToSend).build();
Message msg = new Message.Builder().
addData("notification_title", msgToSend)
.addData("description","Check ").build();
// crop longer messages
if (msgToSend.length() > 1000) {
msgToSend = msgToSend.substring(0, 1000) + "[...]";
}
for (RegistrationRecord record : records) {
Result result = sender.send(msg, record.getRegId(), 5);
if (result.getMessageId() != null) {
log.info("Message sent to " + record.getRegId());
String canonicalRegId = result.getCanonicalRegistrationId();
if (canonicalRegId != null) {
// if the regId changed, we have to update the datastore
log.info("Registration Id changed for " + record.getRegId() + " updating to " + canonicalRegId);
record.setRegId(canonicalRegId);
ofy().save().entity(record).now();
}
} else {
String error = result.getErrorCodeName();
if (error.equals(Constants.ERROR_NOT_REGISTERED)) {
log.warning("Registration Id " + record.getRegId() + " no longer registered with GCM, removing from datastore");
// if the device is no longer registered with Gcm, remove it from the datastore
ofy().delete().entity(record).now();
} else {
log.warning("Error when sending msgToSend : " + error);
}
}
}
}
It looks like server is blocking you :/
I believe it has something to do with the 1000 network requests you're shooting at it.
Send the server a list of the 1000 ids you want to push to them, and let the server handle the pushes.

gData: get account(self contact) first and last name

I want to get first and last name of a google account using gdata library. I have the auth token(I take it from android device - send it to my java servlet- then should add an insert into a mysql db with first, last, display name and provider_uid(provider_uid is the form of https://www.google.com/accounts/o8/id?id=AItOawmyn...)).
I used Contacts feed like this(without success):
public String tryGoogleAuthentication(String auth_token){
ContactsService contactsService = new ContactsService("...");
contactsService.setUserToken(auth_token);
//contactsService.setAuthSubToken(auth_token);
ContactFeed feed = null;
try {
feed = contactsService.getFeed(new URL("https://www.google.com/m8/feeds/contacts/" + "someEmail#gmail.com" + "/full?max-results=10000"), ContactFeed.class);
} catch (IOException e) {
e.printStackTrace();
return CONST.GOOGLE_AUTH_INVALID_TOKEN;
} catch (ServiceException e) {
e.printStackTrace();
return CONST.GOOGLE_AUTH_INVALID_TOKEN;
} catch (NullPointerException e) {
e.printStackTrace();
return CONST.GOOGLE_AUTH_INVALID_TOKEN;
}
if (feed == null)
return "";
String externalId = feed.getId();
Person person = feed.getAuthors().get(0);
String email = person.getEmail();
String name = person.getName();
String nameLang = person.getNameLang();
String extensionLocalName = person.getExtensionLocalName();
String uri = person.getUri();
System.out.println("externalId: " + externalId);
System.out.println("email: " + email);
System.out.println("name: " + name);
System.out.println("nameLang: " + nameLang);
System.out.println("extension local name: " + extensionLocalName);
System.out.println("URI: " + uri);
System.out.println(feed.getSelf().getEntries().get(0).getTitle().getPlainText());
return CONST.STATUS_OK;
}
Also,
System.out.println("ID: " + feed.getSelf().getEntries().get(0).getId());
will output:
ID: http://www.google.com/m8/feeds/contacts/someEmail%40gmail.com/base/c....
but I want something like this:
https://www.google.com/accounts/o8/id?id=AItOawmyn...
I need this to insert into an existing data base.
Please note that I want the info only for the account, not for it's contacts.
Thanks,
Alex
Please see this answer from google groups for resolution. The problem is that I cannot access user profile with the auth_token taken from the android because it's a Client Login token, and Client Login does not have a scope for accessing user's profile. I integrated OAUTH login in android like this and with the token returned, I can access user's profile.
Alex.

Categories

Resources