I am trying to make an android application where I receive notification using firebase. I followed resources available over the internet.
All I want to do is send notification from firebase, the message that I receive I want to display it in TextView in main activity.
Currently I am testing in an emulator. There are few problems that I am not able to resolve.
I am able to send notification from firebase but:
When the application is running in foreground I don't receive a notification in the android notification panel and nothing happens in the main activity too. That is the text in TextView does not change.
When the application is running in background I do receive the notification in android notification panel with message sent from firebase, clicking the notification main activity opens but the text in TextView does not change.
Firebase Messaging Service
public class VAFirebaseMessagingService extends FirebaseMessagingService {
private static final String TAG = "VAFirebaseMessagingS";
public VAFirebaseMessagingService() {}
#Override
public void onMessageReceived(RemoteMessage remoteMessage) {
super.onMessageReceived(remoteMessage);
Log.d(TAG, "From: " + remoteMessage.getFrom());
if(remoteMessage.getData().size() > 0) {
Log.d(TAG, "Message data payload: " + remoteMessage.getData());
sendNotification(remoteMessage.getData().get("text"));
}
if(remoteMessage.getNotification() != null) {
Log.d(TAG, "Message Notification Body: " + remoteMessage.getNotification().getBody());
sendNotification(remoteMessage.getNotification().getBody());
}
}
private void sendNotification(String messageBody) {
Intent intent = new Intent(this, MainActivity.class);
intent.addFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP);
intent.putExtra(Intent.EXTRA_TEXT, messageBody);
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.drawable.ic_stat_name);
notificationBuilder.setContentTitle("PFIVA");
notificationBuilder.setContentText(messageBody);
notificationBuilder.setAutoCancel(true);
notificationBuilder.setSound(defaultSoundUri);
notificationBuilder.setContentIntent(pendingIntent);
NotificationManager notificationManager = (NotificationManager) getSystemService(Context.NOTIFICATION_SERVICE);
notificationManager.notify(0, notificationBuilder.build());
}
}
Main Activity
public class MainActivity extends AppCompatActivity {
private TextView userFeedbackQuery;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
userFeedbackQuery = (TextView) findViewById(R.id.pfiva_user_feedback_query);
final Intent intent = getIntent();
if(intent.hasExtra(Intent.EXTRA_TEXT)) {
String userFeedbackQueryText = intent.getStringExtra(Intent.EXTRA_TEXT);
userFeedbackQuery.setText(userFeedbackQueryText);
}
}
}
Android Manifest
<?xml version="1.0" encoding="utf-8"?>
<manifest xmlns:android="http://schemas.android.com/apk/res/android"
package="de.pfiva.mobile.voiceassistant">
<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=".activities.MainActivity">
<intent-filter>
<action android:name="android.intent.action.MAIN" />
<category android:name="android.intent.category.LAUNCHER" />
</intent-filter>
</activity>
<service android:name=".messaging.FirebaseInstanceService">
<intent-filter>
<action android:name="com.google.firebase.INSTANCE_ID_EVENT" />
</intent-filter>
</service>
<service
android:name=".messaging.VAFirebaseMessagingService"
android:enabled="true"
android:exported="true">
<intent-filter>
<action android:name="com.google.firebase.MESSAGING_EVENT"/>
</intent-filter>
</service>
</application>
</manifest>
Please can someone guide what is wrong here? How can i solve the above two problems.
Thanks
After suggestions i made the below changes in Messaging Service, basically added notification channel.
private void sendNotification(String messageBody) {
Intent intent = new Intent(this, MainActivity.class);
intent.addFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP);
intent.putExtra(Intent.EXTRA_TEXT, messageBody);
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, CHANNEL_ID);
notificationBuilder.setSmallIcon(R.drawable.ic_stat_name);
notificationBuilder.setContentTitle("PFIVA");
notificationBuilder.setContentText(messageBody);
notificationBuilder.setPriority(NotificationCompat.PRIORITY_HIGH);
notificationBuilder.setAutoCancel(true);
notificationBuilder.setSound(defaultSoundUri);
notificationBuilder.setContentIntent(pendingIntent);
NotificationManager notificationManager = (NotificationManager) getSystemService(Context.NOTIFICATION_SERVICE);
// Create the NotificationChannel, but only on API 26+ because
// the NotificationChannel class is new and not in the support library
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.O) {
int importance = NotificationManager.IMPORTANCE_DEFAULT;
NotificationChannel channel = new NotificationChannel(CHANNEL_ID, CHANNEL_NAME, importance);
notificationManager.createNotificationChannel(channel);
}
notificationManager.notify(0, notificationBuilder.build());
}
Problem i face now is that when the app is running in background, i do receive notification in notification panel and clicking on it open main activity but the text in TextView is not updated.
Two ideas to solve your issue:
Have you register your VAFirebaseMessagingService in your AndroidManifest.xml:
Since Android 8, you must use an Notification Channel to send push notifications. Android
Related
Goal: click the button to jump out of the notification, the user can jump from the notification to another page.
The notification is displayed but clicking the notification cannot jump to the page.
I think the PendingIntent is wrong.
How to fix it?
public class MainActivity extends AppCompatActivity {
private String CHANNEL_ID = "Coder";
NotificationManager manager;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.O) {
NotificationChannel channel = new NotificationChannel(
CHANNEL_ID, "DemoCode", NotificationManager.IMPORTANCE_DEFAULT);
manager = getSystemService(NotificationManager.class);
assert manager != null;
manager.createNotificationChannel(channel);
}
Button btDefault,btCustom;
btDefault = findViewById(R.id.button_DefaultNotification);
btCustom = findViewById(R.id.button_CustomNotification);
btDefault.setOnClickListener(onDefaultClick);
}
private final View.OnClickListener onDefaultClick = new View.OnClickListener() {
#Override
public void onClick(View v) {
Intent nextIntent = new Intent(MainActivity.this, secondActivity.class);
PendingIntent pendingIntent = PendingIntent.getActivity(MainActivity.this, 0, nextIntent,PendingIntent.FLAG_IMMUTABLE);
NotificationCompat.Builder builder = new NotificationCompat.Builder(MainActivity.this, CHANNEL_ID);
builder.setContentTitle("Notification");
builder.setContentText("You have a new message");
builder.setSmallIcon(R.drawable.ic_baseline_accessible_forward_24);
builder.setContentIntent(pendingIntent);
builder.setAutoCancel(true);
manager.notify(1, builder.build());
}
Check if this works for you. As mentioned in android api
You should consider user's expected navigation experience. So for making the best navigation using pendingIntent with Notification, you should do as follow:
1. First define your app's hierarchy inside AndroidManifest.xml:
<activity
android:name=".MainActivity"
... >
<intent-filter>
<action android:name="android.intent.action.MAIN" />
<category android:name="android.intent.category.LAUNCHER" />
</intent-filter>
</activity>
<!-- MainActivity is the parent for SecondActivity -->
<activity
android:name=".SecondActivity"
android:parentActivityName=".MainActivity" />
...
</activity>
Now you told android that when a notification clicked, SecondActivity would be the child of MainActivity when user is navigating up.
2. Create PendingIntent using TaskStackBuilder:
Intent intent = new Intent(MainActivity.this, SecondActivity.class);
PendingIntent pendingIntent = TaskStackBuilder.create(MainActivity.this)
.addNextIntentWithParentStack(intent)
.getPendingIntent(0, PendingIntent.FLAG_IMMUTABLE)
Then you can set the PendingIntent we created to the notification. And now if user touches the notification, android system will navigate him to SecondActivity while holding MainActivity in back stack.
I'm trying to send a notification at a particular time, this part works perfectly but after I reboot the phone, the service doesn't get started unless the app is opened which then starts the service. I've tried multiple solutions online but still can't fix the issue.
Activity:
private void startNotificationAlarm() {
AlarmManager alarmManager = (AlarmManager) getSystemService(Context.ALARM_SERVICE);
Intent intent = new Intent(this, ReminderBroadcastReceiver.class);
PendingIntent pendingIntent = PendingIntent.getBroadcast(this, (int) ((new Date().getTime() / 1000L) % Integer.MAX_VALUE), intent, 0);
Objects.requireNonNull(alarmManager).setExact(AlarmManager.RTC_WAKEUP, calendar.getTimeInMillis(), pendingIntent);
BroadcastReceiver:
public class ReminderBroadcastReceiver extends BroadcastReceiver {
#Override
public void onReceive(Context context, Intent intent) {
if ("android.intent.action.BOOT_COMPLETED".equals(intent.getAction())) {
Intent serviceIntent = new Intent(context, BootService.class);
intent.setAction("<package>.Receiver");
context.startService(serviceIntent);
} else {
scheduleNotification(context, intent);
}
}
private void scheduleNotification(Context context, Intent intent) {
Notification notification = new NotificationCompat.Builder(context, BaseApp.CHANNEL_ID)
.setSmallIcon(R.drawable.ic_calendar_alert)
.setContentTitle(title)
.setContentText(message)
.setColor(color)
.setPriority(NotificationCompat.PRIORITY_HIGH)
.setCategory(NotificationCompat.CATEGORY_REMINDER)
.setAutoCancel(true)
.setOnlyAlertOnce(false)
.setStyle(new NotificationCompat.BigTextStyle().bigText(message))
.build();
NotificationManager notificationManager = (NotificationManager) context.getSystemService(Context.NOTIFICATION_SERVICE);
Objects.requireNonNull(notificationManager).notify((int) ((new Date().getTime() / 1000L) % Integer.MAX_VALUE), notification);
}
IntentService:
public class BootService extends IntentService {
public BootService() {
super("BootService");
}
#Override
protected void onHandleIntent(Intent intent) {
if (intent != null) {
try {
Thread.sleep(5000);
startNotification();
} catch (InterruptedException e) {
e.printStackTrace();
}
}
}
}
Manifest
<receiver
android:name=".Receiver.ReminderBroadcastReceiver" android:enabled="true" android:exported="false">
<intent-filter>
<action android:name="android.intent.action.BOOT_COMPLETED" />
<action android:name="android.intent.action.QUICKBOOT_POWERON" />
</intent-filter>
</receiver>
<service android:name=".Service.BootService"/>
You have to provide below permission in manifest:
<uses-permission android:name="android.permission.RECEIVE_BOOT_COMPLETED"/>
Also you have to make android:exported as true
as per android docs:
android:exported
Whether or not the broadcast receiver can receive messages from sources outside its application — "true" if it can, and
"false" if not. If "false", the only messages the broadcast receiver
can receive are those sent by components of the same application or
applications with the same user ID.
sample code
<receiver android:name=".sample.BootReceiver"
android:enabled="true"
android:exported="true">
<intent-filter>
<action android:name="android.intent.action.BOOT_COMPLETED"/>
</intent-filter>
</receiver>
I have problem that sometimes not received notification. In order to receive notification, I need to restart my application then execute notification.php and notification will appear.But after 30 minute/15 minute when i try again running notification.php , not received any notification (I need to run my app again). I hope you guys can help me solve this problem.Thank you in advance.
notification.php
<?php
require "../../init.php";
include("../../function_lib.php");
$id = $_GET['id'];
$title = "Try App";
$message = "news..";
$path_to_fcm = "https://fcm.googleapis.com/fcm/send"; //send push notification through this firebase url
$server_key = "####";
$topic = "/topics/reminder";
$type = "reminder";
//create http request to firease server
//request need 2 section : 1.header section 2. payload section
//add push notification in payload section
//header section for http request : that content authorization key and content_type of this application
//below are the header section of the http request
$headers = array(
'Authorization:key='.$server_key,
'Content-Type:application/json'
);
/*
$field = array('to'=>$topic,'notification'=>array("title"=>"add title","text"=>"add text","click_action"=>"OPEN_ACTIVITY_1"),
'data'=>array('title'=>$title,'body'=>$message,'type'=>$type,'id'=>$id),'priority'=>"high");
*/
//echo "\n".$key;
// to = refer to fcm token, notification refer to message that wull be use in push notification.
///below are the payload section.
$field = array('to'=>$topic,
'data'=>array('title'=>$title,'body'=>$message,'type'=>$type,'id'=>$id));
//perform json encode
$payload = json_encode($field);
//pass $payload (content json encode) variable to firebase server
//below gonna start url section.gonna use firebase url http to send json to firebase server.
$curl_session = curl_init();
curl_setopt($curl_session,CURLOPT_URL, $path_to_fcm);
curl_setopt($curl_session,CURLOPT_POST,true);
curl_setopt($curl_session,CURLOPT_HTTPHEADER,$headers);
curl_setopt($curl_session,CURLOPT_RETURNTRANSFER,true);
curl_setopt($curl_session,CURLOPT_SSL_VERIFYPEER, false);
curl_setopt($curl_session,CURLOPT_IPRESOLVE,CURL_IPRESOLVE_V4);
curl_setopt($curl_session,CURLOPT_POSTFIELDS, $payload);
//execute curl
$result = curl_exec($curl_session);
//close curl
curl_close($curl_session);
//close mysqli
//mysql_close($conn);
$path = "../dashboard.php?act=home";
echo ('<script>location.href="'.$path.'"</script>');
?>
AndroidManifest.xml
<?xml version="1.0" encoding="utf-8"?>
<manifest xmlns:android="http://schemas.android.com/apk/res/android"
package="com.mas.khoi.infoevent">
<uses-permission android:name="android.permission.INTERNET" />
<uses-permission android:name="android.permission.RECEIVE_BOOT_COMPLETED" />
<application
android:allowBackup="true"
android:icon="#drawable/icon_logo_only"
android:label="#string/app_name"
android:roundIcon="#mipmap/ic_launcher_round"
android:supportsRtl="true"
android:theme="#style/AppTheme">
<service android:name=".firebase.FcmInstanceIdService">
<intent-filter>
<action android:name="com.google.firebase.INSTANCE_ID_EVENT" />
</intent-filter>
</service>
<service android:name=".firebase.FcmMessagingService">
<intent-filter>
<action android:name="com.google.firebase.MESSAGING_EVENT" />
</intent-filter>
</service>
<activity android:name=".ScreenActivity">
<intent-filter>
<action android:name="android.intent.action.MAIN" />
<category android:name="android.intent.category.LAUNCHER" />
</intent-filter>
</activity>
<activity android:name=".fragment.MainActivity">
</activity>
<activity android:name=".EventDetailsActivity">
</activity>
</application>
</manifest>
FcmInstanceIdService.java
public class FcmInstanceIdService extends FirebaseInstanceIdService {
#Override
public void onTokenRefresh() {
//http://stackoverflow.com/questions/38340526/firebase-fcm-token-when-to-send-to-server
String recent_token = FirebaseInstanceId.getInstance().getToken();
//add token to sharepreference
SharedPreferences sharedPreferences = getApplicationContext().getSharedPreferences(Config.SETTING, Context.MODE_PRIVATE);
SharedPreferences.Editor editor = sharedPreferences.edit();
Log.i("generate token",recent_token);
editor.putString(Config.SETTING_FCM_TOKEN,recent_token);
editor.commit();
}
}
FcmMessagingService.java
public class FcmMessagingService extends FirebaseMessagingService {
#Override
public void onMessageReceived(RemoteMessage remoteMessage) {
//if want to use function below need to used change data to notification at $field at server side.
//String message = remoteMessage.getNotification().getBody();
//String title = remoteMessage.getNotification().getTitle();
if(remoteMessage.getData().size()>0){
Log.i("Notification Sucess",""+remoteMessage.getData());
startNotification(remoteMessage);
}else{
Log.i("Notification Failed",""+remoteMessage.getData());
}
}
public void startNotification(RemoteMessage remoteMessage){
String title = remoteMessage.getData().get("title");
String messsge = remoteMessage.getData().get("body");
String type = remoteMessage.getData().get("type");
String id = remoteMessage.getData().get("id");
Log.i("Notification","active");
//Log.i("Notificaition","type:"+type);
//Log.i("Notificaition","id:"+id);
//check if notification eihter is reminder or new quote/event
if (!type.equals("reminder") && id.equals("none")) {
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);
NotificationCompat.Builder notificationBuilder = new NotificationCompat.Builder(this);
notificationBuilder.setContentTitle(title);
notificationBuilder.setContentText(messsge);
notificationBuilder.setSmallIcon(R.drawable.icon_no_bg);
notificationBuilder.setAutoCancel(true);
notificationBuilder.setContentIntent(pendingIntent);
NotificationManager notificationManager = (NotificationManager) getSystemService(Context.NOTIFICATION_SERVICE);
notificationManager.notify(0, notificationBuilder.build());
//super.onMessageReceived(remoteMessage);
}else
if(type.equals("reminder") && ! id.equals("none")) {
Intent intent = new Intent(this, EventDetailsActivity.class);
intent.putExtra("id",id);
intent.addFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP);
PendingIntent pendingIntent = PendingIntent.getActivity(this, 0, intent, PendingIntent.FLAG_ONE_SHOT);
NotificationCompat.Builder notificationBuilder = new NotificationCompat.Builder(this);
notificationBuilder.setContentTitle(title);
notificationBuilder.setContentText(messsge);
notificationBuilder.setSmallIcon(R.drawable.icon_logo_only);
notificationBuilder.setAutoCancel(true);
notificationBuilder.setContentIntent(pendingIntent);
NotificationManager notificationManager = (NotificationManager) getSystemService(Context.NOTIFICATION_SERVICE);
notificationManager.notify(0, notificationBuilder.build());
}
}
}
Please check this reference about when onMessageReceived() method is fired.
onMessageReceived() is fired only if app is in foreground for notification messages but for data messages, it will always get handled.
Here's my problem:
I have an application which includes 3 activities.
-SplashscreenActivity (Launcher - Main)
-LoginActivity
-HomeActivity
--Application killed:--
Normal process:
when I run the application by the dashboard icon, I go through the splash, (i logged in), and coming up on the home.
If I put the application in background and I raise it by the dashboard icon, I go back on the home. Everything is normal.
--Application killed:--
However, for the following process:
I get a push notification. I run the application by this push, I go through the splash, and coming up on the home.
But if I put the application in the background, and I raise it by the dashboard icon, I go through by the splash again systematically. Here is the problem!
Here's my manifest.xml ( EDITED )
<activity
android:name="my.package.SplashscreenActivity"
android:label="#string/app_name"
android:noHistory="false"
android:screenOrientation="portrait">
<intent-filter>
<action android:name="android.intent.action.MAIN"/>
<category android:name="android.intent.category.LAUNCHER"/>
</intent-filter>
</activity>
<activity
android:name="my.package.LoginActivity"
android:label="#string/app_name"
android:noHistory="false"
android:screenOrientation="portrait"
android:windowSoftInputMode="adjustResize">
</activity>
<activity
android:name="my.package.HomeActivity"
android:label="#string/app_name"
android:noHistory="false"
android:launchMode="singleTask"
android:screenOrientation="portrait"
android:windowSoftInputMode="adjustResize">
</activity>
Here's my push notifications BroadcastReceiver (sendNotificationMethod)
private void sendNotification(String message, String title, int count, String type, long threadId)
{
Activity m_activity;
if (App.getInstance().m_currentActivity != null && App.getInstance().isOnPause())
m_activity = App.getInstance().m_currentActivity;
else
m_activity = null;
PendingIntent pendingIntent = null;
Intent intent = null;
if (m_activity != null)
{
intent = new Intent(this, m_activity.getClass());
intent.putExtra("type", type);
intent.setData((Uri.parse("foobar://" + SystemClock.elapsedRealtime())));
pendingIntent = PendingIntent.getActivity(this, 0, intent, 0);
}
else
{
PackageManager pm = getPackageManager();
intent = pm.getLaunchIntentForPackage("my.package");
intent.setAction(Intent.ACTION_MAIN);
intent.addCategory(Intent.CATEGORY_LAUNCHER);
intent.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
intent.putExtra("type", type);
pendingIntent = PendingIntent.getActivity(App.getInstance(), 0, intent, 0);
}
Uri defaultSoundUri = RingtoneManager.getDefaultUri(RingtoneManager.TYPE_NOTIFICATION);
NotificationCompat.Builder notificationBuilder = new NotificationCompat.Builder(this)
.setSmallIcon(R.mipmap.logo_push_lolilol)
.setColor(App.getInstance().getResources().getColor(R.color.colorPrimary))
.setContentTitle(title)
.setContentText(message)
.setAutoCancel(true)
.setSound(defaultSoundUri)
.setContentIntent(pendingIntent)
.setStyle(new NotificationCompat.BigTextStyle()
.bigText(message));
NotificationManager notificationManager = (NotificationManager) getSystemService(Context.NOTIFICATION_SERVICE);
notificationManager.notify((int)threadId, notificationBuilder.build());
}
Do you have "the solution"?
Thank you in advance.
Try this
intent.setAction("android.intent.action.MAIN");
intent.addCategory("android.intent.category.LAUNCHER");
intent.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
intent.addFlags(Intent.FLAG_ACTIVITY_REORDER_TO_FRONT);
I'm trying to send a push notification to all devices from firebase but at first i tried only in my phone, it doesn't work, after that i tried in another phone and it doesn't work either. Finally with the 3rd one it work and it work at the second one magically. What i have to do to the push notifications work in all devices?
Manifest ->
<manifest xmlns:android="http://schemas.android.com/apk/res/android"
package="com.startingandroid.firebasecloudmessaging">
<uses-permission android:name="android.permission.INTERNET"/>
<application
android:allowBackup="true"
android:icon="#mipmap/ic_launcher"
android:label="#string/app_name"
android:supportsRtl="true"
android:theme="#style/AppTheme">
<activity android:name=".SplashActivity" android:label="">
<intent-filter>
<action android:name="android.intent.action.MAIN" />
<category android:name="android.intent.category.LAUNCHER" />
</intent-filter>
</activity>
<activity android:name=".MainActivity" android:label="FCM"></activity>
<service
android:name=".MyFirebaseMessagingService">
<intent-filter>
<action android:name="com.google.firebase.MESSAGING_EVENT"/>
</intent-filter>
</service>
<service
android:name=".MyFirebaseInstanceIDService">
<intent-filter>
<action android:name="com.google.firebase.INSTANCE_ID_EVENT"/>
</intent-filter>
</service>
</application></manifest>
MyFirebaseInstanceIDService ->
public class MyFirebaseInstanceIDService extends FirebaseInstanceIdService {
private static final String TAG = "MyFirebaseIIDService";
#Override
public void onTokenRefresh() {
//Getting registration token
String refreshedToken = FirebaseInstanceId.getInstance().getToken();
//Displaying token in logcat
Log.e(TAG, "Refreshed token: " + refreshedToken);
}
private void sendRegistrationToServer(String token) {
//You can implement this method to store the token on your server
//Not required for current project
} }
MyFirebaseMessagingService ->
public class MyFirebaseMessagingService extends FirebaseMessagingService {
private static final String TAG = "StartingAndroid";
#Override
public void onMessageReceived(RemoteMessage remoteMessage) {
//It is optional
Log.e(TAG, "From: " + remoteMessage.getFrom());
Log.e(TAG, "Notification Message Body: " + remoteMessage.getNotification().getBody());
//Calling method to generate notification
sendNotification(remoteMessage.getNotification().getTitle(),remoteMessage.getNotification().getBody());
}
//This method is only generating push notification
private void sendNotification(String title, 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)
.setSmallIcon(R.mipmap.ic_launcher)
.setContentTitle(title)
.setContentText(messageBody)
.setAutoCancel(true)
.setSound(defaultSoundUri)
.setContentIntent(pendingIntent);
NotificationManager notificationManager =
(NotificationManager) getSystemService(Context.NOTIFICATION_SERVICE);
notificationManager.notify(0, notificationBuilder.build());
}}
SplashActivity
public class SplashActivity extends AppCompatActivity {
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
getWindow().requestFeature(Window.FEATURE_ACTION_BAR);
getSupportActionBar().hide();
getWindow().setFlags(WindowManager.LayoutParams.FLAG_FULLSCREEN,
WindowManager.LayoutParams.FLAG_FULLSCREEN);
setContentView(R.layout.activity_splash);
new Handler().postDelayed(new Runnable() {
#Override
public void run() {
Intent i = new Intent(SplashActivity.this,
MainActivity.class);
startActivity(i);
finish();
}
}, 4000);
}}