FCM push notification when app is killed/swiped out - android

I am using FCM cloud messaging and it is working fine when the app is in the background but not killed or when the app is running.
Once the app is stopped or killed from recent apps it doesn't receive any notification.
Even it doesn't receive the old messages once the app is started.
code for onMessageReceived()
#Override
public void onMessageReceived(RemoteMessage remoteMessage) {
Map<String, String> data = remoteMessage.getData();
String myCustomKey = data.get("Nick");
String myCustomKey1 = data.get("Room");
testNotification(myCustomKey,myCustomKey1);
}
private void testNotification(String message,String title) {
Intent intent = new Intent(this, ChatActivity.class);
intent.addFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP);
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.drawable.sham_icon)
.setContentTitle(title)
.setContentText(message)
.setAutoCancel(true)
.setSound(defaultSoundUri)
.setContentIntent(pendingIntent);
NotificationManager notificationManager =
(NotificationManager) getSystemService(Context.NOTIFICATION_SERVICE);
notificationManager.notify(0, notificationBuilder.build());
}
server side code for sending notification
{
"to" : "token-key",
"data" : {
"title":"title",
"body":"body",
"Nick" : "Mario",
"Room" : "PortugalVSDenmark"
}
}
manifest code for firebase services and notification
<meta-data
android:name="com.google.firebase.messaging.default_notification_icon"
android:resource="#drawable/narendramodi_icon" />
android:resource="#drawable/sham_icon" />
<meta-data
android:name="com.google.firebase.messaging.default_notification_color"
android:resource="#color/accent" />
<service android:name=".firebase.MyFirebaseMessagingService"
android:exported="false">
<intent-filter android:priority="10000">
<action android:name="com.google.firebase.MESSAGING_EVENT" />
</intent-filter>
</service>
<service android:name=".firebase.MyFirebaseInstanceIDService">
<intent-filter>
<action android:name="com.google.firebase.INSTANCE_ID_EVENT" />
</intent-filter>
</service>
Any help is appreciated.

This happens because on some devices system doesn't allow starting apps or app services by other apps, For FCM notifications Google Play services starts your app service if your app has been killed, when they are killed (ex. Xiaomi phones with MIUI).

Use your app server and FCM server API: Set the data key only. Can be either collapsible or non-collapsible.
If you are sending the notification from console, then use the particular key to send the notification from the Advanced Option features.
if (getIntent().getExtras() != null) {
// Call your NotificationActivity here..
Intent intent = new Intent(MainActivity.this, NotificationActivity.class);
startActivity(intent);
}

The Android framework advises that apps that have been stopped (not in background) should not be started without explicit user interaction.
FCM follows this recommendation and thus does not deliver messages to stopped apps.
For some phones,Once the app is stopped or killed from recent apps, it was completely stopped by the OS. this can save battery but fcm won't work.

Related

FCM notification doesn't show notification pop up in background

I'm using firebase cloud function for showing notification in my app and that working perfectly only issue I'm facing is when app is closed or in background notification doesn't show pop up.
Heads up notifications are used in app and I do get the notification but notification doesn't pop up as it do while app is in foreground.I have set the Priority to high for both channel and notification but still it doesn't work.
My Service Class :
#Override
public void onMessageReceived(RemoteMessage remoteMessage) {
super.onMessageReceived(remoteMessage);
Log.d("msg", "onMessageReceived: " + remoteMessage.getData().get("message"));
Intent intent = new Intent(this, WebViewActivity.class);
intent.addFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP);
PendingIntent pendingIntent = PendingIntent.getActivity(this, 0, intent, PendingIntent.FLAG_ONE_SHOT);
String channelId = "Default";
NotificationCompat.Builder builder = new NotificationCompat.Builder(this, channelId)
.setSmallIcon(R.drawable.app_logo)
.setContentTitle(remoteMessage.getNotification().getTitle())
.setContentText(remoteMessage.getNotification().getBody())
.setAutoCancel(true).setContentIntent(pendingIntent)
.setDefaults(DEFAULT_SOUND | DEFAULT_VIBRATE)
.setPriority(Notification.PRIORITY_MAX);
NotificationManager manager = (NotificationManager) getSystemService(NOTIFICATION_SERVICE);
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.O) {
NotificationChannel channel = new NotificationChannel(channelId, "Default channel", NotificationManager.IMPORTANCE_HIGH);
channel.setShowBadge(true);
channel.setLockscreenVisibility(Notification.VISIBILITY_PUBLIC);
manager.createNotificationChannel(channel);
}
manager.notify(0, builder.build());
}
Manifest
<application
android:allowBackup="true"
android:icon="#mipmap/ic_launcher"
android:label="#string/app_name"
android:roundIcon="#mipmap/ic_launcher_round"
android:supportsRtl="true"
android:theme="#style/AppTheme">
<activity android:name="com.noderon.riscalert.WebViewActivity">
<intent-filter>
<action android:name="android.intent.action.MAIN" />
<category android:name="android.intent.category.LAUNCHER" />
</intent-filter>
</activity>
<activity android:name="com.noderon.riscalert.MainActivity">
</activity>
<service
android:name=".NotificationService">
<intent-filter>
<action android:name="com.google.firebase.MESSAGING_EVENT"/>
</intent-filter>
</service>
</application>
Any help would be appreciated. Thanku
As you are already setting the Priorities it seems like you are not adding the metadata for the notification and when the app is in the background it won't get any data that's why it only showing the pop up in the foreground
add these metadata in your code:
<meta-data
android:name="com.google.firebase.messaging.default_notification_icon"
android:resource="#drawable/ic_stat_ic_notification" />
<meta-data
android:name="com.google.firebase.messaging.default_notification_color"
android:resource="#color/colorAccent" />
<meta-data
android:name="com.google.firebase.messaging.default_notification_channel_id"
android:value="#string/default_notification_channel_id" />
Also, you can see Google Cloud Messaging documentation for more details
Happy coding
I have faced the same issue. I have followed the official documentation from the firebase and now notifications are working fine. Follow this link
.
Have you created FirebaseMessage Instance() in your Activity?

How to generate notification when a new picture is taken by camera app?

I want to create a notification from my app when a new picture is taken from the camera app. I want to achieve this when my app is not running. I am using Broadcast receiver to do this.
Here is my Code...
In Android Manifest..
<receiver
android:name=".receivers.CameraEventReceiver"
android:label="CameraEventReceiver"
android:enabled="true">
<intent-filter>
<action android:name="android.hardware.action.NEW_PICTURE" />
<data android:mimeType="image/*" />
</intent-filter>
</receiver>
In my receiver class
public class CameraEventReceiver extends BroadcastReceiver {
#Override
public void onReceive(Context context, Intent intent) {
NotificationManager manager = (NotificationManager) context.getSystemService(Context.NOTIFICATION_SERVICE);
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.O){
NotificationChannel channel = new NotificationChannel("CHANNEL_ID", "my channel name", NotificationManager.IMPORTANCE_HIGH);
manager.createNotificationChannel(channel);
}
NotificationCompat.Builder builder = new NotificationCompat.Builder(context, "CHANNEL_ID")
.setColor(ContextCompat.getColor(context, R.color.colorPrimary))
.setSmallIcon(R.mipmap.ic_launcher)
.setContentTitle("Picture Taken")
.setContentText("here is the uri : "+intent.getData())
.setDefaults(NotificationCompat.DEFAULT_VIBRATE)
.setAutoCancel(true);
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.JELLY_BEAN && Build.VERSION.SDK_INT < Build.VERSION_CODES.O){
builder.setPriority(NotificationCompat.PRIORITY_HIGH);
}
manager.notify(222, builder.build());
}
}
It is working fine for Android 6.0 when the app is running...
But it is not working for newer versions. What can I do to achieve this?
I want it to support for all devices with android versions greater than 4.1 (JELLY_BEAN)
Thanks in advance
But it is not working for newer versions.
Correct. Those broadcasts are no longer supported. See the Android 7.0 release notes.
What can I do to achieve this?
Take the picture yourself, whether using ACTION_IMAGE_CAPTURE, the camera APIs, or libraries (e.g., Fotoapparat, CameraKit-Android).
There is no direct replacement for that broadcast, and there was no requirement for camera apps to trigger that broadcast anyway.
You could use JobScheduler and addTriggerContentUri() to monitor the MediaStore for changes. However, I do not know how you would limit it to only pictures taken by a camera app.
I have implemented when new SMS arrived and i was facing the same issue. I have put below lines in my manifest file.
<intent-filter>
<action android:name="android.intent.action.BOOT_COMPLETED" />
<action android:name="android.intent.action.INPUT_METHOD_CHANGED" />
</intent-filter>

Using the display intent on a page of a wearable notification

I create a wearable compatible notification with a second page which should embedd a custom activity (on the wearable).
Here is the relevant part of the Manifest from the wearable app:
<activity android:name=".Test"
android:label="aaa"
android:allowEmbedded="true"
android:taskAffinity=""
android:theme="#android:style/Theme.DeviceDefault.Light">
<intent-filter>
<action android:name="android.intent.action.MAIN"/>
<category android:name="android.intent.category.LAUNCHER"/>
</intent-filter>
</activity>
Here is my related android code from the phone:
Intent notificationIntent = new Intent();
notificationIntent.setClassName(BuildConfig.APPLICATION_ID, BuildConfig.APPLICATION_ID + ".wear.Main");
PendingIntent notificationPendingIntent = PendingIntent.getActivity(this, 0,
notificationIntent, PendingIntent.FLAG_UPDATE_CURRENT);
Bitmap bg = BitmapFactory.decodeResource(getResources(), R.drawable.bg_wearable);
Notification test = new NotificationCompat.Builder(this)
.setAutoCancel(true)
.setSmallIcon(R.drawable.ic_launcher)
.setContentTitle("Title")
.setContentText("Message")
.extend(new NotificationCompat.WearableExtender()
.setBackground(bg)
.addPage(new NotificationCompat.Builder(this)
.setContentTitle("Page 1")
.extend(new NotificationCompat.WearableExtender()
.setDisplayIntent(notificationPendingIntent)
.setCustomSizePreset(NotificationCompat.WearableExtender.SIZE_FULL_SCREEN)
).build()
)
)
.build();
NotificationManagerCompat.from(this).notify(12345, test);
Do you have any idea why this don't work on the phone, but on the wearable itself?
You can only create and issue custom notifications with embedded activities from the wearable itself.
From the docs:
You can only create and issue custom notifications on the wearable,
and the system does not sync these notifications to the handheld.
Source

GCM not Working

I am learning GCM(Google cloud Messaging)
I Completed Following steps
1 - Activated and Obtained a Key for browser apps
2 - added following in manifest
Uses permission : com.google.android.c2dm.permission.RECEIVE
Created permission to prevent other Android applications from registering and receiving the Android application's messages
Created a receiver for com.google.android.c2dm.intent.RECEIVE, with the category set as applicationPackage. The receiver should require the com.google.android.c2dm.SEND permission
3 – in receiver
#Override
public void onReceive(Context context, Intent intent) {
ComponentName comp = new ComponentName(context.getPackageName(),
GcmMessageHandler.class.getName());
startWakefulService(context, (intent.setComponent(comp)));
setResultCode(Activity.RESULT_OK);
}
GcmMessageHandler it’s a Intend Service to show a notification on receive gcm message.following is onHandleIntent Method in GcmMessageHandler.
#Override
protected void onHandleIntent(Intent intent) {
handler.post(new Runnable() {
#Override
public void run() {
NotificationManager manager = (NotificationManager) getApplicationContext()
.getSystemService(Context.NOTIFICATION_SERVICE);
NotificationCompat.Builder mBuilder = new NotificationCompat.Builder(
getApplicationContext());
mBuilder.setSmallIcon(R.drawable.ic_launcher);
mBuilder.setContentTitle("GCM Received");
mBuilder.setContentText("GCM Message");
manager.notify(1, mBuilder.build());
}
});
Log.i("app", "Received ");
GcmBroadcastReceiver.completeWakefulIntent(intent);
}
4 - MainActivity-to register and get clint ID, from log cat I copyed that id.
5 - from browser I make post request to https://android.googleapis.com/gcm/send with authorization,content-type,and registration_ids.
Its gets success message.
But my device not showing notification.
Sorry everyone,
Actually my program is correct. I think it’s a problem with my phone.
(I can’t receive messages from Facebook messenger also,)
but Today morning I surprised, I got every messages from my test app(message that I send 2 days ago), Facebook ,etc.
Thank you everyone.
Follow this and this easy tutorial to send and receive push nothification in Android.
And check package naming and AndroidManifest.xml file configured correctly as explained in this example and set receiver like this:
<receiver
android:name="com.google.android.gcm.GCMBroadcastReceiver"
android:permission="com.google.android.c2dm.permission.SEND" >
<intent-filter>
<!-- Receives the actual messages. -->
<action android:name="com.google.android.c2dm.intent.RECEIVE" />
<!-- Receives the registration id. -->
<action android:name="com.google.android.c2dm.intent.REGISTRATION" />
<category android:name="your package name here" />
</intent-filter>
</receiver>

Android Push notifications on Samsung Galaxy Tab 10

I have a pair applications where I use a GCMBroadcastReceiver and a GCMIntentService to listen for google cloud messaging messages and then send a notification to Android's tray via NotificationManager. Pretty standard code, as far as I know I'm not doing anything strange here.
And the code works, most all devices show my notifications (both) , each application shows a similar notification, with a different icon.
The problem is, the Galaxy Tab 10 is only showing one of them, and the other not. And I can't put my finger on what could be causing the difference.
Specially since the code is so simple.
here is the code where I make the notification:
mNotificationManager = (NotificationManager)
this.getSystemService(Context.NOTIFICATION_SERVICE);
PendingIntent contentIntent = PendingIntent.getActivity(this, 1,
new Intent(this, HomeActivity.class), 0);
Resources res = getResources();
Bitmap bm = BitmapFactory.decodeResource(res, R.drawable.notifier_app_launcher);
NotificationCompat.Builder mBuilder =
new NotificationCompat.Builder(this)
.setLargeIcon(bm)
.setSmallIcon(R.drawable.app_icon_notifier)
.setContentTitle(getString(R.string.title))
.setNumber(number)
.setStyle(new NotificationCompat.BigTextStyle()
.bigText(msg))
.setContentText(msg);
mBuilder.setContentIntent(contentIntent);
mNotificationManager.notify(NOTIFICATION_ID, mBuilder.build());
Also, this is how I define my receiver:
<receiver android:name="com.company.mobile.app.GcmBroadcastReceiver" android:exported="true" android:process=":remote" android:permission="com.google.android.c2dm.permission.SEND">
<intent-filter>
<action android:name="com.google.android.c2dm.intent.RECEIVE" />
<category android:name="com.company.mobile.app" />
</intent-filter>
Is it a known error of that model? Has anyone experienced this before? am I missing something in the code? All feedback is welcome.

Categories

Resources