Parse.com Receiving push notifications even after Logout -Android - android

I've made an app that uses Parse to send push notifications to other devices when the user is logged into his account. The problem is that the users still receive pushes even after they've logged out.
A method to fix this would be awesome.
Here's the code i use to register the device.
public void registerPushNotification() {
ParseInstallation installation = ParseInstallation.getCurrentInstallation();
installation.put("user", mCurrentUser);
installation.saveInBackground();
}
Thanks in advance!

Try this (code is in Swift, but I think it's the same)
PFUser.logOut()
PFInstallation.currentInstallation().removeObjectForKey("user")
PFInstallation.currentInstallation().saveInBackground()

Try by calling the ParseInstallation.getCurrentInstallation().deleteInBackground() at the time of logout.

I suggest using channels, with channels you can get some sort of control of pushes and so on.
The method signature is like this
ParsePush.subscribeInBackground("Name of my channel", SaveCallback cb);
Try using this when the user logs in:
ParsePush.subscribeInBackground("my_channel", new SaveCallback() {
#Override
public void done(ParseException e) {
if (e == null) {
// Great
} else {
// Something wrong happened...
}
}
});
Use this when user logs out:
ParsePush.unsubscribeInBackground("my_channel");
When sending pushes query for all users who (are still) subscribed to the "my_channel" channel:
ParsePush push = new ParsePush();
push.setChannel("my_channel");
push.setMessage("Message to the subscribers of the channel!");
push.sendInBackground();
Make sure to check out Parse guide and docs.
Cheers!

Related

Firebase Cloud Messaging - Handling logout

How do I handle situation, when user logs out of my application and I no longer want him to receive notifications to the device.
I tried
FirebaseInstanceId.getInstance().deleteToken(FirebaseInstanceId.getInstance().getId(), FirebaseMessaging.INSTANCE_ID_SCOPE)
But I still receive the notifications to my device's registration_id.
I also made sure that this is the token I should delete:
FirebaseInstanceId.getInstance().getToken(FirebaseInstanceId.getInstance().getId(), FirebaseMessaging.INSTANCE_ID_SCOPE)
or simply FirebaseInstanceId.getInstance().getToken()).
I also tried FirebaseInstanceId.getInstance().deleteInstanceId(), but then the next time I call FirebaseInstanceId.getInstance.getToken I receive null (it works on the second try).
I guess, after deleteInstanceId I could immediately call getToken() again, but it looks like a hack. And also there's this answer which states that it shouldn't be done, but it proposes deleting the token which apparently doesn't work.
So what is the right method to handle this?
Okay. So I managed to do some testing and have concluded the following:
deleteToken() is the counterpart of getToken(String, String), but not for getToken().
It only works if the Sender ID you are passing is a different Sender ID (not the same ID that can be seen in your google-services.json). For example, you want to allow a different Server to send to your app, you call getToken("THEIR_SENDER_ID", "FCM") to give them authorization to send to your app. This will return a different registration token that corresponds only to that specific sender.
In the future, if you chose to remove their authorization to send to your app, you'll then have to make use of deleteToken("THEIR_SENDER_ID", "FCM"). This will invalidate the corresponding token, and when the Sender attempts to send a message, as the intended behavior, they will receive a NotRegistered error.
In order to delete the token for your own Sender, the correct handling is to use deleteInstanceId().
Special mentioning this answer by #Prince, specifically the code sample for helping me with this.
As #MichałK already doing in his post, after calling the deleteInstanceId(), getToken() should be called in order to send a request for a new token. However, you don't have to call it the second time. So long as onTokenRefresh() onNewToken() is implemented, it should automatically trigger providing you the new token.
For short, deleteInstanceId() > getToken() > check onTokenRefresh() onNewToken().
Note: Calling deleteInstanceId() will not only delete the token for your own app. It will delete all topic subscriptions and all other tokens associated with the app instance.
Are you positive you're calling deleteToken() properly? The value for audience should be (also seen from my answer that you linked) is "set to the app server's sender ID". You're passing the getId() value which is not the same as the Sender ID (it contains the app instance id value). Also, how are you sending the message (App Server or Notifications Console)?
getToken() and getToken(String, String) returns different tokens. See my answer here.
I also tried FirebaseInstanceId.getInstance().deleteInstanceId(), but then the next time I call FirebaseInstanceId.getInstance.getToken I receive null (it works on the second try).
It's probably because the first time you're calling the getToken(), it's still being generated. It's just the intended behavior.
I guess, after deleteInstanceId I could immediately call getToken() again, but it looks like a hack.
Not really. It's how you'll get the new generated (provided that it is already generated) token. So I think it's fine.
I did a brief research on what would be the most elegant solution to get back the full control (subscribe and unsubscribe to FCM) as before. Enable and disable the FCM after the user logged in or out.
Step 1. - Prevent auto initialization
Firebase now handle the InstanceID and everything else which need to generate a registration token. First of all you need to prevent auto initialization. Based on the official set-up documentation you need to add these meta-data values to your AndroidManifest.xml:
<?xml version="1.0" encoding="utf-8"?>
<application>
<!-- FCM: Disable auto-init -->
<meta-data android:name="firebase_messaging_auto_init_enabled"
android:value="false" />
<meta-data android:name="firebase_analytics_collection_enabled"
android:value="false" />
<!-- FCM: Receive token and messages -->
<service android:name=".FCMService">
<intent-filter>
<action android:name="com.google.firebase.MESSAGING_EVENT"/>
</intent-filter>
</service>
</application>
Now you disabled the automatic token request process. At the same time you have an option to enable it again at runtime by code.
Step 2. - Implement enableFCM() and disableFCM() functions
If you enable the auto initialization again then you received a new token immediately, so this is a perfect way to implement the enableFCM() method.
All subscribe information assigned to InstanceID, so when you delete it then initiate to unsubscribe all topic. On this way you able to implement disableFCM() method, just turn back off auto-init before you delete it.
public class FCMHandler {
public void enableFCM(){
// Enable FCM via enable Auto-init service which generate new token and receive in FCMService
FirebaseMessaging.getInstance().setAutoInitEnabled(true);
}
public void disableFCM(){
// Disable auto init
FirebaseMessaging.getInstance().setAutoInitEnabled(false);
new Thread(() -> {
try {
// Remove InstanceID initiate to unsubscribe all topic
// TODO: May be a better way to use FirebaseMessaging.getInstance().unsubscribeFromTopic()
FirebaseInstanceId.getInstance().deleteInstanceId();
} catch (IOException e) {
e.printStackTrace();
}
}).start();
}
}
Step 3. - FCMService implementation - token and message receiving
In the last step you need to receive the new token and send direct to your server.
Other hand you'll receive your data message and just do it what you want.
public class FCMService extends FirebaseMessagingService {
#Override
public void onNewToken(String token) {
super.onNewToken(token);
// TODO: send your new token to the server
}
#Override
public void onMessageReceived(RemoteMessage remoteMessage) {
super.onMessageReceived(remoteMessage);
String from = remoteMessage.getFrom();
Map data = remoteMessage.getData();
if (data != null) {
// TODO: handle your message and data
sendMessageNotification(message, messageId);
}
}
private void sendMessageNotification(String msg, long messageId) {
// TODO: show notification using NotificationCompat
}
}
I think this solution is clear, simple and transparent. I tested in a production environment and it's works. I hope it was helpful.
I was working on the same problem, when I had done my logout() from my application. But the problem was that after logging out, I was still getting push notifications from Firebase. I tried to delete the Firebase token. But after deleting the token in my logout() method, it is null when I query for it in my login() method. After working 2 days I finally got a solution.
In your logout() method, delete the Firebase token in the background because you can not delete Firebase token from the main thread
new AsyncTask<Void,Void,Void>() {
#Override
protected Void doInBackground(Void... params) {
try
{
FirebaseInstanceId.getInstance().deleteInstanceId();
} catch (IOException e)
{
e.printStackTrace();
}
return null;
}
#Override
protected void onPostExecute(Void result) {
// Call your Activity where you want to land after log out
}
}.execute();
In your login() method, generate the Firebase token again.
new AsyncTask<Void,Void,Void>() {
#Override
protected Void doInBackground(Void... params) {
String token = FirebaseInstanceId.getInstance().getToken();
// Used to get firebase token until its null so it will save you from null pointer exeption
while(token == null) {
token = FirebaseInstanceId.getInstance().getToken();
}
return null;
}
#Override
protected void onPostExecute(Void result) {
}
}.execute();
Developers should never unregister the client app as a mechanism for
logout or for switching between users, for the following reasons:
A registration token isn't associated with a particular logged in user. If the client app unregisters and then re-registers, the app can
receive the same registration token or a different registration token.
Unregistration and re-registration may each take up to five minutes to propagate. During this time messages may be rejected due to the
unregistered state, and messages may go to the wrong user. To make
sure that messages go to the intended user:
The app server can maintain a mapping between the current user and the registration token.
The client app can then check to ensure that messages it receives match the logged in user.
this quote is from a deprecated google documentation
But there is reasons to believe this is still true - even if the documentation above is deprecated.
You can observe this here - check out how they do it in this codelab https://github.com/firebase/functions-samples/blob/master/fcm-notifications/functions/index.js
and here
https://github.com/firebase/friendlychat-web/blob/master/cloud-functions/public/scripts/main.js
Since the getToken() is deprecated, use getInstanceId() to regenerate new token instead. It has same effect.
public static void resetInstanceId() {
new Thread(new Runnable() {
#Override
public void run() {
try {
FirebaseInstanceId.getInstance().deleteInstanceId();
FirebaseInstanceId.getInstance().getInstanceId();
Helper.log(TAG, "InstanceId removed and regenerated.");
} catch (IOException e) {
e.printStackTrace();
}
}
}).start();
}
Use this methods.
This is my solution, and I referred this at here
When you sign-up, use initFirebaseMessage,. and when log-out or delete
use removeFirebaseMessage().
private fun removeFirebaseMessage(){
CoroutineScope(Dispatchers.Default).launch {
FirebaseMessaging.getInstance().isAutoInitEnabled = false
FirebaseInstallations.getInstance().delete()
FirebaseMessaging.getInstance().deleteToken()
}
}
private fun initFirebaseMessage(){
val fcm = FirebaseMessaging.getInstance()
fcm.isAutoInitEnabled = true
fcm.subscribeToTopic("all")
fcm.subscribeToTopic("")
}
Another handy way to clear the firebase token and regenerated a new one using FirebaseMessaging.getInstance()
fun clearFirebaseToken() {
FirebaseMessaging.getInstance().apply {
deleteToken().addOnCompleteListener { it ->
Log.d("TAG++", "firebase token deleted ${it.result}")
token.addOnCompleteListener {
Log.d("TAG++", "firebase token generated ${it.result}")
if (it.result != null) saveTokenGenerated(it.result!!)
}
}
}
}
Just call deleteToken method on a background Thread upon Logout:
https://firebase.google.com/docs/reference/android/com/google/firebase/iid/FirebaseInstanceId.html#public-void-deletetoken-string-senderid,-string-scope
FirebaseInstanceId.getInstance().deleteToken(getString(R.string.gcm_defaultSenderId), "FCM")
The first argument takes the SenderID as it is defined in your FireBaseConsole
It takes a few seconds to update - and after that, you will no longer get FCM notifications.
I know I am late for the party. deleteInstanceId() should be called from the background thread since it's a blocking call. Just check the method deleteInstanceId() in FirebaseInstanceId() class.
#WorkerThread
public void deleteInstanceId() throws IOException {
if (Looper.getMainLooper() == Looper.myLooper()) {
throw new IOException("MAIN_THREAD");
} else {
String var1 = zzh();
this.zza(this.zzal.deleteInstanceId(var1));
this.zzl();
}
}
You can start an IntentService to delete the instance id and the data associated with it.
The firebase.iid package that contains FirebaseInstanceId is now deprecated. Auto-initialization has been migrated from Firebase Instance ID to Firebase Cloud Messaging. Also its behaviour has slighly changed. Before, a call to deleteInstanceId() would automatically generate a new token if auto-initialization was enabled. Now, the new token is only generated on the next app-start or if getToken() is called explicitly.
private suspend fun loginFCM() = withContext(Dispatchers.Default) {
val fcm = FirebaseMessaging.getInstance()
fcm.isAutoInitEnabled = true
fcm.token.await()
}
private suspend fun logoutFCM() = withContext(Dispatchers.Default) {
val fcm = FirebaseMessaging.getInstance()
fcm.isAutoInitEnabled = false // To prevent a new token to be generated automatically in the next app-start (remove if you don't care)
fcm.deleteToken().await()
}
If you want to logout completely from Firebase you can just delete the whole installation afterwards:
private suspend fun logoutFirebase() = withContext(Dispatchers.Default) {
logoutFCM()
val firebase = FirebaseInstallations.getInstance()
firebase.delete().await()
}
To wrap it all up, use background thread to delete the instanceID, the next time you login keep an eye on the Firestore/Realtime DB (if you save your tokens there), they will refresh
public void Logout() {
new Thread(){
#Override
public void run() {
super.run();
try {
FirebaseInstanceId.getInstance().deleteInstanceId();
FirebaseInstanceId.getInstance().getInstanceId();
} catch (final IOException e) {
runOnUiThread(new Runnable() {
#Override
public void run() {
Toast.makeText(Flags.this, e.getMessage(), Toast.LENGTH_SHORT).show();
}
});
}
}
}.start();
FirebaseMessaging.getInstance().setAutoInitEnabled(false);
FirebaseAuth.getInstance().signOut();
SharedPreferences sharedPreferences = getDefaultSharedPreferences(Flags.this);
SharedPreferences.Editor editor = sharedPreferences.edit();
editor.clear();
editor.apply();
startActivity(new Intent(Flags.this, MainActivity.class));
Flags.this.finish();
}
This code below I used it and it helps me, and I used Kotlin coroutine instead of Thread(Runnable{}).start() because it less cost than creating a new thread object
private fun logoutFromFCM() {
GlobalScope.launch(Dispatchers.IO) {
FirebaseInstallations.getInstance().delete()
FirebaseMessaging.getInstance().deleteToken()
FirebaseMessaging.getInstance().token.addOnCompleteListener(OnCompleteListener { task ->
if (!task.isSuccessful) {
Log.w(TAG, "Fetching FCM registration token failed", task.exception)
return#OnCompleteListener
}
// Get new FCM registration token
val token = task.result
saveFirebaseToken(token)
Log.w(TAG, "Token Updated - newToken> $token")
})
}
}
For many situations where the notifications requirements are simple, the issue of handling log out can be implemented much more easily. For example, in my case every user is subscribed to only two topics:
Global alerts topic
User specific topic defined as the users email (with replacement of # with - because # is not allowed in topic string)
For such simple scenarios simply unsubscribe from the unwanted topics on log out:
Future<void> signOut() async {
messaging.unsubscribeFromTopic(emailToTopic(_firebaseAuth.currentUser.email));
await _firebaseAuth.signOut();
}
And of course subscribe to topics only on successful log in or sign up:
Future<String> signIn({String email, String password}) async {
try {
await _firebaseAuth.signInWithEmailAndPassword(
email: email, password: password);
messaging.subscribeToTopic(emailToTopic(email));
return "Signed in";
} on FirebaseAuthException catch (e) {
return e.message;
}
}

Unable to subscribe channel in Parse from Android device

I am developing an Android application and using Parse for push notification. Currently I have a problem when registering new device. I've used the code below to subscribe my Android phone on a specific channel on Parse server.
final String channel = "myapp_" + userId;
ParsePush.subscribeInBackground(channel, new SaveCallback() {
#Override
public void done(ParseException e) {
if (e != null) {
e.printStackTrace();
ParsePush.subscribeInBackground(channel, new SaveCallback() {
#Override
public void done(ParseException e) {
Log.e("Subscribe", e == null ? "Success" : "Failure");
}
});
} else {
Log.e("Subscribe", "Success");
}
}
});
I have a strange problem on this:
The device can be registered to Parse for the 1st time after installing apps to phone (my device has already subscribed a channel successfully) but the GCM does not return the device token. Even after I wait for a long time, but nothing good happen. Unless I quit and re-open the apps, then GCM returns device token. I don't know where is the difference between them: the 1st time using apps vs reopen apps.
Have anyone got this problem? And can you give me any suggestion to solve this?
I found the reason: the Parse registration must be proceed at onCreate action of base Application class. Then the deviceToken will be retrieved normally on Parse server.

Parse.com android - disable push notifications

I've started using parse.com to receive push notifications in my application.
It works perfectly, but I have a couple of questions.
We perform registration, but unused channels, as follows:
ParsePush.subscribeInBackground("", new SaveCallback() {
#Override
public void done(ParseException e) {
if (e == null) {
Log.d("dmode", "Oks!");
} else {
Log.e("dmode", "Fail :(", e);
}
}
});
My first question is:
I find no way to disable receiving push notifications
I searched the official documentation and stackoverflow, but I find solutions that do not work for me.
I tried:
ParsePush.unsubscribeInBackground("", new SaveCallback() {
#Override
public void done(ParseException e) {
if (e == null) {
Log.d("dmode", "unsuscribe oks");
} else {
Log.e("dmode", "unsuscribe fail", e);
}
}
});
Unsuccessfully, I have also tried:
ParsePush.unsubscribeInBackground("");
...but not work.
I'm not using channels, that is why the quotes are empty:
ParsePush.subscribeInBackground("", new SaveCallback() { //...
How I can enable and disable push notifications?
The second query is that sometimes receive duplicate notifications until two three times at once on the same device.
Someone has been the same?
Thank you very much for the help.
Greetings!
I think you should use a name for a default channel even if you are not using channels and not the empty string "".
Also have a look here Parse Question
I quote from the answer on the above link
If you called PushService.setDefaultCallback, call it again passing null as the class.

Android Basic Push Notification Send from client side doesn't work

I'm looking for some help with push notifications on Android.
Situation:
I'm trying to do a push send from an Android device, at this time for itself ( will understand later) but when I hit the send button nothing happens
Config:
Firstly, yes, the client side push is enabled.
Secondly my onCreate method in the "extends Application" class
public void onCreate() {
super.onCreate();
//Parse
//Parse.enableLocalDatastore(this);
Parse.initialize(this, "", "");
ParseObject.registerSubclass(Groups.class);
ParseObject.registerSubclass(Users.class);
//Subscribe to push
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);
}
}
});
// Save the current Installation to Parse.
ParseInstallation.getCurrentInstallation().saveInBackground();
}
My button to send the push notification ( its the basic code from the docs )
sendReqBtn.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
System.out.println("Debug push onclick");
ParsePush push = new ParsePush();
push.setChannel("");
push.setMessage("The Giants just scored! It's now 2-2 against the Mets.");
push.sendInBackground(new SendCallback() {
#Override
public void done(ParseException e) {
System.out.println("Push send done");
}
});
}
});
All other settings set by the basic android tutorial (Like manifest and basic sdk adding, I already use other parse functions)
So after this code snippets added to my app I hoped that I will get a notification on the device itself as described earlier, but nothing happens. From the parse push dashboard I tried it, and it works fine (thats why I think the manifest and other things are configured well) and in the core panel on the dashboard i can see the installation in the list and the "" mark in the channels array.
Can anyone help me out?
Thanks in advance!!
Steve

Parse Push on Android not sending

I'm developing an app for Android,which have a push notification system that uses Parse (https://www.parse.com).
I've already setup the Parse on my app exactly as they instructs on their tutorials, and it is working - if I send the notifications "manually" from the Parse panel, it is received with no problems.
But when I try to send the push notifications from inside the app, the pushes never gets to it's destination channel, and it does not show up in the Parse logs either.
Take a look on my code:
public class Application extends android.app.Application {
public Application() {
}
#Override
public void onCreate() {
super.onCreate();
Parse.initialize(this, "MY_CODE", "MY_OTHER_CODE");
ParsePush.subscribeInBackground("");
ParsePush push = new ParsePush();
push.setChannel( "my_example_channel" );
push.setMessage( "Test message" );
push.sendInBackground( new SendCallback() {
#Override
public void done(com.parse.ParseException e) {
if (e == null) Log.d("push", "success!");
else Log.d("push", "failure");
}
});
}
The callback returns null - no errors are shown and it logs "success", and the other mobile that I'm using to test the app is subscribed to the "my_example_channel" - it receives notifications if I send them through the Parse Dashboard.
I've also tried to put the "Push send code" (the previous code, without the "Parse.initialize..." and "parsePush.subscribeInBackground..." parts) on a Button click, and on an "onCreate" method of an Activity, but the result is the same.
I believe I solved it! It seems that you have to enable Client Side Push in your Parse Settings. Settings > Push > Client push enabled? >Yes. I was struggling with it all last night!!

Categories

Resources