I have seen this question, and although my problem seems similar, I have everything set up properly, here's the relevant java:
Parse.initialize(this, "MY_KEY", "MY_KEY");
ParseInstallation.getCurrentInstallation().saveInBackground();
ParsePush.subscribeInBackground("", new SaveCallback() {
#Override
public void done(ParseException e) {
// callback to confirm subscription
if (e == null) {
Log.d("com.parse.push", "successfully subscribed to the broadcast channel.");
} else {
Log.e("com.parse.push", "failed to subscribe for push", e);
}
}
});
Anyways, looking at my dashboard on parse.com the subscription is being recognized and when I attempt to send the push it says "sending to 2 devices" (my phone and a virtual machine). It then shows up with a green check mark on the list of sent pushes BUT under "pushes sent" it says 0.
It also seems that sometimes, deviceToken and pushType are not being set properly, but there hasn't been any difference in effect whether these are present are not, although I'm assuming they are necessary.
How is not sending any pushes to subscribed devices a success?
My manifest can be found here
Considering that all the XML manifest is correct, try this:
> Parse.initialize(this, "MY_KEY", "MY_KEY");
> ParseAnalytics.trackAppOpenedInBackground(getIntent());
> ParsePush.subscribeInBackground("");//Optionaly put your callback
> PushService.startServiceIfRequired(getApplicationContext());
>
> ParseInstallation.getCurrentInstallation().saveInBackground();
Related
I will try to show personal single notification on my phone tray, but I can't rich, so help.
I am having an issue with FireBase Cloud Messaging in which I get the Token from the device and send the notification test through the Google Firebase notification console, however, the notification is never logged nor pushed to the android virtual device. The documentation for FCM is almost exactly the code that I have below and little else in the way of what else you would have to do to get push notifications working with firebase. I have gone through all of the setup information (build.gradle additions, Installing google play services, etc...) as specified in the documentation, but still do not have messages generating. What is wrong with the code that I am not receiving my push notifications to the logcat or the device? Please let me know any further information that would be helpful. Thanks.
mRegistrationBroadcastReceiver = new BroadcastReceiver() {
#Override
public void onReceive(Context context, Intent intent) {
if (intent.getAction().equals(Config.REGISTRATION_COMPLETE)) {
FirebaseMessaging.getInstance().subscribeToTopic(Config.TOPIC_GLOBAL);
displayFirebaseRegId();
} else if (intent.getAction().equals(Config.PUSH_NOTIFICATION))
{
String message = intent.getStringExtra("message");
Toast.makeText(getApplicationContext(), "Push notification: " + message, Toast.LENGTH_LONG).show();
txtMessage.setText(message);
}
}
};
displayFirebaseRegId();
}
private void displayFirebaseRegId() {
SharedPreferences pref = getApplicationContext().getSharedPreferences(Config.SHARED_PREF, 0);
String regId = pref.getString("regId", null);
Log.e(TAG, "Firebase reg id: " + regId);
if (!TextUtils.isEmpty(regId))
txtRegId.setText("Firebase Reg Id: " + regId);
else
txtRegId.setText("Firebase Reg Id is not received yet!");
}
#Override
protected void onResume() {
super.onResume();
LocalBroadcastManager.getInstance(this).registerReceiver(mRegistrationBroadcastReceiver,
new IntentFilter(Config.REGISTRATION_COMPLETE));
LocalBroadcastManager.getInstance(this).registerReceiver(mRegistrationBroadcastReceiver,
new IntentFilter(Config.PUSH_NOTIFICATION));
NotificationUtils.clearNotifications(getApplicationContext());
}
#Override
protected void onPause() {
LocalBroadcastManager.getInstance(this).unregisterReceiver(mRegistrationBroadcastReceiver);
super.onPause();
}
And I will add lib of fire base messaging is:
compile 'com.google.firebase:firebase-messaging:11.0.4'
You don't need to subscribe inside the BroadcastReceiver you can just do it inside the onTokenRefresh method in the FirebaseInstanceIdService
You don't need to get the push notification in the BroadcastReceiver, you have to do it inside the onMessageReceive in the FirebaseMessagingService
FCM is extremely unreliable with emulators, simply use a real device, I have struggled with this and in some cases I even get the notification days later when opening the emulator for other projects, test this with real phones
I am a little bit confusing on integrating FCM (Firebase cloud messaging) push notification on my application.
Normally, Rather than the Intent services other services are not stopped anymore in the middle. I have created my message receiving service by extending to the FirebaseMessagingService as follow
public class MyFirebaseMessagingService extends FirebaseMessagingService {
#Override
public void onMessageReceived(RemoteMessage remoteMessage) {
Log.e(TAG, "From: " + remoteMessage.getFrom());
if (remoteMessage == null)
return;
// Check if message contains a notification payload.
if (remoteMessage.getNotification() != null) {
Log.e(TAG, "NotificationBean Body: " + remoteMessage.getNotification().getBody());
//This method is responsible for handling notification
handleNotification(remoteMessage.getNotification().getBody());
}
// Check if message contains a data payload.
if (remoteMessage.getData().size() > 0) {
Log.e(TAG, "Data Payload: " + remoteMessage.getData().toString());
try {
JSONObject json = new JSONObject(remoteMessage.getData().toString());
handleDataMessage(json);
} catch (Exception e) {
Log.e(TAG, "Exception: " + e.getMessage());
}
}
}
}
and registered the service on manifest as follow:
<service android:name=".service.MyFirebaseMessagingService">
<intent-filter>
<action android:name="com.google.firebase.MESSAGING_EVENT" />
</intent-filter>
</service>
This service is run on when the app is live and running in the background too. But when the app is not in the background the service is not run anymore.
I have registered the service on Main Activity as follow
#Override
protected void onResume() {
super.onResume();
// register GCM registration complete receiver
LocalBroadcastManager.getInstance(this).registerReceiver(mRegistrationBroadcastReceiver,
new IntentFilter(Config.REGISTRATION_COMPLETE));
// register new push message receiver
// by doing this, the activity will be notified each time a new message arrives
LocalBroadcastManager.getInstance(this).registerReceiver(mRegistrationBroadcastReceiver,
new IntentFilter(Config.PUSH_NOTIFICATION));
// clear the notification area when the app is opened
NotificationUtils.clearNotifications(getApplicationContext());
}
#Override
protected void onPause() {
super.onPause();
}
Let me know anything wrong in my code. (Possibly not) .Why notifications are not running on background. How do I overcome this issue?
Thanks in advance.
use your server data or api like this
{
"to" : "deviceToken",
"notification" : {
"body" : "Pass body here",
"title" : "Title n",
"icon" : " icon ",
"sound" : "notification sound "
}
}
//for exa.
$fields=array('to'=>fdfdfdfdsfdsdfdfdsfdsfdfdsfd" ,'notification'=>array('title'=>'mytitle','body'=>$title,'click_action'=>'abc','icon'=>'ic_stat_final','sound'=>'default','color'=>'#00aff0'),'data'=>array('ghmid'=>$hgmid,'page'=>$page));
If your data is of type notification ie "Notification"then the onReceived method is not supposed to be get called when app is in background. Though it can be retrived when app comes to foreground. If it is of type data then it will get called.Change your type to "Data" instead of notification. Also when you change the data to type "Data" your getNotification() method may not work and app will get null pointer exception. Server data can also be of type where it has both "data" and "notification".
change json object key from notification to data
e.g
{
“to”: “device_ID/fcmID”,
“notification”: {
“body”: “great match!”,
“title”: “Portugal vs. Denmark”,
“icon”: “myicon”
}
}
change to
{
“to”: “device_ID/fcmID”,
“data”: {
“Nick”: “abc”,
“body”: “nfjwhhwruguig”,
“Room”: “cnrughwriugg”
},
}
Client app receives a data message in onMessageReceived() irrespective of the fact whether app is in foreground or background.
ref: https://blog.talentica.com/2017/01/20/firebase-cloud-messaging-in-android/
I have done a lot of reading on Parse push notifications. I have push notifications working perfectly if the app is running or sitting in the background (user gets out of the app by pushing the home button or back button). I know I cannot get notifications to appear if the app has been force quit but if I close the app/force quit the app, is there a way to get the notifications to pop up the next time the app opens?
I have implemented MainApplication and made sure my manifest is correct but if the app is completely closed, then I do a push notification from Parse and then go to open the app it is as if it has not received it and never will display. Is that normal behavior?
Thanks,
Adam
Main Application
public class MainApplication extends Application {
private static MainApplication instance = new MainApplication();
public MainApplication()
{
instance=this;
}
public static Context getContext()
{
return instance;
}
#Override
public void onCreate() {
super.onCreate();
Parse.enableLocalDatastore(this);
//initialise whatson from parse.com
Parse.initialize(this, "xxxxx", "xxxxx");
PushService.setDefaultPushCallback(this, MainActivity.class);
//to register device to get push notifications and register the install
ParsePush.subscribeInBackground("", new SaveCallback() {
#Override
public void done(ParseException e) {
if (e == null) {
Log.d("com.parse.push", "successfully subscribed to the broadcast channel.");
} else {
Log.e("com.parse.push", "failed to subscribe for push", e);
}
}
});
ParseInstallation.getCurrentInstallation().saveInBackground();
}
}
I am trying to send a Parse Push Notification from one Android application to all others.
The following is the set-up code in my Application object:
Parse.enableLocalDatastore(this);
ParseObject.registerSubclass(Game.class);
Parse.initialize(this, "code", "code");
ParsePush.subscribeInBackground(ParseHelper.SUBSCRIPTION_CHANNEL_GAME);
The following is the Push Notification code:
ParsePush push = new ParsePush();
String message = "Hello";
push.setChannel(ParseHelper.SUBSCRIPTION_CHANNEL_GAME);
push.setMessage(message);
push.sendInBackground(new SendCallback() {
#Override
public void done(ParseException e) {
if (e == null) {
Toast.makeText(CreateGameActivity.this, "Success", Toast.LENGTH_LONG).show();
} else {
Toast.makeText(CreateGameActivity.this, "Failed", Toast.LENGTH_LONG).show();
}
}
});
break;
}
Even though the Success Toast is called, I still don't see the Notification appearing on any of the two Android devices I have installed the app on.
I have tested the Push Notifications via www.parse.com's Dashboard and that does work. Why won't it work in my app though?
To send notifications from a device, you have to do one extra step. Go into the settings of your app on parse and enable Client Push. That should resolve your issue.
We are using parse to store chat messages and we are using notification of parse.
For iOS we are doing this to create entry in installation table of parse.. It's creating entry in installation table of parse, which i think is must to receive notification.
PFInstallation *currentInstallation = [PFInstallation currentInstallation];
currentInstallation.deviceToken = user.notificationToken;
[currentInstallation saveInBackground];
But in android I am not able to create entry in installation table.
I am not receiving notification from parse and I think this is the reason behind not getting notification..
Is this the case?
Can any one guild me to the right path ?
UPDATE
Now receiving notification but still having some doubts.
I am doing this when user logs in. I have put conditions if user is not created then only create otherwise don't. I haven't added it to this because that's not necessary
// setting up parse installation
private void setUpParseInstallation()
{
ParseInstallation currentInstallation = ParseInstallation
.getCurrentInstallation();
currentInstallation.saveInBackground(new SaveCallback()
{
#Override
public void done(com.parse.ParseException e)
{
if (e != null)
{
Log.e(TAG, "Error saving parse installation");
}
}
});
}
// add user to parse it it doesn't exist otherwise handle the cases
private void addUserToParseIfNotExisting()
{
// if user doesn't exist create a new user
ParseObject newuser = new ParseObject("user");
newuser.put("name", email);
newuser.put("userId", id);
newuser.saveInBackground();
}
private void setChannel()
{
channel = "abdf";
RS_User user = new RS_User(this);
ParseQuery<ParseObject> pquery = ParseQuery.getQuery("user");
pquery.whereEqualTo("userId", user.getUserId());
// see if user exists in user table on parse
pquery.findInBackground(new FindCallback<ParseObject>()
{
#Override
public void done(List<ParseObject> list,
com.parse.ParseException error)
{
if (list.size() > 0)
{
list.get(i).put("channels", channel);
list.get(i).saveInBackground();
PushService.subscribe(getApplicationContext(),channel, RS_HelpActivity.class);
}
}
});
}
Sending a notification
ParsePush push = new ParsePush();
if(object.get(k).has("channels"))
{
push.setChannel(object.get(k).getString(
"channels"));
}
push.setData(dataAndroid);
push.sendInBackground();
Currently I am doing all this to send/receive notification using Parse. Is there a way to do without using channel and directly using notification token or something else using parse ? Because I will be having user notification token.
I hope this code will help you
Application.java
public class Application extends android.app.Application {
public Application() {
}
#Override
public void onCreate() {
super.onCreate();
// Initialize the Parse SDK.
Parse.initialize(this, "your applicationId", "your clientKey");
// Specify an Activity to handle all pushes by default.
PushService.setDefaultPushCallback(this, MainActivity.class);
}
}
AndroidManifest.xml
<application
android:name="<Your Package Name>.Application"
android:allowBackup="true"
android:icon="#drawable/ic_launcher"
android:label="#string/app_name"
android:theme="#style/AppTheme" >
Have you tried to use advanced targeting to send a notification to any installation with a device token which matches a contained in (in) query (or any other condition you need).
Something like this:
ParseQuery<ParseInstallation> query = ParseInstallation.getQuery();
query.whereEqualTo("your_key", "your_value");
// OR any of whereXXX method
ParsePush push = new ParsePush();
push.setData(dataAndroid);
push.setQuery(query);
push.sendInBackground();
EDIT
ParseInstallation as others ParseObject(s) has put method.
Since in Android you haven't a UDID like iOS you have to figure out how to create something similiar. Unfortunately I cannot send you how we generate "ours" device token, but here you can find valid suggestions.
ParseInstallation install = ParseInstallation.getCurrentInstallation();
install.put("device-token", yourGeneratedDeviceId);
install.saveInBackground(new SaveCallback() { ... });