Handling fcm notification click - android

I am using fcm to send messages. The messages arrive to the app, but when the user clicks on the notification, t it supposed to open a link but it just opens the app. My manifest is like this
<service android:name=".MyFirebaseMessagingService">
<intent-filter>
<action android:name="com.google.firebase.MESSAGING_EVENT" />
</intent-filter>
</service>
<meta-data
android:name="com.google.firebase.messaging.default_notification_channel_id"
android:value="#string/default_notification_channel_id"/>
Where the notification is supposed to be handled :
Bundle extras = getIntent().getExtras();
if (extras != null && extras.containsKey("rateUpdate")) {
try {
startActivity(new Intent("android.intent.action.VIEW", Uri.parse("market://details?id=tino.varconn.com.fastnetworks")));
} catch (ActivityNotFoundException unused) {
startActivity(new Intent("android.intent.action.VIEW", Uri.parse("http://play.google.com/store/apps/details?id=tino.varconn.com.fastnetworks")));
}
}
When sending the message, I always make sure that in the key, value text boxes I put rateUpdate. Where am I going wrong here?

Inside FirebaseMessagingService class you can get content from push notification and build your own Notification
#Override
public void onMessageReceived(RemoteMessage remoteMessage) {
super.onMessageReceived(remoteMessage);
Notification notification = remoteMessage.getNotification()
String title = notification.getTitle()
String body = notification.getBody();
//now you can build and show your own notification
}
with .setContentIntent() method, where you can set any Activity you want to start.
NotificationCompat.Builder builder = ...
Intent intent = new Intent(context, destinationClass);
intent.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
intent.addFlags(Intent.FLAG_ACTIVITY_SINGLE_TOP | Intent.FLAG_ACTIVITY_CLEAR_TOP);
PendingIntent contentIntent = PendingIntent.getActivity(context, 0, intent,
0);
builder.setContentIntent(contentIntent);

Related

Android Firebase notification when application starts

I’m new to android.I programmed an app that uses Firebase to get push notifications. If I send a notification from the Firebase interface, the device receives the notification only when the app is running. Is there a way to get the notifications when the app is not running or at least to get all the unseen notifications when the app starts up?
Thank you in advance!
I add my code...
This is the class extending the FirebaseMessagingService:
public class MyFirebaseMessagingService extends FirebaseMessagingService {
public MyFirebaseMessagingService() {
}
#Override
public void onMessageReceived(RemoteMessage remoteMessage) {
super.onMessageReceived(remoteMessage);
sendNotification(remoteMessage.getNotification().getBody());
}
private void sendNotification(String messageBody)
{
//Intent intent = new Intent (this, MainActivity.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);
notificationBuilder.setSmallIcon(R.mipmap.ic_launcher_round);
notificationBuilder.setContentTitle("My app");
notificationBuilder.setContentText(messageBody);
notificationBuilder.setAutoCancel(true);
notificationBuilder.setSound(defaultSoundUri);
//notificationBuilder.setContentIntent(pendingIntent);
NotificationManager notificationManager = (NotificationManager)getSystemService(Context.NOTIFICATION_SERVICE);
notificationManager.notify(0,notificationBuilder.build());
}
}
and this is the class extending the FirebaseInstanceIdService:
public class MyFirebaseInstanceIDService extends FirebaseInstanceIdService{
#Override
public void onTokenRefresh() {
// Get updated InstanceID token.
String refreshedToken = FirebaseInstanceId.getInstance().getToken();
// If you want to send messages to this application instance or
// manage this apps subscriptions on the server side, send the
// Instance ID token to your app server.
sendRegistrationToServer(refreshedToken);
}
private void sendRegistrationToServer(String token)
{
}
}
Finally, this is the manifest:
<?xml version="1.0" encoding="utf-8"?>
<manifest xmlns:android="http://schemas.android.com/apk/res/android"
package="user.pushnotificationexample">
<uses-permission android:name="android.permission.INTERNET"/>
<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=".MainActivity">
<intent-filter>
<action android:name="android.intent.action.MAIN" />
<category android:name="android.intent.category.LAUNCHER" />
</intent-filter>
</activity>
<service android:name=".MyFirebaseInstanceIDService">
<intent-filter>
<action android:name="com.google.firebase.INSTANCE_ID_EVENT" />
</intent-filter>
</service>
<service
android:name=".MyFirebaseMessagingService"
android:enabled="true"
android:exported="true">
<intent-filter>
<action android:name="com.google.firebase.MESSAGING_EVENT"/>
</intent-filter>
</service>
</application>
</manifest>
This is Xamarin Android solution, but it should get you close to native.
Try test sending a "data" push notification from an online tester like "pushwatch". Make sure to click the json checkbox and add a json payload that includes the key, "data":
{"data": {"title":"This is a title!","body":"This is the body text!"}}
The OnMessageReceived(RemoteMessage message) method, message parameter, has a dictionary property "Data": i.e. message.Data. You'll find the json payload key value pairs (title & body) in that dictionary.
Note, if the app is STOPPED, the user will OPEN the notification and Android will open the app, targeting the Activity used in the pending intent created and used to build the local notification (see below). You will need to handle the notification intent from the OnCreate method of your target Activity ( otherwise if the app is running, you'll handle the intent from an override of OnNewIntent).
public class MainActivity....
{
protected override void OnCreate(Bundle bundle)
{
...
var pushExtra = Intent.GetStringExtra("your.pushextra.key");
if(pushExtra != null)
{
MyType myType = JsonConvert.Deserialize<MyType>(pushExtra);
//if you have a framework like MVVM or startup process
//and your type
//is used for app navigation, you may need to store
//the string value in shared preferences and deserialize
//and use it later
//after the app has completely finished starting
}
}
}
Save yourself some effort, if you need a type or dictionary here, make sure to serialize the object when putting the extra (when you create the local notification) and then deserialize the pushExtra to your concrete type to use an instance of it above. You may find most examples put a string, or int or dictionary of key value pairs.
void ConfigureLocalNotification(MyType typeInstance)
{
...
var intent = new Intent(context, typeof(MainActivity));
var jsonData = JsonConvert.SerializeObject(typeInstance);
Log.Info(TAG, $"Adding IntentExtra: {jsonData}");
intent.PutExtra("your.pushextra.key", jsonData);
intent.AddFlags(ActivityFlags.ClearTop | ActivityFlags.SingleTop |
ActivityFlags.IncludeStoppedPackages); //| ActivityFlags.NewTask);
var pendingIntent = PendingIntent.GetActivity(context, 0, intent,
PendingIntentFlags.OneShot);
....
NotificationCompat.Builder builder = null;
builder = new NotificationCompat.Builder(context ...);
builder.SetContentIntent(pendingIntent) ....
}
Hope this helps

Notification showing Wrongly in Firebase android

Hi Here i write it using Firebase Notification,i am used onMessageReceived to get notification,and send it on sendNotification functionality,Here my problem is ,my app is sleep mode,when i click the notification i need to go main activity page,but i got error ,its started from splash screen Here is my code on Firebase Messaging Service
public class FirebaseMessagingService extends com.google.firebase.messaging.FirebaseMessagingService {
private static final String TAG = "MyFirebaseMsgService";
String data;
String jsonObject;
#Override
public void onMessageReceived(RemoteMessage remoteMessage) {
Log.d(TAG, "From: " + remoteMessage.getFrom()); //MyFirebaseMsgService: From: 1055554437945
// Check if message contains a data payload.
data = String.valueOf(remoteMessage.getData());
Log.d(TAG, "Message data payload: " + remoteMessage.getData());
if (remoteMessage.getData().size() > 0) {
jsonObject = remoteMessage.getData().toString();
}
// Check if message contains a notification payload.
if (remoteMessage.getNotification() != null) {
Log.d(TAG, "Message Notification Body: " + remoteMessage.getNotification().getTitle()); ////MyFirebaseMsgService: Message Notification Body: Customer request for service
if (remoteMessage.getNotification().getTitle().equalsIgnoreCase("Service Request")) {
sendNotification(remoteMessage.getNotification().getBody(), remoteMessage.getData().toString());
}
}
// Also if you intend on generating your own notifications as a result of a received FCM
// message, here is where that should be initiated. See sendNotification method below.
}
/**
* Create and show a simple notification containing the received FCM message.
*
* #param messageBody FCM message body received.
*/
private void sendNotification(String messageBody, String values) {
Log.i("messageBodymageBody", "" + messageBody);
if (isUserLoggedIn()) {
Intent intent = new Intent(this, MainActivity.class);
intent.putExtra("values", values);
intent.putExtra("identify", "1");
intent.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK | Intent.FLAG_ACTIVITY_CLEAR_TASK);
intent.addFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP);
intent.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
TaskStackBuilder stackBuilder = TaskStackBuilder.create(this);
stackBuilder.addParentStack(MainActivity.class);
stackBuilder.addNextIntent(intent);
PendingIntent contentIntent = stackBuilder
.getPendingIntent(0, PendingIntent.FLAG_UPDATE_CURRENT
| PendingIntent.FLAG_ONE_SHOT);
startActivity(intent);
Uri defaultSoundUri = RingtoneManager.getDefaultUri(RingtoneManager.TYPE_NOTIFICATION);
NotificationCompat.Builder notificationBuilder = new NotificationCompat.Builder(this)
.setSmallIcon(R.drawable.fixmelogo)
.setContentTitle("Service Request")
.setContentText("Customer request for service")
.setAutoCancel(true)
.setSound(defaultSoundUri)
.setContentIntent(contentIntent);
NotificationManager notificationManager = (NotificationManager) getSystemService(Context.NOTIFICATION_SERVICE);
notificationManager.notify(0, notificationBuilder.build());
} else {
Intent intent1 = new Intent(this, LoginActivity.class);
startActivity(intent1);
}
}
public boolean isUserLoggedIn() {
Log.i("bollcheck", "" + UserInformations.getUserInformations(this).getId() + UserInformations.getUserInformations(this).getEmail());
/*if (UserInformations.getUserInformations(this).getId() != null || UserInformations.getUserInformations(this).getEmail() != null
|| UserInformations.getUserInformations(this).getMobile() != null) {*/
return UserInformations.getUserInformations(this).getId().trim().length() > 0;
}}
and also my manifest file
<application
android:name=".App"
android:allowBackup="true"
android:icon="#drawable/fixmelogo"
android:label="#string/app_name"
android:roundIcon="#drawable/fixmelogo"
android:supportsRtl="true"
android:theme="#style/AppTheme">
<activity android:name=".Activity.SplashScreen">
<intent-filter>
<action android:name="android.intent.action.MAIN" />
<category android:name="android.intent.category.LAUNCHER" />
</intent-filter>
</activity>
<service android:name=".FirebaseMessagingService">
<intent-filter>
<action android:name="com.google.firebase.MESSAGING_EVENT" />
</intent-filter>
</service>
<service android:name=".FirebaseInstanceIDService">
<intent-filter>
<action android:name="com.google.firebase.INSTANCE_ID_EVENT" />
</intent-filter>
</service>
<meta-data
android:name="com.google.firebase.messaging.default_notification_icon"
android:resource="#drawable/fixmelogo" />
<meta-data android:name="com.google.firebase.messaging.default_notification_color"
android:resource="#color/colorPrimary" />
<activity android:name=".Activity.MainActivity"
android:exported="true"/>
<activity android:name=".Activity.TripActivity" />
</application>
when I click notification need to Main Activity, but it's going from splash Screen page, Sorry for my poor English, I am Beginner of the Android, kindly give some solution
Hi Here my Notification Json from Server
{
"to":"d7XvGt8pD60:APA91bEjEe9IjhjJDmojvRDogMp1xc4sQFT9EcoB8TBvM-rCtkwryFhRVGvHIx1T6CWMoJu3l4UuaXgkgWrFj_Fo1SFhip9C-RXuthO6pfHvJ4GRQOipWtiVjUl9wtO7jfVd-T6jMBpJ",
"notification":{
"body":"Customer request for service",
"title":"Service Request",
"sound":"mySound"
},
"data":{
"CustomerId":"99",
"CustomerName":"Mayil",
"CustomerLastName":"Kannan",
"PhoneNumber":"96788484887",
"PickupLocation":"Ponmeni Muniyaandi koil main road, Chandragandhi Nagar, Ponmeni, Madurai, Tamil Nadu 625016",
"DropLocation":"Ponmeni Muniyaandi koil main road, Chandragandhi Nagar, Ponmeni, Madurai, Tamil Nadu 625016",
"PickupLatitude":"9.92074762937605",
"PickupLongitude":"78.0926296301913",
"DropLatitude":"9.92074762937605",
"DropLongitude":"78.0926296301913"
}
}
they Are sending like this.

FCM notification not opening intended activity Android

I am trying to get notification generated by FCM console and I am receiving them but I am unable to override onMessageReceived of FirebaseMessagingService. Don't know what I am doing wrong.
MyFirebaseMessagingService class responsible for handling notifications:
public class MyFirebaseMessagingService extends FirebaseMessagingService {
private static final String TAG = "MyFirebaseMsgService";
#Override
public void onCreate() {
super.onCreate();
}
#Override
public void onMessageReceived(RemoteMessage remoteMessage) {
Log.d(TAG, "FROM:" + remoteMessage.getFrom());
//Check if the message contains data
if(remoteMessage.getData().size() > 0) {
Log.d(TAG, "Message data: " + remoteMessage.getData());
}
//Check if the message contains notification
if(remoteMessage.getNotification() != null) {
Log.d(TAG, "Mesage body:" + remoteMessage.getNotification().getBody());
sendNotification(remoteMessage.getNotification().getBody(),remoteMessage.getData());
}
}
/**
* Dispay the notification
* #param body
*/
private void sendNotification(String body , Map<String,String> data) {
// int finalSecId = Integer.parseInt((String) data.get("sec_id"));
// int sec = Integer.parseInt((String) data.get("sec"));
Intent intent = new Intent(this, InsuranceActivity.class);
intent.setFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP);
PendingIntent pendingIntent = PendingIntent.getActivity(this, 0/*Request code*/, intent, PendingIntent.FLAG_ONE_SHOT);
//Set sound of notification
Uri notificationSound = RingtoneManager.getDefaultUri(RingtoneManager.TYPE_NOTIFICATION);
NotificationCompat.Builder notifiBuilder = new NotificationCompat.Builder(this)
.setSmallIcon(R.drawable.login_meter)
.setContentTitle(getString(R.string.app_name))
.setContentText((String) data.get("sec_id")+ " "+(String) data.get("sec"))
.setAutoCancel(true)
.setSound(notificationSound)
.setContentIntent(pendingIntent);
NotificationManager notificationManager = (NotificationManager)getSystemService(Context.NOTIFICATION_SERVICE);
notificationManager.notify(0 /*ID of notification*/, notifiBuilder.build());
}
}
And Inside Application tag
<service android:name=".Fcm.MyFirebaseMessagingService"
android:enabled="true"
android:exported="true"
>
<intent-filter>
<action android:name="com.google.firebase.MESSAGING_EVENT"/>
</intent-filter>
</service>
<service android:name=".Fcm.MyFirebaseInstanceIDService">
<intent-filter>
<action android:name="com.google.firebase.INSTANCE_ID_EVENT"/>
</intent-filter>
</service>
There are two types of FCM
notification Messages: Sending a payload with this message type triggers onMessageReceived() only when your app is in foreground.
data Messages: Sending a payload with only this specific message type triggers onMessageReceived() regardless if your app is in foreground/background.
Reference:here
Extending #Sudip Podder comments and #Ratilal Chopda answer
Follow these steps:
Step1:
<activity android:name=".SplashActivity">
<intent-filter>
<action android:name=".SplashActivity" />
<category android:name="android.intent.category.DEFAULT" />
</intent-filter>
</activity>
Step2:
I am using php at server so you need to adjust things the way you like but in notification payload add "click_action" : ".SplashActivity"
$fields = array(
'to' => $token,
'notification' => array(
'title' => 'Motors City',
'body' => $message,
"click_action" => ".AppSplash",
),
'data' => array(
'sec_id' => $secID,
'sec' => $sec,
'extra1'=>$extra1,
'extra2'=>$extra2
)
);
$headers = array(
'Authorization:key=' . $server_key,
'Content-Type:application/json'
);
Step3:
In Oncreate of your SplashActivity
Bundle bundle = getIntent().getExtras();
if (bundle != null) {
Log.d(TAG,bundle.toString);
}}
and you are done
I had this problem of handling the notifications from FCM.
First we have to understand that there are 2 types of notifications.
Notification - It will trigger when your app is not in foreground and generate a notification. If you click on it then it will open the launcher activity.
Data notification - This one is used to parse the data and it is received in background as well as foreground. So you can build a custom notification based on the data provided in the data object by the FCM Push.
Map<String ,String> dataMap = remoteMessage.getData();
Here i created a simple Map with key value pairs. Now i can receive the title of the notification in the data object and make a simple notification with a custom intent.
I personally use a context object to determine if the app is in foreground or background. Based on that i decide if i have to show the notification or just update the data.
Hope this helps.
Right now you are having Notification in notification type, which triggers Notification Default,and Just open the app on the click of the notification.
So you need to change server side code from notification type to data type.
And try to get Message from
`remoteMessage.getData()` not from `remoteMessage.getNotification()`
if you want to manage click of the notification use data type notification.to understand more about this types go through this link
https://firebase.google.com/docs/cloud-messaging/concept-options
Try this
intent.addFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP);
PendingIntent pendingIntent = PendingIntent.getActivity(this, 0 /* Request code */, intent, PendingIntent.FLAG_ONE_SHOT);

Did not get Notification in Android mobile when Application removed from the Recent Used Apps

I am using firebase cloud messaging for send notification to my application.I get notification when my application in foreground and also switch to another app (my application running in background not closed). But when I was removing from recent used apps.I didn't get notification.
I get the Token Id also. Problem is didn't get the notification when app is removed from the latest used apps.
Android Manifest file:
Inside application
<service
android:name="com.mysite.android.abc.service.MyFirebaseMessagingService"
android:permission="android.permission.RECEIVE_BOOT_COMPLETED"
>
<intent-filter>
<action android:name="com.google.firebase.MESSAGING_EVENT"/>
</intent-filter>
</service>
<!-- [END firebase_service] -->
<!-- [START firebase_iid_service] -->
<service
android:name="com.mysite.android.abc.service.MyFirebaseInstanceIDService"
>
<intent-filter>
<action android:name="com.google.firebase.INSTANCE_ID_EVENT"/>
</intent-filter>
</service>
<!-- [END firebase_iid_service] -->
<receiver
android:name=".service.FirebaseDataReceiver"
android:exported="true"
android:permission="com.google.android.c2dm.permission.SEND">
<intent-filter>
<action android:name="com.google.android.c2dm.intent.RECEIVE" />
</intent-filter>
</receiver>
MyFirebaseInstanceIDService:
public class MyFirebaseInstanceIDService extends FirebaseInstanceIdService {
#Override
public void onTokenRefresh() {
super.onTokenRefresh();
String refreshedToken = FirebaseInstanceId.getInstance().getToken();
// Notify UI that registration has completed, so the progress indicator can be hidden.
Intent registrationComplete = new Intent( Config.REGISTRATION_COMPLETE);
registrationComplete.putExtra("token", refreshedToken);
LocalBroadcastManager.getInstance(this).sendBroadcast(registrationComplete);
}
}
MyFirebaseMessagingService:
public class MyFirebaseMessagingService extends FirebaseMessagingService {
private NotificationUtils notificationUtils;
#Override
public void onMessageReceived(RemoteMessage remoteMessage) {
super.onMessageReceived( remoteMessage );
if(remoteMessage==null){
return;
}
if (remoteMessage.getNotification()!=null) {
handleNotification( remoteMessage.getNotification().getBody() );
}
if(remoteMessage.getData().size()>0){
try {
JSONObject jsonObject=new JSONObject( remoteMessage.getData().toString() );
handleDataMessage( jsonObject );
}catch (Exception e){
e.printStackTrace();
}
}
}
private void handleNotification(String message){
if(!NotificationUtils.isAppIsInBackground( getApplicationContext() )){
Intent pushNotification=new Intent( Config.PUSH_NOTIFICATION );
pushNotification.putExtra( "message",message );
LocalBroadcastManager.getInstance( this ).sendBroadcast( pushNotification );
// play notification sound
/*NotificationUtils notificationUtils = new NotificationUtils(getApplicationContext());
notificationUtils.playNotificationSound();*/
}else{
}
}
private void handleDataMessage(JSONObject jsonObject){
Log.e("GGGGG mm",jsonObject.toString());
try {
JSONObject data=jsonObject.getJSONObject( "data" );
String title=data.getString( "title" );
String message=data.getString( "message" );
JSONObject payload = data.getJSONObject("payload");
if(!NotificationUtils.isAppIsInBackground( getApplicationContext() )){
// app is in foreground, broadcast the push message
Intent pushNotification = new Intent(Config.PUSH_NOTIFICATION);
pushNotification.putExtra("message", message);
LocalBroadcastManager.getInstance(this).sendBroadcast(pushNotification);
// play notification sound
/*NotificationUtils notificationUtils = new NotificationUtils(getApplicationContext());
notificationUtils.playNotificationSound();*/
} else {
// app is in background, show the notification in notification tray
Intent resultIntent = new Intent(getApplicationContext(), Dashboard.class);
resultIntent.putExtra("message", message);
// check for image attachment
if (TextUtils.isEmpty(imageUrl)) {
showNotificationMessage(getApplicationContext(), title, message, timestamp, resultIntent);
} else {
// image is present, show notification with image
showNotificationMessageWithBigImage(getApplicationContext(), title, message, timestamp, resultIntent, imageUrl);
}
}
} catch (JSONException e) {
e.printStackTrace();
}
}
/**
* Showing notification with text only
*/
private void showNotificationMessage(Context context, String title, String message, String timeStamp, Intent intent) {
notificationUtils = new NotificationUtils(context);
intent.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK | Intent.FLAG_ACTIVITY_CLEAR_TASK | Intent.FLAG_INCLUDE_STOPPED_PACKAGES);
notificationUtils.showNotificationMessage(title, message, timeStamp, intent);
}
/**
* Showing notification with text and image
*/
private void showNotificationMessageWithBigImage(Context context, String title, String message, String timeStamp, Intent intent, String imageUrl) {
notificationUtils = new NotificationUtils(context);
intent.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK | Intent.FLAG_ACTIVITY_CLEAR_TASK | Intent.FLAG_INCLUDE_STOPPED_PACKAGES);
notificationUtils.showNotificationMessage(title, message, timeStamp, intent, imageUrl);
}
}
What you are asking is not supported on FCM (this used to work with GCM which is now deprecated)
https://developer.android.com/about/versions/android-3.1#launchcontrols:
Note that the system adds FLAG_EXCLUDE_STOPPED_PACKAGES to all
broadcast intents. It does this to prevent broadcasts from background
services from inadvertently or unnecessarily launching components of
stoppped applications. A background service or application can
override this behavior by adding the FLAG_INCLUDE_STOPPED_PACKAGES
flag to broadcast intents that should be allowed to activate stopped
applications.
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).
The broadcast FCM triggers has FLAG_EXCLUDE_STOPPED_PACKAGES set to TRUE which effectively will not wake up your app if it's force stopped by the user (as you did).
Someone requested that firebase allow the user to control this flag - but this was shot down by the dev team

how opening the targeted activity on click of notification when app is in background

I have sent notification through firebase console using key vale pair and handled the notification in launcher activity. below is the tried code:
#Override
protected void onNewIntent(Intent intent) {
super.onNewIntent(intent);
if (intent.hasExtra("click_action")) {
ClickActionHelper ck=new ClickActionHelper();
ck.startActivity(intent.getStringExtra("click_action"), intent.getExtras(), this);
}
}
public class ClickActionHelper {
public void startActivity(String className, Bundle extras, Context context){
Class cls=null;
try {
cls = Class.forName(className);
}catch(ClassNotFoundException e){
}
Intent i = new Intent(context, cls);
i.putExtras(extras);
context.startActivity(i);
}
}
but this way i am not able to open the targeted activity on click of notification. Any ideas?
If you need to navigate any Activity then there should be bind with Notification class(NotificationCompat.Builder) which is missing in implementation.
Below line is very important to redirect any Activity:
NotificationCompat.Builder builder = new **NotificationCompat.Builder(this); builder.setContentIntent(resultPendingIntent);**
Here resultPendingIntent is used for to containing the backstack for the Activity with the notifications as below:
// Gets a PendingIntent containing the entire back stack PendingIntent
resultPendingIntent = stackBuilder.getPendingIntent(0, PendingIntent.FLAG_UPDATE_CURRENT);
The complete code snippet is available here.
int id = 1;
Intent resultIntent = new Intent(this, ResultActivity.class);
TaskStackBuilder stackBuilder = TaskStackBuilder.create(this);
// Adds the back stack
stackBuilder.addParentStack(ResultActivity.class);
// Adds the Intent to the top of the stack
stackBuilder.addNextIntent(resultIntent);
// Gets a PendingIntent containing the entire back stack
PendingIntent resultPendingIntent =
stackBuilder.getPendingIntent(0, PendingIntent.FLAG_UPDATE_CURRENT);
NotificationCompat.Builder builder = new NotificationCompat.Builder(this);
builder.setContentIntent(resultPendingIntent);
NotificationManager mNotificationManager =
(NotificationManager) getSystemService(Context.NOTIFICATION_SERVICE);
mNotificationManager.notify(id, builder.build());
Edit:
Let me explain how it will works
Suppose you are set response from server as below
{
"registration_ids": ["XXX", ...],
"data": {
"id_offer": "41"
},
"notification": {
"title": "This is the Title",
"text": "Hello I'm a notification",
"icon": "ic_push",
"click_action": "ACTIVITY_XPTO"
}
}
And In your Manifest File
<activity android:name=".ActivityXPTO" android:screenOrientation="sensor" android:windowSoftInputMode="stateHidden"> <intent-filter> <action android:name="ACTIVITY_XPTO" />
<category android:name="android.intent.category.DEFAULT" /> </intent-filter> </activity>
When the app is closed or in background and the user clicks on the notification it opens my ActivityXPTO, to retrieve the id_offer I only need to do:
public class ActivityXPTO extends AppCompatActivity {
#Override
protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState);
String idOffer = "";
Intent startingIntent = getIntent();
if (startingIntent != null) {
idOffer = startingIntent.getStringExtra("id_offer");
// Retrieve the id
}
getOfferDetails(id_offer);
}
}
}
And In Second Way
Send key through data payload like below and get key in MainActivity via getIntent() and call specific activity or fragments.
json1.put("title","Your Title");
json1.put("body","body content");
json1.put("message","Your Message");
json1.put("screen","2"); //secondFragment is 2nd position in nav drawer
json.put("data", json1);
Sample project on GitHub.
Nothing works for me. The thing work for me is simple. Make sure you add this in the activity that you want to open directly.
<intent-filter>
<action android:name="MainActivity" />
<category android:name="android.intent.category.DEFAULT" />
</intent-filter>
And from the push notification you must add a new payload: click_action
it will looks like this -
"notification": {
"title": "hello",
"body": "test message",
"click_action": "MAIN_ACTIVITY"
},
Note: You can name it as you want MAIN_ACTIVITY but must be same in both place.

Categories

Resources