firebase / quickstart-android

Firebase Quickstart Samples for Android
https://firebase.google.com
Apache License 2.0
8.82k stars 7.32k forks source link

Can Firebase console push notification if apps is closed? (User swipe away with the long click menu) #41

Closed jamesytl closed 8 years ago

jamesytl commented 8 years ago

I have tried developing a firebase notification apps with this MyFirebaseMessagingService link and MyFirebaseInstanceIDService link example that will receive notification from the console. However, if I close the apps by swiping away the app from the task manager, the app will no longer be able to receive any notification.

I have tried using a service that return START_STICKY and using it to start the MyFirebaseMessagingService but still couldn't receive any notification.

Is this how the firebase push notification intended to perform or am I doing it wrongly?

Extra Info. : My apps is working if I only click back but not if I swipe it away in task manager.

syahnurizal commented 7 years ago

@shomronh I'm not sure either because google also suggest to use FCM. By the way, I'm in the middle of asking them what is the best way to solve this issue. I will update here again after they reply.

shomronh commented 7 years ago

@syahnurizal Great ! Thanks a lot.

shomronh commented 7 years ago

@syahnurizal
actually I'm testing Google Cloud Messaging and same thing on my hyawei device push notifications works only when the app is running, and on a simulator running recent android version it's working when the app is closed manually. any solution about that ? is a broadcast receiver can resolve this ?

shomronh commented 7 years ago

actually this seems to happen on device like huawei and other....

syahnurizal commented 7 years ago

@shomronh

This is the latest answer from Google support:

I cannot recommend any particular logic for this as it is up to the developer on how to implement it. As my extent is only with specific, technical questions for Firebase, I would recommend you to reach out to the community like Stackoverflow. Members of the developer community as well as the Firebase team are active participants there and might be able to provide you guidance and best practices for this.

shomronh commented 7 years ago

@syahnurizal yep it means what it means .....

Thanks a lot.

marchy commented 7 years ago

Thanks so much for posting that @syahnurizal.

What's absolutely crazy about this answer is that the entire point of push notifications is that they are PUSH. Having a pre-requisite that the app is in a non-stopped state for them to be received is just scary. What, shutting down your phone means that now you need to re-launch any app you want to get a notification from? Might as well just send SMS messages to everyone on Android - since seems it's the only reliable delivery mechanism of letting someone.

I guess having not invented the push mechanism they never really quite "got it". And with the entire mis-architecture of the Android system as a whole they had to make a concession and kill push notifications in trade-off for trying to reduce the battery issues that the overly-permissive Android architecture created in the first place.

Overall this is just unacceptable – imagine the impact on brand effectiveness and missed user behaviour that these mis-decisions have created.

syahnurizal commented 7 years ago

@marchy Totally agree with your point. I told them exactly like what you said. Unfortunately, thats what they reply.

lelloman commented 7 years ago

Thanks for sharing this info @syahnurizal. I do not totally agree with @marchy though, the idea of the "stopped" state is that the app is shut down until the user actively interact with it. If the user is annoyed by your app and wants to silence it, (s)he should have a way to do that. If notification were shown after the user clicked on "force stop" from the device settings, it would go against the purpose of "force stop".

The problem is that some manufacturer are blocking notification even if the user has not stopped the app. This is messed up because both the user and the developer (well, and the developer's boss) might not expect this behavior. If the app process is killed (swipe recent activity, developer option, activity manager, memory pressure) push messages are delivered. Besides aggressive manufacturers, I think that what Android has failed so far is to make it clear what being in a "stopped" state means.

And then, there is still an open question, how is Whatsapp able to show notification when in stopped state?

syahnurizal commented 7 years ago

@lelloman

As explained by Google, apps like whatapps, facebook etc.

If you see though that other apps (such as Whatsapp, Gmail) are receiving messages, those apps may have been included in the list of the manufacturer's white-listed apps that are allowed to receive notifications in the background (not prematurely stopped).

lelloman commented 7 years ago

@syahnurizal this doesn't answer my question, FCM says that they won't show notification for stopped app because they respect Android's policy. but I do see a notification from Whatsapp even if it is in stopped state, not background. The explanation by Google was about apps that are swiped and still allowed to receive notifications in those particular devices. Google says that if the app is stopped (not background) it shouldn't receive a notification but Whatsapp in stopped state can still show one. How is this possible?

alex-marochko commented 7 years ago

@lelloman AFAIK, 'stopped' (not in background) and 'force stopped' are very different states. At 'original' android stopping app (swiping from background) doesn't mean force stopping. But for MIUI and others does, if your app is not from whitelist like Whatsapp.

owaremx commented 7 years ago

As I said, I tested with a Huawei phone with emui and I had to whitelist my app to continue receiving notifications, maybe it is the same behaviour in other phones like xiaomi

lelloman commented 7 years ago

@alex-marochko if you click force stop from settings the app will go in "stopped" state. Same as "force stopped". Whatsapp is able to reanimate itself from stopped state, I checked also the Intents with dumpsys activity broadcasts and it is receiving an Intent from FCM. Stock android 8 on a Pixel. According to FCM support, if Whatsapp is in stopped state no Intent will be delivered to it, now I'm wondering, how is it possible that Whatsapp is getting out of stopped state just in time to receive the FCM push? Is it hacking it's way out of stopped state or is it Google itself that is reanimating it?

Mt question is not actually relevant for this github issue

Sanjay-Ghadge commented 6 years ago

@alex-marochko Its about permission. On your phone go to Security>Permissions>Autostart and allow your app to autostart

syahnurizal commented 6 years ago

@Sanjay-Ghadge Yes, it is related to that. But it is impossible to tell each of the user to enable the autostart by themselves.

marchy commented 6 years ago

Lesson from all this: use SMS. Push notifications are a large fail.

raphaelkohn commented 6 years ago

Just giving my contribuition here. I'm using a Motorola E2 with Android 6 (pretty old hum)... So.. what happened was the following... I killed the app by swiping in the Recent Apps screen. Logcat stopped and everything. After 4 minutes... Logcat started again saying that my App was being started for Firebase Notifications.

11-16 16:34:35.057 2357-4404/? I/ActivityManager: Killing 28351:com.elektro.elektrofacil/u0a162 (adj 9): remove task 11-16 16:34:35.145 2357-5730/? I/WindowState: WIN DEATH: Window{a85adbf u0 com.elektro.elektrofacil/com.elektro.elektrofacil.MainActivity} 11-16 16:34:39.123 2357-2392/? I/ActivityManager: Start proc 28733:com.elektro.elektrofacil/u0a162 for broadcast com.elektro.elektrofacil/com.google.firebase.iid.FirebaseInstanceIdReceiver

Recommend waiting a little after killing the process to verify. We tend to be too anxious about stuff. In my case, LogCat was connected and was searching for stuff when suddenly I saw the notification in the Notification Tray (a Data Payload)... After that I searched my app in the recents and could not find it... After that I searched my LogCat for info... and found those lines above... Saved my day. Hope you find it useful.

egigi commented 6 years ago

Got the same problem but resolved fortunately... Some phone have an option tha kill some apps when the screen is turnd off to save further battery power. H30-U10 have a fetures that looks like the following:

device-2017-12-09-192808

I fixed the problem enabling FCM app under Protected apps

device-2017-12-09-192622

Hope this help! Cheers :)

hoanganhtuan95ptit commented 6 years ago

Fix bug not receive notification FCM in OPPO

I found a solution that uses an AlarmManager to trigger a firebase listener

Demo

// MainActivity.start(this,message);

    Intent intent = new Intent(this, MainActivity.class);
    intent.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK);

    PendingIntent pendingIntent = PendingIntent.getActivity(this, 0, intent, PendingIntent.FLAG_ONE_SHOT);
    Uri defaultSoundUri = RingtoneManager.getDefaultUri(RingtoneManager.TYPE_NOTIFICATION);

    NotificationCompat.Builder notificationBuilder = new NotificationCompat.Builder(this)
            .setSmallIcon(R.mipmap.ic_launcher)
            .setContentTitle("Tuấn Đẹp Trai")
            .setContentText(message)
            .setAutoCancel(true)
            .setSound(defaultSoundUri)
            .setContentIntent(pendingIntent);

    NotificationManager notificationManager = (NotificationManager) getSystemService(Context.NOTIFICATION_SERVICE);
    notificationManager.notify(0, notificationBuilder.build());
}

}

*  JobSchedulerReceiver
```java
public class JobSchedulerReceiver extends BroadcastReceiver {

    @Override
    public void onReceive(final Context context, Intent intent) {

        DemoFirebaseMessagingService.start(context);

        AlarmManager alarmManager = (AlarmManager) context.getSystemService(Context.ALARM_SERVICE);

        Intent mIntent = new Intent();
        mIntent.setAction("com.hoanganhtuan95ptit.JobSchedulerReceiver");
        PendingIntent pendingIntent = PendingIntent.getBroadcast(context, 0, mIntent, 0);

        if (alarmManager == null) return;
        if (Build.VERSION.SDK_INT >= 19) {
            alarmManager.setExact(AlarmManager.RTC_WAKEUP, System.currentTimeMillis() + 2 * 60 * 1000, pendingIntent);
        } else {
            alarmManager.set(AlarmManager.RTC_WAKEUP, System.currentTimeMillis() + 2 * 60 * 1000, pendingIntent);
        }
    }
}
martinadamec commented 6 years ago

@hoanganhtuan95ptit I´m using phone with Android 5.1 API 22 (Huawei) and your solution not work. In Android Studio I have Android 5.1.1 API 22 (Nexus 5) and it works, even without your solution.

radityagumay commented 6 years ago

Hi, i also found similar issue when using Firebase. i am using Asus Zenphone. by default Asus Zenphone will disable app that being killed. EVERY SINGLE APP that disable will kill after app are being killed. Even you disable whatsapp, WhatsApp will won't work after app being killed.

Any Alarm, Service, Job Scheduler won't work for this case.

Any workaround for this?

On Wed, Jan 31, 2018 at 8:07 AM, Martin Adamec notifications@github.com wrote:

@hoanganhtuan95ptit https://github.com/hoanganhtuan95ptit I´m using phone with Android 5.1 API 22 (Huawei) and your solution not work. In Android Studio I have Android 5.1.1 API 22 (Nexus 5) and it works, even without your solution.

— You are receiving this because you commented. Reply to this email directly, view it on GitHub https://github.com/firebase/quickstart-android/issues/41#issuecomment-361788848, or mute the thread https://github.com/notifications/unsubscribe-auth/ACV6DCD3irADDbZyBHPG64_k2oOJ1cVpks5tP7y6gaJpZM4Ivrw2 .

hoanganhtuan95ptit commented 6 years ago

@martinadamec @radityagumay My solution was to solve the OPPO lineup (I made it clear in my description) that other models I have not found the solution. This error only appears in the Oppo, Redmi, Xiaomi (Nexus, Samsung ... not in this error)

Some lines like Redmi seem to have checked the source of the installation files, my releases on chplay are working fine, but debug is not.

skfaisal93 commented 6 years ago

@hoanganhtuan95ptit Can we work together and write some code which will work for all (maximum) the devices?

radityagumay commented 6 years ago

Include me please.

On Feb 3, 2018 03:28, "Faisal Shaikh" notifications@github.com wrote:

@hoanganhtuan95ptit https://github.com/hoanganhtuan95ptit Can we work together and write some code which will work for all (maximum) the devices?

— You are receiving this because you were mentioned. Reply to this email directly, view it on GitHub https://github.com/firebase/quickstart-android/issues/41#issuecomment-362697759, or mute the thread https://github.com/notifications/unsubscribe-auth/ACV6DKpunGTBB4leG3QnmxFIv1L5zMPcks5tQ2_VgaJpZM4Ivrw2 .

dreiklangdev commented 6 years ago

Another approach would be recognizing the app being killed and recommend/instruct the user to whitelist it. That may be more on par with the system's guidelines.

skfaisal93 commented 6 years ago

I found so many apps which are new on PlayStore but still I receive the push notification on my OnePlus 5 (as they are new on PlayStore hence they are not whitelisted from manufacturer company like WhatsApp & Facebook). But sadly for my app I am still unable to figure out how can I solve this issue with my OnePlus 5.

SagarPanwala commented 6 years ago

@skfaisal93 : agree with you, many apps are getting notifications which I think might not be whitelisted or not that much popular like fb and whatsapp, but still getting notification.

ibrahimAlii commented 6 years ago

I have this Issue too, when app is closed I didn't receive any notification, I'm tried to make a JobScheduler to schedule and check for notification every some time, but I didn't get a good result.

Ktirumalsetty commented 6 years ago

Does anyone found solution for this I have observed same with One Plus with 8.0 (Oreo)

Haidar-Hammoud commented 6 years ago

Is there really no solution yet? Does anybody have any way of ensuring these services run after app is swiped?

Haidar-Hammoud commented 6 years ago

I've found a solution!!!! in the manifest, define this:

        <service
            android:name=".BService"
            android:enabled="true"
            android:stopWithTask="false" />

Then create the following java class:

import android.app.Service;
import android.content.Intent;
import android.os.Binder;
import android.os.IBinder;
import android.util.Log;
import android.widget.Toast;

public class BService extends Service {
    public class LocalBinder extends Binder {
        BService getService() {
            return BService.this;
        }
    }
    @Override
    public void onCreate() {
        for(int x = 0; x < 100; x++){
            Toast.makeText(this, "Wow", Toast.LENGTH_SHORT).show();
        }
    }

    @Override
    public int onStartCommand(Intent intent, int flags, int startId) {
        Log.i("LocalService", "Received start id " + startId + ": " + intent);
        return START_STICKY;
    }
    @Override
    public IBinder onBind(Intent intent) {
        return mBinder;
    }
    private final IBinder mBinder = new LocalBinder();
}

As you can see, there is a toast constantly being displayed. Notifications are indeed received and displayed, at least for me, even after the app is swiped away. If somebody can now play with this and find out something more practical than toasting infinitely in the onCreate method, maybe we can finally have a working solution.

What I've found is that it must be some type of loop, one log doesn't suffice. I've also discovered that this only works for about a minute. However, and most importantly, it works after the app is swiped away, so that's at least more progress than anything I've encountered.

darklow commented 6 years ago

I have ASUS ZenPad 3S 10 (Asus P027) tablet with Android 7.0 and none of the solutions mentioned here worked for me, until I discovered app under settings that comes with tablet that blocks all background activities. Under: Settings > Power management > Auto-start Manager I needed to turn checkbox ON for my app in order to allow background activities like push notifications. By default all newly installed apps were OFF, unless they came already pre-installed like Facebook, and other big apps.

IgniteCoders commented 6 years ago

Yes, FirebaseMessagingService can receive PushNotification even when app is killed.

But there are some problems in the way. The behavior of the apps changes between development and production, and because of the device provider.

The first thing you have to consider, is when the app is in development, if you force close the app (kill-process), FirebaseMessagingService stop being triggered. But this doesn't happen in production, so don't be aware of this if you APK is signed. link to source

The second thing, is that there some Android phone providers that manage processes by them selfs. We can see an example like Huawei phones and their "Protected applications", which make user decide if want to protect the app or not. Only famous apps are protected on installation like WhatApp or Twitter... link to source

At this point, your FirebaseMessagingService should be triggered, but the are other problems related with memory and processes managed by system (OS). Your Service can be canceled because of the time that it's spending to handle the PushNotification. You can find many ways to handle this problem, but the best way, is Firebase JobDispatcher. link to source

Mina-Mikhail commented 6 years ago

@IgniteCoders I read your comment, it's so clearly. thank you. but i want to handle a notification count to add it in app badge, i handled it in onMessageReceived() , but it working only when app is in foreground, you wrote in case to handle it when app in background(killed), you should use Firebase JobDispatcher.. I don't know how to handle it with Firebase JobDispatcher, can you help me ??!

IgniteCoders commented 6 years ago

Hi @Mina-Mikhail

I am glad to be helpful!

I dont have the code right now, but. The way to use JobDispacher is firing a Job when you receive the notification instead of trying to handle it in that moment. JobDispacher makes Job to be fired when there are resources for it (memory, baterry...).

I will post the code when i am at home, but there are lot of tutorials and a documentation in the link. Let me know if did it!

kroikie commented 6 years ago

Hi I'd like to clarify that FCM will NOT deliver messages to apps that are in a stopped state.

From the Android documentation:

Applications are in a stopped state when they are first installed but are not yet launched and when they are manually stopped by the user (in Manage Applications).

Unfortunately some manufactures are incorrectly putting apps into a stopped state. Eg: when swiped from the recents view. Thus FCM will NOT deliver messages to applications in this state. We are working with manufactures to ensure that apps are only put into the stopped state as described in the documentation.

Backgrounded apps (Eg: apps that are swiped from recents or if the user leaves an app by going to the home screen.) do receive messages from FCM.

gagangoku commented 6 years ago

This is a major issue for me. I ended up not using flutter and developing my Android app the typical way. On my OnePlus 5T, a normal android app (https://play.google.com/store/apps/details?id=com.homedruid.notificationtester) is able to receive notifications when swipe closed. However, when I create a flutter project, I don't get firebase notifications when app is swiped off.

I am sure this is not a whitelisting issue, my simple android app is new and is receiving notifications fine. I think the issue is somewhere the flutter sdk when onDestroy() is called.

I can't use flutter now (I really liked the ease of drawing widgets) for my customer app, push notifications is a MUST.

gagangoku commented 6 years ago

UPDATE: This might be a good news for OnePlus 5T. Can't say for other devices. It seems if you have the word notificationtest in the package name, fcm notifications are received upon app swipe.

Haidar-Hammoud commented 6 years ago

I have some great news. I updated my firebase versions within Gradle and data notifications are working without fail now! It would seem that the firebase team fixed the problem.

BestDI commented 6 years ago

@haidarcorp Could you tell the fcm-messaging version you used?

BestDI commented 6 years ago

I have find that if the phone battery optimization is on, the push notification wouldn't be received after the app is closed.

gerryhigh commented 6 years ago

@gagangoku that seems to make no sense that it would work. From here https://github.com/flutter/plugins/tree/master/packages/firebase_messaging it shouldn't be supported

gagangoku commented 6 years ago

@gerryhigh I'm not using the firebase plugin, am directly registering with firebase using native android. I guess OnePlus 5T isn't terminating the application when app is swipe closed. With my old package name, it was and I wasn't receiving firebase notifications.

dhruvishah22 commented 5 years ago

@Sanjay-Ghadge 's solution worked for me. Thanks!

What worked for you?

erlangparasu commented 5 years ago
  1. Your app: use AlarmManager to broadcast -> then register an implisit BroadcastReceiver (inside AndroidManifest.xml) -> then the receiver start an foreground service (with notification) -> then in that foreground Service, return START_STICKY.

  2. Firebase: send message (data) only.

  3. Android Settings: enable Autostart of your app.

ricardoroth commented 5 years ago

@kroikie after testing on my Huawei P20 it looks like the definition of "stopped state" is not complete. If my app is running (with FCM correctly displaying notifications in background state) and I reset my phone, then FCM doesn't display notifications anymore until I start the app again. However... If I open the recent apps just after the reset, it does show up there!

Reseting the phone is not included as a cause for apps to stop on google manual.

Applications are in a stopped state when they are first installed but are not yet launched and when they are manually stopped by the user (in Manage Applications).

I really doubt that the intention here is that FCM will stop showing notifications of apps not restarted after a phone reset.

thelilla commented 5 years ago

TEAM- Is it still true that an app must be running in the background in order to get notified of the app's push notes?

DennisSamual commented 4 years ago

TEAM- Is it still true that an app must be running in the background in order to get notified of the app's push notes?

Yes. I tried solving this issue for the whole day (03/02/2020). And still I'am facing this issue. If anyone have a solution, please let us know.

Thank you in advance.

Jacky-na commented 4 years ago

https://github.com/firebase/quickstart-android/issues/41 - ``