How to get context when application off? - android

In firebase messaging system, the onMessageReceived()method run when application off and get a push notification. So I want to use SQLite in onMessageReceived() method. SQLite must require a context, But I can't get an ApplicationContext in the method because of application is off. How to get application context when application off?
#Override
public void onMessageReceived(RemoteMessage remoteMessage) {
DatabaseHelper database = new DatabaseHelper(FirebaseMessagingService.this);
database.updateTicket(Integer.parseInt(remoteMessage.getData().get("idx")));
try{
Badges.setBadge(this, 1);
}catch(BadgesNotSupportedException e){
e.printStackTrace();
}
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);
String channelId = "Default";
NotificationCompat.Builder builder = new NotificationCompat.Builder(this, channelId)
.setSmallIcon(R.mipmap.ic_launcher)
.setContentTitle(remoteMessage.getNotification().getTitle())
.setContentText(remoteMessage.getNotification().getBody()).setAutoCancel(true).setContentIntent(pendingIntent);;
NotificationManager manager = (NotificationManager) getSystemService(NOTIFICATION_SERVICE);
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.O) {
NotificationChannel channel = new NotificationChannel(channelId, "Default channel", NotificationManager.IMPORTANCE_DEFAULT);
manager.createNotificationChannel(channel);
}
manager.notify(0, builder.build());
//sendPushNotification(remoteMessage.getData().get("title"), remoteMessage.getData().get("body"));
}
This is my onMessageReceived Code. The problem is database code where first two lines are doesn't work. I already checked it works on application on or application run on background.

Services has their own context and as FirebaseMessagingService extends Service
so you can use this or YourServiceClassName.this

Related

Unable to received notification in device notification section in android

This is my code to receive notification
public class FirebaseMessageReceiver
extends FirebaseMessagingService {
#Override
public void onMessageReceived(RemoteMessage remoteMessage) {
super.onMessageReceived(remoteMessage);
sendNotification(remoteMessage.getNotification().getTitle(),remoteMessage.getNotification().getBody());
}
private void sendNotification(String messageTitle,String messageBody) {
Intent intent = new Intent(this, NotificationActivity.class);
intent.addFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP);
PendingIntent pendingIntent = PendingIntent.getActivity(this,0 /* request code */, intent,PendingIntent.FLAG_UPDATE_CURRENT);
long[] pattern = {500,500,500,500,500};
Uri defaultSoundUri= RingtoneManager.getDefaultUri(RingtoneManager.TYPE_NOTIFICATION);
NotificationCompat.Builder notificationBuilder = (NotificationCompat.Builder) new NotificationCompat.Builder(this)
.setSmallIcon(R.drawable.ic_launcher_background)
.setContentTitle(messageTitle)
.setContentText(messageBody)
.setAutoCancel(true)
.setVibrate(pattern)
.setLights(Color.BLUE,1,1)
.setSound(defaultSoundUri)
.setContentIntent(pendingIntent);
NotificationManager notificationManager = (NotificationManager) getSystemService(Context.NOTIFICATION_SERVICE);
notificationManager.notify(0 /* ID of notification */, notificationBuilder.build());
}
}
i am trying to received notification from firebase console i am able to get to get call back when fire notification i am also getting title and msg code executed successfully but i am unable to see notification in notification section of device can any one please help me what i am doing mistake .
Do you use notification channel?
If you are using Adroid 8 or higher it's expected behavior:
Starting in Android 8.0 (API level 26), all notifications must be
assigned to a channel or it will not appear.
https://developer.android.com/guide/topics/ui/notifiers/notifications#ManageChannels
Here you can find detail tutorial how to create notification channel:
https://developer.android.com/training/notify-user/channels
For devices running Android O or higher, you need to create a notification channel first in order to receive notifications like this:
private void createNotificationChannel() {
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.O) {
NotificationChannel channel = new NotificationChannel(
CHANNEL_ID,
"Channel 1",
NotificationManager.IMPORTANCE_HIGH
);
channel.setDescription("This is Channel 1");
NotificationManager manager = getSystemService(NotificationManager.class);
manager.createNotificationChannel(channel);
}
}
Also, you need to pass this CHANNEL_ID constant in NotificationCompact.Builder constructor like this:
NotificationCompat.Builder notificationBuilder = (NotificationCompat.Builder) new NotificationCompat.Builder(this, CHANNEL_ID)

Adding "Remind me later" option in Android notification

I am working on a simple Water Reminder app. One of the final things that are left to implement is adding "Remind me later" option when the reminder notification pops. I've searched in many similar questions and articles but I didn't find solution. The thing is that I dont even know what i'm supposed to do...Start some activity, or send something to broadcast receiver or something else. I don't even know how to start trying different approaches. I will be very thankfull if someone helps me! Below is the code. What can I add to the code to implement this function?
public class ReminderManager {
public void createNotificationChannel() {
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.O) {
Uri soundUri = Uri.parse(Constants.PATH_TO_NOTIFICATION_RINGTONE);
AudioAttributes audioAttributes = new AudioAttributes.Builder()
.setContentType(AudioAttributes.CONTENT_TYPE_SONIFICATION)
.setUsage(AudioAttributes.USAGE_ALARM)
.build();
NotificationChannel notificationChannel = new NotificationChannel
(Constants.NOTIFICATION_CHANNEL_ID, "WaterReminderChannel", NotificationManager.IMPORTANCE_HIGH);
notificationChannel.setSound(soundUri, audioAttributes);
notificationChannel.setDescription("Channel for Water Reminder");
NotificationManager notificationManager = context.getSystemService(NotificationManager.class);
notificationManager.createNotificationChannel(notificationChannel);
}
}
public void setReminder() {
Intent intent = new Intent(context, ReminderBroadcastReceiver.class);
PendingIntent pendingIntentForBroadcast = PendingIntent.getBroadcast(context, 0, intent, 0);
AlarmManager alarmManager = (AlarmManager) context.getSystemService(ALARM_SERVICE);
AlarmManagerCompat.setExactAndAllowWhileIdle(alarmManager, AlarmManager.RTC_WAKEUP,
System.currentTimeMillis() + MainActivity.reminderTime, pendingIntentForBroadcast);
}
public class ReminderBroadcastReceiver extends BroadcastReceiver {
#Override
public void onReceive(Context context, Intent i) {
if (MainActivity.reminderTime > 0 && !MainActivity.dayFinished) {
Intent intent = new Intent(context, MainActivity.class);
PendingIntent pendingIntent = PendingIntent.getActivity(context, 0, intent, 0);
Uri soundUri = Uri.parse(Constants.PATH_TO_NOTIFICATION_RINGTONE);
Notification notification = new NotificationCompat.Builder(context, Constants.NOTIFICATION_CHANNEL_ID)
.setSmallIcon(R.mipmap.water)
.setContentTitle("Water Reminder")
.setContentText("It's time to drink something!")
.setPriority(NotificationCompat.PRIORITY_HIGH)
.setSound(soundUri)
.setDefaults(Notification.DEFAULT_VIBRATE)
.setContentIntent(pendingIntent)
.setAutoCancel(true)
.build();
NotificationManagerCompat notificationManager = NotificationManagerCompat.from(context);
notificationManager.notify(1, notification);
}
}
If I understand you correctly, I believe the simplest way to handle this is to use Notification “action buttons.” See https://developer.android.com/training/notify-user/build-notification for more detail.
Thanks. Your information helped me to solve the problem. I've made it and want to share my code because it's very simple and maybe will save someone's time instead of searching alot of complicated solutions like I did.
So, below is the code that set alarm for specified by the user time, then after that time occurs the BroadcastReceiver gets triggered even when the phone is in idle state thanks to "AlarmManagerCompat.setExactAndAllowWhileIdle" (works for older and newer Android versions). Then the receiver checks by which action is triggered - SNOOZE or REMINDER. If it's SNOOZE, it calls the setReminder() method of my custom ReminderManager class to reset the alarm and then calls notificationManager.cancelAll() to remove the previous notification banner. If it's REMINDER then it calls the showNotification() method which build the notification and show it to the user (I don't find the need to build the notification before the time when the AlarmManager is set to trigger the receiver).
In my ReminderManager class I have createNotificationChannel() method which is needed for newer Android versions and I call it in onCreate of MainActivity. The setReminder() method is called from places that it needs the reminder to be set (when the user sets notification and from the BroadcastReciever as described above) and the showNotification() method is called from BroadcastReciever as described above.
public class BroadcastReceiver extends android.content.BroadcastReceiver {
#Override
public void onReceive(Context context, Intent intent) {
ReminderManager reminderManager = new ReminderManager(context);
NotificationManagerCompat notificationManager = NotificationManagerCompat.from(context);
if (intent.getAction().equals(Constants.SNOOZE_ACTION)) {
reminderManager.setReminder();
notificationManager.cancelAll();
} else if (intent.getAction().equals(Constants.REMINDER_ACTION)) {
reminderManager.showNotification();
}
}
}
public class ReminderManager {
private final Context context;
public ReminderManager(Context context) {
this.context = context;
}
public void createNotificationChannel() {
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.O) {
AudioAttributes audioAttributes = new AudioAttributes.Builder()
.setContentType(AudioAttributes.CONTENT_TYPE_SONIFICATION)
.setUsage(AudioAttributes.USAGE_ALARM)
.build();
NotificationChannel notificationChannel = new NotificationChannel
(Constants.NOTIFICATION_CHANNEL_ID, "WaterReminderChannel",
NotificationManager.IMPORTANCE_HIGH);
notificationChannel.setSound
(RingtoneManager.getDefaultUri(RingtoneManager.TYPE_NOTIFICATION), audioAttributes);
notificationChannel.setDescription("Channel for Water Reminder");
NotificationManager notificationManager =
context.getSystemService(NotificationManager.class);
notificationManager.createNotificationChannel(notificationChannel);
}
}
public void setReminder() {
Intent intent = new Intent(context, BroadcastReceiver.class);
intent.setAction(Constants.REMINDER_ACTION);
PendingIntent pendingIntentForBroadcast =
PendingIntent.getBroadcast(context, 0, intent, 0);
AlarmManager alarmManager = (AlarmManager) context.getSystemService(ALARM_SERVICE);
AlarmManagerCompat.setExactAndAllowWhileIdle(alarmManager, AlarmManager.RTC_WAKEUP,
System.currentTimeMillis()
+ MainActivity.reminderTime, pendingIntentForBroadcast);
}
public void showNotification() {
Intent maniActivityIntent = new Intent(context, MainActivity.class);
PendingIntent mainActivityPendingIntent =
PendingIntent.getActivity(context, 0, maniActivityIntent, 0);
Intent snoozeIntent = new Intent(context, BroadcastReceiver.class);
snoozeIntent.setAction(Constants.SNOOZE_ACTION);
PendingIntent snoozePendingIntent =
PendingIntent.getBroadcast(context, 0, snoozeIntent, 0);
Notification notification = new NotificationCompat.Builder(context, Constants.NOTIFICATION_CHANNEL_ID)
.setSmallIcon(R.mipmap.water)
.setContentTitle("Water Reminder")
.setContentText("It's time to drink something!")
.setPriority(NotificationCompat.PRIORITY_HIGH)
.setSound(RingtoneManager.getDefaultUri(RingtoneManager.TYPE_NOTIFICATION))
.setDefaults(Notification.DEFAULT_VIBRATE)
.setContentIntent(mainActivityPendingIntent)
.addAction(android.R.drawable.ic_lock_idle_alarm, "Remind me later", snoozePendingIntent)
.setAutoCancel(true)
.build();
NotificationManagerCompat notificationManager = NotificationManagerCompat.from(context);
notificationManager.notify(0, notification);
}
}

Cannot resolve Method "builder()"

I want to send notifications to topics with FCM without using the Firebase console. When I build a new message with the help of Firebase Documentation it´s a problem.
Picture of the problem
Here my Codes:
public void sendToTopic() {
Message message = Message.builder()
.putData("score", "850")
.putData("time", "2:45")
.setTopic("1")
.build();
}
public class MyFirebaseMessagingService extends FirebaseMessagingService {
private static final String TAG = "MyFirebaseMsgService";
public void onMessageReceived(RemoteMessage remoteMessage) {
}
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 /* Request code */, intent,
PendingIntent.FLAG_ONE_SHOT);
String channelId = ("asda");
Uri defaultSoundUri = RingtoneManager.getDefaultUri(RingtoneManager.TYPE_NOTIFICATION);
NotificationCompat.Builder notificationBuilder =
new NotificationCompat.Builder(this, channelId)
.setSmallIcon(R.drawable.book_icon)
.setContentTitle("Test")
.setContentText(messageBody)
.setAutoCancel(true)
.setSound(defaultSoundUri)
.setContentIntent(pendingIntent);
NotificationManager notificationManager =
(NotificationManager) getSystemService(Context.NOTIFICATION_SERVICE);
// Since android Oreo notification channel is needed.
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.O) {
NotificationChannel channel = new NotificationChannel(channelId,
"Channel human readable title",
NotificationManager.IMPORTANCE_DEFAULT);
notificationManager.createNotificationChannel(channel);
}
notificationManager.notify(0 /* ID of notification */, notificationBuilder.build());
}
}
The Message class is inside the Firebase admin sdk but you cannot use that in your android project, you can only use firebase admin sdk in the server side and there you will be able to use the Message class. Check the docs for reference:-
https://firebase.google.com/docs/cloud-messaging/manage-topics

Android notifications not showing

I'm trying to make a daily notification which will be show at a specific time.
Unfortunately it doesn't show.
I tried to follow couples tuto (also from developer.android.com) and checked similar questions that have already been asked. To save hour I'm using Hawk library.
Intent intent = new Intent(getContext(), AlarmReceiver.class);
int notificationId = 1;
intent.putExtra("notificationId", notificationId);
PendingIntent alarmIntent = PendingIntent.getBroadcast(getContext(), 0,
intent,PendingIntent.FLAG_NO_CREATE);
AlarmManager alarm = (AlarmManager) getContext().getSystemService(getContext().ALARM_SERVICE);
switch (view.getId()) {
int hour = timePicker.getCurrentHour();
int minute = timePicker.getCurrentMinute();
// Create time
....
//set alarm
alarm.setRepeating(AlarmManager.RTC_WAKEUP, alarmStartTime, AlarmManager.INTERVAL_DAY, alarmIntent);
Hawk.put("notification_hour", alarmStartTime);
break;
case R.id.cancel_button:
//cancel notification
break;
}
}
and here AlarmReceiver class
public class AlarmReceiver extends BroadcastReceiver {
public AlarmReceiver () {
}
#Override
public void onReceive(Context context, Intent intent) {
sendNotification(context, intent);
}
private void sendNotification(Context con, Intent intent) {
int notificationId = intent . getIntExtra ("notificationId", 1);
String message = " message";
Intent mainIntent = new Intent(con, MainActivity.class);
PendingIntent contentIntent = PendingIntent . getActivity (con, 0, mainIntent, 0);
NotificationManager myNotificationManager =(NotificationManager) con . getSystemService (Context.NOTIFICATION_SERVICE);
Notification.Builder builder = new Notification.Builder(con);
builder.setSmallIcon(android.R.drawable.ic_dialog_info)
.setContentTitle("Reminder")
.setContentText(message)
.setWhen(System.currentTimeMillis())
.setAutoCancel(true)
.setContentIntent(contentIntent)
.setPriority(Notification.PRIORITY_MAX)
.setDefaults(Notification.DEFAULT_ALL);
myNotificationManager.notify(notificationId, builder.build());
}
}
In OREO, they have redesigned notifications to provide an easier and more consistent way to manage notification behavior and settings. Some of these changes include:
Notification channels: Android 8.0 introduces notification channels that allow you to create a user-customizable channel for each type of notification you want to display.
Notification dots: Android 8.0 introduces support for displaying dots, or badges, on app launcher icons. Notification dots reflect the presence of notifications that the user has not yet dismissed or acted on.
Snoozing: Users can snooze notifications, which causes them to disappear for a period of time before reappearing. Notifications reappear with the same level of importance they first appeared with.
Messaging style: In Android 8.0, notifications that use the MessagingStyle class display more content in their collapsed form. You should use theMessagingStyle class for notifications that are messaging-related.
Here, we have created the NotificationHelper class that require the Context as the constructor params. NOTIFICATION_CHANNEL_ID variable has been initialize in order to set the channel_id to NotificationChannel.
The method createNotification(…) requires title and message parameters in order to set the title and content text of the notification. In order to handle the notification click event we have created the pendingIntent object, that redirect towards SomeOtherActivity.class.
Notification channels allow you to create a user-customizable channel for each type of notification you want to display. So, if the android version is greater or equals to 8.0, we have to create the NotificationChannel object and set it to createNotificationChannel(…) setter property of NotificationManager.
public class NotificationHelper {
private Context mContext;
private NotificationManager mNotificationManager;
private NotificationCompat.Builder mBuilder;
public static final String NOTIFICATION_CHANNEL_ID = "10001";
public NotificationHelper(Context context) {
mContext = context;
}
/**
* Create and push the notification
*/
public void createNotification(String title, String message)
{
/**Creates an explicit intent for an Activity in your app**/
Intent resultIntent = new Intent(mContext , SomeOtherActivity.class);
resultIntent.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
PendingIntent resultPendingIntent = PendingIntent.getActivity(mContext,
0 /* Request code */, resultIntent,
PendingIntent.FLAG_UPDATE_CURRENT);
mBuilder = new NotificationCompat.Builder(mContext);
mBuilder.setSmallIcon(R.mipmap.ic_launcher);
mBuilder.setContentTitle(title)
.setContentText(message)
.setAutoCancel(false)
.setSound(Settings.System.DEFAULT_NOTIFICATION_URI)
.setContentIntent(resultPendingIntent);
mNotificationManager = (NotificationManager) mContext.getSystemService(Context.NOTIFICATION_SERVICE);
if (android.os.Build.VERSION.SDK_INT >= android.os.Build.VERSION_CODES.O)
{
int importance = NotificationManager.IMPORTANCE_HIGH;
NotificationChannel notificationChannel = new NotificationChannel(NOTIFICATION_CHANNEL_ID, "NOTIFICATION_CHANNEL_NAME", importance);
notificationChannel.enableLights(true);
notificationChannel.setLightColor(Color.RED);
notificationChannel.enableVibration(true);
notificationChannel.setVibrationPattern(new long[]{100, 200, 300, 400, 500, 400, 300, 200, 400});
assert mNotificationManager != null;
mBuilder.setChannelId(NOTIFICATION_CHANNEL_ID);
mNotificationManager.createNotificationChannel(notificationChannel);
}
assert mNotificationManager != null;
mNotificationManager.notify(0 /* Request Code */, mBuilder.build());
}
Just include a NotificationChannel and set a channel id to it.

Notification not received in android API eval 26 [duplicate]

This question already has answers here:
Notification not showing in Oreo
(24 answers)
Closed 4 years ago.
I try to receive notification in android Oreo. But App does not receive any
notification. I also create notification Chanel but it's not work
If I send a notification from fcm then app received. but using the token app not received any notification. In other lower, version notification work proper. In Oreo it does not work.
Here is my MyFirebaseMessagingService class:
public class MyFirebaseMessagingService extends FirebaseMessagingService {
public static int NOTIFICATION_ID = 1;
public static final String NOTIF_CHANNEL_ID = "my_channel_01";
#Override
public void onMessageReceived(RemoteMessage remoteMessage) {
super.onMessageReceived(remoteMessage);
sendNotification(remoteMessage.getData());
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.O) {
createNotifChannel(this);
}
}
#RequiresApi(api = Build.VERSION_CODES.O)
private void createNotifChannel(MyFirebaseMessagingService
myFirebaseMessagingService)
{
NotificationChannel channel = new NotificationChannel(NOTIF_CHANNEL_ID,
"MyApp events", NotificationManager.IMPORTANCE_LOW);
// Configure the notification channel
channel.setDescription("MyApp event controls");
channel.setShowBadge(false);
channel.setLockscreenVisibility(Notification.VISIBILITY_PUBLIC);
NotificationManager manager = getApplicationContext().
getSystemService(NotificationManager.class);
manager.createNotificationChannel(channel);
Log.d(TAG, "createNotifChannel: created=" + NOTIF_CHANNEL_ID);
}
private void sendNotification(Map<String, String> data) {
int num = ++NOTIFICATION_ID;
Bundle msg = new Bundle();
for (String key : data.keySet()) {
Log.e(key, data.get(key));
msg.putString(key, data.get(key));
}
Intent intent = new Intent(this, HomeActivity.class);
if (msg.containsKey("action")) {
intent.putExtra("action", msg.getString("action"));
}
intent.addFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP);
PendingIntent pendingIntent = PendingIntent.getActivity(this, num /*
Request code */, intent,
PendingIntent.FLAG_ONE_SHOT);
Uri defaultSoundUri =
RingtoneManager.getDefaultUri(RingtoneManager.TYPE_NOTIFICATION);
NotificationCompat.Builder notificationBuilder = new
NotificationCompat.Builder(this)
.setSmallIcon(instauser.application.apps.R.drawable.icon)
.setContentTitle(msg.getString("title"))
.setContentText(msg.getString("msg"))
.setAutoCancel(true)
.setSound(defaultSoundUri)
.setContentIntent(pendingIntent);
NotificationManager notificationManager =
(NotificationManager)
getSystemService(Context.NOTIFICATION_SERVICE);
notificationManager.notify(num, notificationBuilder.build());
}
}
I also create a notification channel but it's not work
You created notification channel, but didn't set it to notification
NotificationCompat.Builder notificationBuilder = new NotificationCompat.Builder(this)
...
.setChannelId(NOTIF_CHANNEL_ID)

Categories

Resources