QuickBlox not delivering GCM notifications to subscribed devices. I tried sending notification message from Admin Panel too, but it isn't delivered to device, but still in Admin Panel it shows it as "sent". But no history available.
And also what could be the reason for this ? How to mitigate this ?
How to view sent GCM notifications.
The admin panel is not good enough - it lies sometime by saying 'send successfully' but it never reaches the other end.
Try sending the GCM notification by using the code snippet provided in the documentation. It works always.
public void sendMessageOnClick() {
// Send Push: create QuickBlox Push Notification Event
QBEvent qbEvent = new QBEvent();
qbEvent.setNotificationType(QBNotificationType.PUSH);
qbEvent.setEnvironment(QBEnvironment.DEVELOPMENT);
// generic push - will be delivered to all platforms (Android, iOS, WP, Blackberry..)
qbEvent.setMessage("how are you doing");
StringifyArrayList<Integer> userIds = new StringifyArrayList<Integer>();
userIds.add(6132691);
qbEvent.setUserIds(userIds);
QBMessages.createEvent(qbEvent, new QBEntityCallbackImpl<QBEvent>() {
#Override
public void onSuccess(QBEvent qbEvent, Bundle bundle) {
}
#Override
public void onError(List<String> strings) {
// errors
}
});
}
//OR the below:--
private void sendPushNotifications(){
// recipients
StringifyArrayList<Integer> userIds = new StringifyArrayList<Integer>();
userIds.add(6114793);
//userIds.add(960);
QBEvent event = new QBEvent();
event.setUserIds(userIds);
event.setEnvironment(QBEnvironment.DEVELOPMENT);
event.setNotificationType(QBNotificationType.PUSH);
event.setPushType(QBPushType.GCM);
HashMap<String, String> data = new HashMap<String, String>();
data.put("data.message", "Hello");
data.put("data.type", "welcome message");
event.setMessage(data);
QBMessages.createEvent(event, new QBEntityCallbackImpl<QBEvent>() {
#Override
public void onSuccess(QBEvent qbEvent, Bundle args) {
// sent
}
#Override
public void onError(List<String> errors) {
}
});
}
Related
I've searched in the web, parse docs and ask many people but no one can point me how to do it.
I have an RSS app who getting the articles into a UITableView.
when I'm sending a Push it's open the app itself but not the article I want to (well obviously since I don't know how to code that) .
Can anyone please give me ideas how to do it ?
(code sample will be useful as well) .
First of all you have to implement your own Receiver class instead of default Parse push receiver and put it into AndroidManifest.xml as follows :
<receiver android:name="net.blabla.notification.PushNotifHandler" android:exported="false">
<intent-filter>
<action android:name="net.bla.PUSH_MESSAGE" />
</intent-filter>
</receiver>
In your PushNotifHandler.java class you should put some parameters to Intent you will throw as follows :
public class PushNotifHandler extends BroadcastReceiver{
private static final String TAG = PushNotifHandler.class.getSimpleName();
private static int nextNotifID = (int)(System.currentTimeMillis()/1000);
private static final long VIBRATION_DURATION = 500;
#Override
public void onReceive(Context context, Intent intent) {
try {
String action = intent.getAction();
Intent resultIntent = new Intent(context, ToBeOpenedActivity.class);
JSONObject jsonData = new JSONObject(intent.getExtras().getString("com.parse.Data"));
fillNotificationData(jsonData, action, resultIntent);
String title = jsonData.getString("messageTitle") + "";
String message = jsonData.getString("messageText") + "";
TaskStackBuilder stackBuilder = TaskStackBuilder.from(context);
stackBuilder.addParentStack(ToBeOpenedActivity.class);
stackBuilder.addNextIntent(resultIntent);
PendingIntent resultPendingIntent =
stackBuilder.getPendingIntent(
0,
PendingIntent.FLAG_UPDATE_CURRENT
);
Notification notification;
NotificationCompat.Builder builder = new NotificationCompat.Builder(context).
setSmallIcon(R.drawable.icon).
setContentTitle(title).
setContentText(message).
setAutoCancel(true);
builder.setContentIntent(resultPendingIntent);
notification = builder.getNotification();
NotificationManager mNotificationManager = (NotificationManager) context.getSystemService(Context.NOTIFICATION_SERVICE);
mNotificationManager.notify(TAG, nextNotifID++, notification);
vibratePhone(context);
} catch (Exception e) {
Log.d(TAG, "Exception: " + e.getMessage());
}
}
private void vibratePhone(Context context) {
Vibrator vibrator = (Vibrator) context.getSystemService(Context.VIBRATOR_SERVICE);
vibrator.vibrate(VIBRATION_DURATION);
}
private void fillNotificationData(JSONObject json, String action, Intent resultIntent)
throws JSONException {
Log.d(TAG, "ACTION : " + action);
resultIntent.putExtra("paramString", json.getString("paramFromServer"));
}
}
With key "com.parse.Data" you will get parameters sent from your server code as json format.After getting paramString and paramBoolean parameters from this json, you will put these parameters into new Intent you hav created as seen in fillNotificationData method.
Other parts of onReceive method creates a local notification and vibrates the device.
Finally on your activity class onResume() method you will check intent parameters to realize if you are opening the app from push notification or not.
#Override
public void onResume() {
super.onResume();
checkPushNotificationCase(getIntent());
}
private void checkPushNotificationCase(Intent intent) {
Bundle extraParameters = intent.getExtras();
Log.d("checking push notifications intent extras : " + extraParameters);
if (extraParameters != null) {
if(extraParameters.containsKey("paramString")) {
// doSomething
}
}
}
I hope you have asked this question for Android :))
I am writing an app which has GCM in it. I am not trying to compete with Whatsapp. It should just a sort of bulletin board between all those who use this app.
The app is opened with a menu of buttons and one of them directs the user to the Messages activity.
As long as you stay on this activity, the messages are there and everything works as it should be.
But, if I go back to the menu activity and then go back into the messages activity, then all messages are gone and are not shown.
I am using ListActivity for the messages and the onCreate function, destroys the current list each time it is read.
My question is, how can I return to the messages activity without loosing them? I want to have it as in Whatsapp, when you go into Whatsapp the messages are always there!
I thought of saving the messages list into a file and then read it (or let's say the last 40-50 messages) anytime the onCreate is called. Is this a good solution? Is there any solution without saving the list to a file?
Here is some of my code inside the messages activity:
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_msg_main);
Intent in = getIntent();
username = in.getStringExtra("username");
password = in.getStringExtra("password");
nickname = in.getStringExtra("nickname");
messages = new ArrayList<Message>();
txtNewMsg = (EditText) this.findViewById(R.id.text);
adapter = new MessagesAdapter(this, messages);
setListAdapter(adapter);
registerReceiver(mHandleMessageReceiver, new IntentFilter(DISPLAY_MESSAGE_ACTION));
}
private final BroadcastReceiver mHandleMessageReceiver = new BroadcastReceiver() {
#Override
public void onReceive(Context context, Intent intent) {
String newMessage = intent.getExtras().getString(EXTRA_MESSAGE);
// Waking up mobile if it is sleeping
WakeLocker.acquire(getApplicationContext());
SimpleDateFormat sdf = new SimpleDateFormat("dd/MM/yyyy HH:mm:ss");
String currentDateandTime = sdf.format(new Date());
Spanned newMessageDate = Html.fromHtml("<small><i><font color=\"red\">" + currentDateandTime + "</font></i></small>" + " " + "<small><i><font color=\"blue\">" + nickname + "</font></i></small>" + "<br />" + newMessage);
addNewMessage(new Message(newMessageDate, true));
WakeLocker.release();
}
};
#Override
protected void onDestroy() {
if (mRegisterTask != null) {
mRegisterTask.cancel(true);
}
try {
unregisterReceiver(mHandleMessageReceiver);
GCMRegistrar.onDestroy(this);
} catch (Exception e) {
Log.e("UnRegister Receiver Error", "> " + e.getMessage());
}
super.onDestroy();
}
void addNewMessage(Message m)
{
messages.add(m);
adapter.notifyDataSetChanged();
getListView().setSelection(messages.size()-1);
}
The code includes: onCreate, BroadcastReceiver (GCM receiver), onDestroy and addNewMessage which adds the new message to the messages list.
Thanks for any help!
AJ
Create database with message table and users table which will store the message and users details.
Now whenever new message is come store in database and then when you open the app load limited message from table. If the app is open and message is come first store in your database and add to your list object and invalidate your listview.
im trying to launch application form notification using Android Edk. I succeded to display notification. But i want to launch my application from notification and i can`t make it work.
Notification is received when application is not running, is triggered from a broadCast reciever.
I think my problem is related to the activity that i created from notification intent.
Here the notification function:
Intent resultIntent = new Intent(context, TaskManagerActivity.class);
resultIntent.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK | Intent.FLAG_ACTIVITY_SINGLE_TOP);
PendingIntent resultPendingIntent = PendingIntent.getActivity( context, 0, resultIntent, 0);
NotificationCompat.Builder mBuilder = new NotificationCompat.Builder(context )
.setSmallIcon(R.drawable.ic_menu_day)
.setContentTitle(title)
.setContentText(message)
.setContentIntent(resultPendingIntent)
.setWhen(System.currentTimeMillis());
NotificationManager manager = (NotificationManager) context.getSystemService(Context.NOTIFICATION_SERVICE);
manager.notify(0, mBuilder.build());
And here is my activity class:
public class TaskManagerActivity extends Activity
{
public static TaskManagerActivity m_Activity;
private static final String TAG = "TaskManagerActivity";
protected void onCreate(Bundle savedInstanceState)
{
super.onCreate(savedInstanceState);
// setContentView(R.layout.main);
}
}
Have a look at official docs of Android about notification. Also I'd suggest you to read this post of SO.
I have developed a small console application to test EWS StreamingSubscriptions / Notifications. In the past we used Push Notifications but ,in theory, when using StreamingNotifications I should be able to avoid creating a listener http endpoint and all the trouble with it (firewall, etc.).
So, from my local machine; I'm doing this:
static void Main(string[] args)
{
if (String.IsNullOrEmpty(ConfigurationManager.AppSettings["PrimaryLabUserId"]))
{
throw new ArgumentNullException("Please provide a value for PrimaryLabUserId in app.config");
}
_primaryLabUserId = ConfigurationManager.AppSettings["PrimaryLabUserId"];
string ServiceAccountName = ConfigurationManager.AppSettings["ExchangeServiceAccountName"];
string ServiceAccountPassword = ConfigurationManager.AppSettings["ExchangeServiceAccountPassword"];
_service = new ExchangeService(ExchangeVersion.Exchange2010_SP2);
_service.Credentials = new WebCredentials(ServiceAccountName, ServiceAccountPassword);
_service.AutodiscoverUrl(_primaryLabUserId, (x) => true);
_ewsUrl = _service.Url.AbsoluteUri;
var _connection = new StreamingSubscriptionConnection(_service, 30);
var sub = SubscribeForStreamingNotifications();
_connection.AddSubscription(sub);
_connection.OnDisconnect +=
new StreamingSubscriptionConnection.SubscriptionErrorDelegate(OnDisconnect);
// set up subscriptions here.
_connection.OnNotificationEvent +=
new StreamingSubscriptionConnection.NotificationEventDelegate(OnNewMail);
_connection.Open();
Console.WriteLine("Listening streaming...");
Console.ReadLine();
}
public static StreamingSubscription SubscribeForStreamingNotifications()
{
var folderIds = new List<FolderId>()
{
WellKnownFolderName.Inbox,
WellKnownFolderName.Calendar
};
var eventTypes = new List<EventType>();
eventTypes.Add(EventType.NewMail);
eventTypes.Add(EventType.Deleted);
eventTypes.Add(EventType.Moved);
eventTypes.Add(EventType.Created);
eventTypes.Add(EventType.Modified);
return _service.SubscribeToStreamingNotifications(folderIds, eventTypes.ToArray());
}
private static void OnNewMail(object sender, NotificationEventArgs args)
{
var test = args;
Console.WriteLine("Incoming");
}
The Subscription initializes OK, but when I send a new mail to the LabUser nothing happens. The Notification Event never fires. I tried the same with pushnotifications and it was working (on another server with a public http endpoint for exchange to call back).
I was wondering if this might have anything to do with my local machine.
How very stupid of me. I forgot to impersonate. Since I'm calling into EWS with a service account it is of course listening on the mailbox of that account unless you specify:
_service.ImpersonatedUserId = new ImpersonatedUserId(ConnectingIdType.SmtpAddress, _primaryLabUserId);
I am using the solution from the ServiceStack Re-usability use case project.
To this solution I have added a new console app which contains the code below.
With the original Re-usability use-case project, when an EmailMessage is published it was handled by a subscriber which sent an email (i.e. SMessageService.Any(EmailMessage request).
When I run the console app, which means I have two applications that are subscribing to the EmailMessage, only the new console app receives the message.
I have the following:
My console app is:
class Program
{
static void Main(string[] args)
{
var subscriberHost = new SubscriberHost();
subscriberHost.Init();
Console.WriteLine("Waiting of publishing
to happen on EmailMessage as we are subscribing to it...");
Console.ReadLine();
}
}
public class SubscriberHost : AppHostHttpListenerBase
{
private RedisMqServer mqHost;
public SubscriberHost()
:base("Subscriber console",typeof(EmailMessageEventHandler).Assembly)
{
}
public override void Configure(Container container)
{
var redisFactory = new PooledRedisClientManager("localhost:6379");
mqHost = new RedisMqServer(redisFactory, retryCount:2);
mqHost.RegisterHandler<EmailMessage>((message) =>
{
var emailMessage = message.GetBody();
Console.WriteLine(emailMessage.To);
Console.WriteLine(emailMessage.Subject);
Console.WriteLine(emailMessage.Body);
return new SMessageReceipt {
Type = "not used",
To = "test",
From = "Reusability",
RefId = "1,"
};
});
// mqHost.RegisterHandler<EmailMessage>(ServiceController.ExecuteMessage);
mqHost.Start();
}
}
I was expecting both subscribers to receive the EmailMessage but only the new console app is receiving it. Why isn't the other subscriber receiving the message?
The client code that does the publishing has not been modified.
What I have shown above is using Redis MQ, and for the multiple subscribers problem I was testing I need the Redis Pub/Sub.
For MQ, a subscriber takes the message off the queue to process. Once processed, that is it.
For Pub/Sub, there could be many subscribers and each will receive a copy of the message.
I hope this helps others.