Unable to send messages to multiple recipients through Sinch in Android App - android

I have tried sending a Sinch message in my Android app and it works perfectly when sending to a single recipient
MyClass
String userId= "abc";
CustomReplyMessageBuild customMessage = new CustomReplyMessageBuild();
customMessage.setRecepientIDs(userId);
Map<String, String> m1 = new HashMap<String, String>();
m1.put(“param1", "YES");
m1.put(“param2”, 123);
m1.put(“param3", time);
customMessage.setHeaders(m1);
messageService.sendMessage(customMessage);
MyBean
private List<String> RecepientIds = new ArrayList<String>();
private Map map;
private void setHeaders(Map map) {
this.map = map;}
private void setRecepientIDs(String id) {
this.RecepientIds.add(id);
}
MyService
private MessageClient messageClient = client.getMessageClient();
public void sendMessage(MyClass.CustomReplyMessageBuild conf_message){`
if(messageClient != null){
WritableMessage message = new WritableMessage(conf_message);
messageClient.send(message);
}
}
But when i try passing a list of recipient ids (for a broadcast sort of feature) , i am unable to receive the message at the other end .
MyBroadcastClass
List<String> broadcastIdList;
String recepId = "a,b,c";
CustomReplyMessageBuild customMessage = new CustomReplyMessageBuild();
broadcastIdList = Arrays.asList(recepId.split(","));
customMessage.setRecepientIdList(broadcastIdList);
Map<String, String> m1 = new HashMap<String, String>();
m1.put(“param1", "YES");
m1.put(“param2”, 123);
m1.put(“param3", time);
customMessage.setHeaders(m1);
messageService.sendMessage(customMessage);
MyBroadcastBean
private List<String> RecepientIds = new ArrayList<String>();
private Map map;
private void setHeaders(Map map) {
this.map = map;}
private void setRecepientIdList(List<String> idList) {
this.RecepientIds.addAll(idList);
}
Please let me know if you spot an error or can post a sample snippet or link to solve this problem.
Thanks a ton!

To send messages to multiple recipients try the following constructor:
// Create a WritableMessage and send to multiple recipients
WritableMessage message = new WritableMessage(
{"recipient user id 1", "recipient user id 2"},
"Hello recipients! How are you?");
// Send it
messageClient.send(message);

Related

Creating a real time notification from android service

I am creating an application which shows the notification as soon as I post a new post on wordpress site.
Now the notification is generated as soon as I put a post on the wordpress site.
But after 40-45 minutes the app gets crashed and gets killed in the background with the following error:-
the error that showed after the app crashes
I have tried many solutions none of it worked.
I don't want to use firebase for the notification.
I have to fetch the data in real time from the wordpress and then create the notification.
This is the following code for generating the notification:-
private void setupNotificationListener(){
StringRequest request = new StringRequest(Request.Method.GET, url, new Response.Listener<String>() {
#Override
public void onResponse(String s) {
flag=1;
//System.out.println(flag);
gson = new Gson();
list = (List) gson.fromJson(s, List.class);
postTitle = new String[list.size()];
postContent=new String[list.size()];
System.out.println("shiv class:"+list.size());
for(int i=0;i<list.size();++i) {
mapPost = (Map<String, Object>) list.get(i);
mapTitle = (Map<String, Object>) mapPost.get("title");
postTitle[i] = (String) mapTitle.get("rendered");
mapContent = (Map<String, Object>) mapPost.get("content");
postContent[i] = (String) mapContent.get("rendered");
}
if(!alreadyNotified(postTitle[0])){
Log.d("not notified","");
createNotif(postContent[0],postTitle[0]);
saveNotificationKey(postTitle[0]);
}else{
System.out.print("already notified");
}
}
}, new Response.ErrorListener() {
#Override
public void onErrorResponse(VolleyError volleyError) {
Log.d("Error","Error");
}
});
rQueue = Volley.newRequestQueue(NotifierService.this);
rQueue.add(request);
NotifierService.getInstance().getRequestQueue().getCache().clear();
}
You create the requestQueue from a timer, so every 5 seconds. And within your executed code you create always a new request queue. This won't work you should keep the requestQueue as final global variable and create it only once in your constructor.
public class NotifierService extends Service {
private final RequestQueue rQueue;
NotifierService() {
this.rQueue = Volley.newRequestQueue(this);
}
private void setupNotificationListener() {
// do your request handling
}
}
The OutOfMemoryError might occur because you create so many objects which are not correctly garbage collected

gmail-api marking as "read"

Using gmail-api I am trying to mak a message as "read" as below but it s not working.
ModifyMessageRequest mods = new ModifyMessageRequest()
.setRemoveLabelIds(new ArrayList<String>(Arrays.asList("UNREAD")));
com.google.api.services.gmail.model.Message message = null;
try {
message = mService.users().messages().modify(acct.sEmail, gmsailID, mods).execute();
} catch (IOException e) {
e.printStackTrace();
}
}
The argument for setRemoveLabelIds() is not the Label String but the Label ID.
So get the label ID from the code below and use that in your function
List<String> labels = new ArrayList<String>();
ListLabelsResponse listResponse = service.users().labels().list(userId).execute();
for (Label label : listResponse.getLabels()) {
Label countLabel = service.users().labels().get(userId, label.getId()).execute();
if (countLabel.getName().equalsIgnoreCase("UNREAD"))
unreadId = countLabel.getId();
}
List<String> add = new ArrayList<String>();
List<String> remove = new ArrayList<String>();
remove.add(unreadId);
modifyMessage(service, userId, message.getId(), add, remove);
public static void modifyMessage(Gmail service, String userId, String messageId,
List<String> labelsToAdd, List<String> labelsToRemove) throws IOException {
ModifyMessageRequest mods = new ModifyMessageRequest().setAddLabelIds(labelsToAdd)
.setRemoveLabelIds(labelsToRemove);
Message message = service.users().messages().modify(userId, messageId, mods).execute();
}
Here is one that I use (after getting messageId with ListMessagesResponse):
public void modifyMessage(String userId, String messageId) throws IOException {
List<String> lblIDRemove=new ArrayList<String>();
lblIDRemove.add("UNREAD");
ModifyMessageRequest mods = new ModifyMessageRequest()
.setAddLabelIds(null)
.setRemoveLabelIds(lblIDRemove);
Message message = mService.users().messages().modify(userId, messageId, mods).execute();
}

How to send Time Triggered Notification using parse.com in Android?

I have implemented push notification using parse. But I want to send notification to user at specific time in their specific time-zones. I know that we can send notification to all devices at once from the dashboard. But can we trigger the notification from within the app?
Right now I just check the system date and display the data matching from my Parse class.
But I want to send a notification to the user at specific time!
Code to get system date!
Calendar c = Calendar.getInstance();
SimpleDateFormat df = new SimpleDateFormat("ddMMyyyy");
final String formattedDate = df.format(c.getTime());
Code that checks date and displays relevant info!
ArrayList<HashMap<String, String>> _temparrayList = HelperFile
.loadArrayListFromFile(MainActivity.this, HelperFile.DAILYVERSE);
if (_temparrayList != null) {
for (int i = 0; i < _temparrayList.size(); i++) {
HashMap<String, String> map = _temparrayList.get(i);
if (formattedDate.equals(map.get("date"))) {
verse = map.get("verse");
book = map.get("book");
book_text.setText(book);
verse_text.setText(verse);
} else if (new_formattedDate.equals(map.get("date"))) {
verse = map.get("verse");
book = map.get("book");
book_text.setText(book);
verse_text.setText(verse);
}
else {
value = true;
new RemoteDataTask().execute();
}
}
} else {
verse_text.setText("Data Yet To Update, Please Refresh");
refresh.setVisibility(View.VISIBLE);
new RemoteDataTask().execute();
}
The Async task that makes the query from Parse!
private class RemoteDataTask extends AsyncTask<Void, Void, Void> {
#Override
protected void onPreExecute() {
super.onPreExecute();
if (value == false) {
mProgressDialog = new ProgressDialog(MainActivity.this);
mProgressDialog.setTitle("Daily Verse Is Updating");
mProgressDialog.setMessage("Loading...");
mProgressDialog.setIndeterminate(false);
mProgressDialog.show();
}
}
#Override
protected Void doInBackground(Void... params) {
// Locate the class table named "Country" in Parse.com
ParseQuery<ParseObject> query = new ParseQuery<ParseObject>(
"DailyVerse");
query.orderByDescending("date");
try {
ob = query.find();
} catch (ParseException e) {
Log.e("Error", e.getMessage());
e.printStackTrace();
}
return null;
}
#Override
protected void onPostExecute(Void result) {
// Retrieve object "name" from Parse.com database
ArrayList<HashMap<String, String>> arrayList = new ArrayList<HashMap<String, String>>();
for (ParseObject country : ob) {
HashMap<String, String> map = new HashMap<String, String>();
String book = (String) country.get("book");
String verse = (String) country.get("verse");
String date = (String) country.get("date").toString();
map.put("book", book);
map.put("verse", verse);
map.put("date", date);
arrayList.add(map);
}
HelperFile.writeArrayListToFile(arrayList, MainActivity.this,
HelperFile.DAILYVERSE);
if (value == false) {
mProgressDialog.dismiss();
}
}
}
So the QUESTION is How will I send a notification to the user everyday at 8:00 AM?
You're going to build a kind of "worker" or "job" within your android application. I think it's not the best option. But to do a "kind" of this, you should implement +service and call startService method. I've already used Parse and I normally send user notifications by push firing by my webservice, and my worker/job is in my webservice(back-end application).
Hope it could be useful for you! =)

Passing object from one activity from another activity

I like to pass object from one activity from another activity. I implemented Serializable.
But somehow, the object is not passed and at the receiver side I get NULL.
Can pls check where is wrong?
public class TrackerInfo implements Serializable{
/**
*
*/
private static final long serialVersionUID = 1L;
String Idnumber;
String Simcardnumber;
String Description;
String Model;
String time;
public String getSimcardnumber() {
return Simcardnumber;
}
public String getDescription() {
return Description;
}
public String getModel() {
return Model;
}
public void setModel(String model) {
this.Model = model;
}
public String getTime() {
return time;
}
public void setInforFromCursor(Cursor cursor){
this.Idnumber = cursor.getString(1);
this.Simcardnumber = cursor.getString(2);
this.Description = cursor.getString(3);
this.Model = cursor.getString(4);
this.time = cursor.getString(5);
}}
At sender side,
#Override
public void itemSelected(String id) {
//get Tracker info
dbHelper = new TrackerDBAdapter(this);
dbHelper.open();
Cursor cursor = dbHelper.fetchListByIDNum(id);
TrackerInfo tracker = new TrackerInfo();
tracker.setInforFromCursor(cursor);
dbHelper.close();
LinkedHashMap<String, Object> obj = new LinkedHashMap<String, Object>();
obj.put("TRAKCER", tracker);
Bundle b = new Bundle();
b.putSerializable("bundleobj", obj);
Intent intent = new Intent(this, DetailMapView.class);
intent.setFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP);
intent.putExtra("bundleobj", b);
startActivity(intent);
}
At receiver side,
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
//setContentView(R.layout.activity_detail_map_view);
try { setContentView(R.layout.activity_detail_map_view);
Bundle bn = new Bundle();
bn = getIntent().getExtras();
HashMap<String, Object> getobj = new HashMap<String, Object>();
getobj = (HashMap<String, Object>) bn.getSerializable("bundleobj");
trackerinfo = (TrackerInfo) getobj.get("TRACKER");
} catch (Exception e) {
Log.e("Err", e.getMessage());
}}
I think that your problem is here:
obj.put("TRAKCER", tracker);
You are adding tracker to HashMap with key TRAKCER
But here:
getobj.get("TRACKER");
You are trying to get object with key TRACKER but keys are not equal and this is reason of NPE. You need to fix
obj.put("TRACKER", tracker);
Now keys are equal so it should works.
Update:
As #Sam pointed out you wrapped your HashMap into Bundle and Bundle into Intent. So if your approach had work you need to do following:
LinkedHashMap<String, Object> obj = new LinkedHashMap<String, Object>();
obj.put("TRACKER", tracker);
Bundle b = new Bundle();
b.putSerializable("trackerObj", obj);
Intent intent = new Intent(this, DetailMapView.class);
intent.setFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP);
intent.putExtra("bundleObj", b);
And for retrieving HashMap:
Bundle wrapper = getIntent().getBundleExtra("bundleObj"); // this Bundle contains HashMap
HashMap<String, Object> obj = (HashMap<String, Object>) wrapper.getSerializable("trackerObj");
Recommendation:
How #Sam pointed out again, better and cleaner way is to wrap directly your HashMap as Serializable into Intent with putExtra("trackerObj", obj) method and then easily retrieve it as
HashMap<String, Object> o = (HashMap<String, Object>) getIntent().getSerializableExtra("trackerObj");
You have a few mistakes, please read Sajmon's answer, but you are also putting a Bundle in a Bundle, but only reading from the outer Bundle. Remove code like this:
Bundle b = new Bundle();
b.putSerializable("bundleobj", obj);
And put the data directly into the Intent:
Intent intent = new Intent(this, DetailMapView.class);
intent.setFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP);
intent.putExtra("bundleobj", obj);
// You may need to help the compiler by casting it to a Serializable
//intent.putExtra("bundleobj", (Serializable) obj);
In order to use your double Bundle method you need to fetch both "bundleobj" tags:
bn = getIntent().getExtras().getBundle("bundleobj");
HashMap<String, Object> getobj = (HashMap<String, Object>) bn.getSerializable("bundleobj");

Hebrew letters are empty

I am building an app which needs to support Hebrew letters (שלום). I am sending a message thru GCM (Google Cloud Messaging). Whenever my OnMessage is called the string (Hebrew) that I am receiving is empty.
Is there any easy workaround for this? Thanks in advance!
protected void onMessage(Context context, Intent intent) {
String message = intent.getStringExtra(GCM_COMMAND);
String action = intent.getAction();
if ("com.google.android.c2dm.intent.RECEIVE".equals(action)) {
message = intent.getStringExtra(GCM_COMMAND);
String s = message.toString();
ItemBean ib =parseJson(s,context);
}
private ItemBean parseJson(String text,Context con) {
ItemBean item = null;
if (text != null) {
JSONObject temp;
try {
temp = new JSONObject(text);
String itemMessage = temp.get(GCM_MESSAGE).toString();
//This String is Empty!
String itemDate = temp.get(GCM_DATE).toString();
long currentTime = System.currentTimeMillis();
item = new ItemBean(currentTime,itemMessage,itemDate);
sendNotification(con,itemMessage,itemDate);
}
}
return item;
}
Server code from NetBeans
JSONObject json = new JSONObject();
System.out.println("******גגגגגגשלום*********");
json.put(GCM_MESSAGE, ib.getmMessage());
//This is hebrew no problem!
json.put(GCM_DATE, ib.getmDate());
Message.Builder builder = new Message.Builder();
Message message = builder.build();
MulticastResult result = sender.send(message, listOfRegisteredDevices, 5);
int success = result.getSuccess();
Can you try :
String itemMessage = temp.getString(GCM_MESSAGE);
and also
json.put(GCM_MESSAGE, JSonObject.quote( ib.getmMessage() ) );

Categories

Resources