How to add click event in push notification? - java

I have tried to add a click event onto the push notification but I get an error every time. Without the click event, it works fine. It is showing the notification perfectly on time. I have tried to do this with an Intent.
Is this the way to do it?How do I implement a click event on the notification itself?
Here is what I currently have:
public class MyFirebaseInstanceService extends FirebaseMessagingService {
#Override
public void onMessageReceived(#NonNull RemoteMessage remoteMessage) {
super.onMessageReceived(remoteMessage);
if (remoteMessage.getData().isEmpty()){
showNotification(remoteMessage.getNotification().getTitle(),remoteMessage.getNotification().getBody());
}else {
showNotification(remoteMessage.getData());
}
}
private void showNotification(Map<String,String> data){
String title=data.get("title").toString();
String body=data.get("body").toString();
NotificationManager notificationManager=(NotificationManager)getSystemService(Context.NOTIFICATION_SERVICE);
String NOTIFICATION_CHANNEL_ID="example.mfree.services.test";
if (android.os.Build.VERSION.SDK_INT >= android.os.Build.VERSION_CODES.O) {
NotificationChannel notificationChannel=new NotificationChannel(NOTIFICATION_CHANNEL_ID,"Notification",
NotificationManager.IMPORTANCE_DEFAULT);
notificationChannel.setDescription("Dipu");
notificationChannel.enableLights(true);
notificationChannel.setLightColor(Color.BLUE);
notificationChannel.enableLights(true);
notificationManager.createNotificationChannel(notificationChannel);
}
NotificationCompat.Builder notificationBuilder=new NotificationCompat.Builder(this,NOTIFICATION_CHANNEL_ID);
notificationBuilder.setAutoCancel(true).setDefaults(Notification.DEFAULT_ALL).
setWhen(System.currentTimeMillis()).setSmallIcon(R.drawable.ic_money)
.setContentTitle(title)
.setContentText(body)
.setContentInfo("Info");
notificationManager.notify(new Random().nextInt(),notificationBuilder.build());
}
private void showNotification(String title,String body){
NotificationManager notificationManager=(NotificationManager)getSystemService(Context.NOTIFICATION_SERVICE);
String NOTIFICATION_CHANNEL_ID="com.example.mfree.services.test";
Intent intent = new Intent(getApplicationContext(), Notification_send_Activity.class);
startActivity(intent);
if (android.os.Build.VERSION.SDK_INT >= android.os.Build.VERSION_CODES.O) {
NotificationChannel notificationChannel=new NotificationChannel(NOTIFICATION_CHANNEL_ID,"Notification",
NotificationManager.IMPORTANCE_DEFAULT);
notificationChannel.setDescription("Dipu");
notificationChannel.enableLights(true);
notificationChannel.setLightColor(Color.BLUE);
notificationChannel.enableLights(true);
notificationManager.createNotificationChannel(notificationChannel);
}
NotificationCompat.Builder notificationBuilder=new NotificationCompat.Builder(this,NOTIFICATION_CHANNEL_ID);
notificationBuilder.setAutoCancel(true).setDefaults(Notification.DEFAULT_ALL).
setWhen(System.currentTimeMillis()).setSmallIcon(R.drawable.ic_money)
.setContentTitle(title)
.setContentText(body)
.setContentInfo("Info");
notificationManager.notify(new Random().nextInt(),notificationBuilder.build());
}
#Override
public void onNewToken(#NonNull String s) {
super.onNewToken(s);
Log.d("TOKENFIREBASE",s);
}
}

You need to add an action
Notification.Action action = new NotificationCompat.Action(icon, title, pendingIntent);
Notification notification = new NotificationCompat.Builder(context)
.addAction(action)
.build();

Related

New Activity not opening on push notification click

I have a class Home.java which runs first on opening the app when I open it to check if the user is logged in or not.
public class Home extends Application {
#Override
public void onCreate() {
super.onCreate();
FirebaseAuth firebaseAuth = FirebaseAuth.getInstance();
FirebaseUser firebaseUser = firebaseAuth.getCurrentUser();
if (firebaseUser != null) {
Intent intent = new Intent(getApplicationContext(), HomeActivity.class);
intent.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK | Intent.FLAG_ACTIVITY_CLEAR_TASK);
startActivity(intent);
}
}
}
The issue I'm facing is when I'm getting a notification for this app, it is starting from LogIn activity instead of going to HomeActivity.
I'm aware that if I want to open a specific activity from a notification, I need to specify getIntent() in the launcher activity, but I don't have any launcher activity.
When I try to implement getIntent() in Home.java class the method is not getting imported since it doesn't extends the Activity class.
Any help!
NotificationService.java
public class NotificationService extends FirebaseMessagingService {
Uri uri = RingtoneManager.getDefaultUri(RingtoneManager.TYPE_NOTIFICATION);
#Override
public void onMessageReceived(RemoteMessage remoteMessage) {
super.onMessageReceived(remoteMessage);
String title = remoteMessage.getNotification().getTitle();
String body = remoteMessage.getNotification().getBody();
NotificationCompat.Builder notificationBuilder =
new NotificationCompat.Builder(this, "Restaurants")
.setContentTitle(title)
.setContentText(body)
.setSmallIcon(R.drawable.ic_launcher_background)
.setSound(uri); //applying default notification sound to the notification
NotificationManager notificationManager = (NotificationManager) getSystemService(NOTIFICATION_SERVICE);
int id = (int) System.currentTimeMillis();
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.O) {
NotificationChannel notificationChannel = new NotificationChannel("Restaurants", "demo", NotificationManager.IMPORTANCE_HIGH);
notificationManager.createNotificationChannel(notificationChannel);
}
notificationManager.notify(id, notificationBuilder.build());
}
}
When you want open an activity when click to Notification then use a code like this:
#Override
public void onMessageReceived(RemoteMessage remoteMessage) {
super.onMessageReceived(remoteMessage);
String title = remoteMessage.getNotification().getTitle();
String body = remoteMessage.getNotification().getBody();
NotificationCompat.Builder notificationBuilder =
new NotificationCompat.Builder(this, "Restaurants")
.setContentTitle(title)
.setContentText(body)
.setSmallIcon(R.drawable.ic_launcher_background)
.setSound(uri); //applying default notification sound to the notification
//Create an intent to gom HomeActivity
Intent intent = new Intent(this, HomeActivity.class);
PendingIntent pendingIntent = PendingIntent.getActivity(this, 0, intent, PendingIntent.FLAG_UPDATE_CURRENT);
notificationBuilder.setContentIntent(pendingIntent);
NotificationManager notificationManager = (NotificationManager) getSystemService(NOTIFICATION_SERVICE);
int id = (int) System.currentTimeMillis();
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.O) {
NotificationChannel notificationChannel = new NotificationChannel("Restaurants", "demo", NotificationManager.IMPORTANCE_HIGH);
notificationManager.createNotificationChannel(notificationChannel);
}
notificationManager.notify(id, notificationBuilder.build());
}

not receiving foreground notification with FirebaseMessaging but working in background

I've added a FirebaseMessagingService class to receive foreground notifications.
I don't receive foreground notifications.
In background when app minimized it works fine.
I've set the background notification with firebase functions and it works fine, now im trying to get this notification in foreground but the notifications doesn't appear.
my FirebaseMessagingService class:
public class FirebaseMessaging extends FirebaseMessagingService {
#Override
public void onMessageReceived(#NonNull RemoteMessage remoteMessage) {
super.onMessageReceived(remoteMessage);
if (remoteMessage.getNotification() != null) {
String notification_title = remoteMessage.getNotification().getTitle();
String notification_message = remoteMessage.getNotification().getBody();
Notification.Builder mBuilder = new Notification.Builder(this)
.setContentTitle(notification_title)
.setContentText(notification_message)
.setSmallIcon(R.drawable.default_avatar);
int mNotificationId = (int) System.currentTimeMillis();
NotificationManager mNotifyMgr = (NotificationManager) getSystemService(NOTIFICATION_SERVICE);
mNotifyMgr.notify(mNotificationId, mBuilder.build());
}
}
}
No error messages:
Actual results: notification never arrives in foreground.
Expected results: i want to receive the notification while im in the app not only when minimized.
i changed my FirebaseMEssagingService class to this it worked:
public class FirebaseMessaging extends FirebaseMessagingService {
private final String CHANNEL_ID = "personal_notifications";
#Override
public void onMessageReceived(#NonNull RemoteMessage remoteMessage) {
super.onMessageReceived(remoteMessage);
NotificationManager mNotifyMgr = (NotificationManager) getSystemService(NOTIFICATION_SERVICE);
String notification_title = remoteMessage.getNotification().getTitle();
String notification_message = remoteMessage.getNotification().getBody();
NotificationManager notificationManager = (NotificationManager) getSystemService(NOTIFICATION_SERVICE);
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.O) {
NotificationChannel notificationChannel = new NotificationChannel(CHANNEL_ID, "My Notifications", NotificationManager.IMPORTANCE_HIGH);
NotificationCompat.Builder mBuilder =
new NotificationCompat.Builder(this, CHANNEL_ID)
.setSmallIcon(R.drawable.default_avatar)
.setContentTitle(notification_title)
.setContentText(notification_message);
notificationManager.createNotificationChannel(notificationChannel);
int mNotificationId = (int) System.currentTimeMillis();
mNotifyMgr.notify(mNotificationId, mBuilder.build());
}
}
}

Android notification dont open activity?

I have an app that sends/receives notification using Firebase. Im sending the notification with no problem, but if the app is open the notification display an square instead of the smallicon also if i click the notification nothing happens, but if i'm using a different app i receive the notification and the notification show the correct icon and also opens the app.
public class MyMessagingService extends FirebaseMessagingService {
#Override
public void onMessageReceived(RemoteMessage remoteMessage) {
super.onMessageReceived(remoteMessage);
showNotification(remoteMessage.getNotification().getTitle(), remoteMessage.getNotification().getBody());
}
public void showNotification(String title, String message) {
NotificationCompat.Builder builder = new NotificationCompat.Builder(this, "MyNotifitcation")
.setContentTitle(title)
.setSmallIcon(R.drawable.ic_launcher_background)
.setAutoCancel(true)
.setContentText(message);
NotificationManagerCompat manager = NotificationManagerCompat.from(this);
manager.notify(999, builder.build());
}
}
public class MainActivity extends AppCompatActivity {
private String TAG = MainActivity.class.getSimpleName();
String title;
#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("MyNotifitcation", "MyNotifitcation", NotificationManager.IMPORTANCE_DEFAULT);
NotificationManager manager = getSystemService(NotificationManager.class);
manager.createNotificationChannel(channel);
}
FirebaseMessaging.getInstance().subscribeToTopic("general").addOnCompleteListener(new OnCompleteListener<Void>() {
#Override
public void onComplete(#NonNull Task<Void> task) {
String msg = "Successfull";
if (!task.isSuccessful()) {
msg = "Failed";
}
// Toast.makeText(MainActivity.this, msg, Toast.LENGTH_SHORT).show();
}
});
}
}
For Notification click add Pending intent to notification builder. and for adding image/icon to notification use setSmallIcon() in notification builder. below is my notification code.
private void sendNotification(String body, String title) {
Intent intent = new Intent(this, NotificationActivity.class);
intent.addFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP);
intent.putExtra("action_type", "notify");
PendingIntent pendingIntent = PendingIntent.getService(getApplicationContext(), 0, intent,
PendingIntent.FLAG_ONE_SHOT);
NotificationCompat.Builder notificationBuilder = new
NotificationCompat.Builder(this,"channel")
.setSmallIcon(R.drawable.logo)
// .setContent(contentView)
.setContentTitle("title")
.setContentText("body")
.setAutoCancel(true)
.setContentIntent(pendingIntent);
Notification notification = notificationBuilder.build();
NotificationManager notificationManager = (NotificationManager) getSystemService(NOTIFICATION_SERVICE);
notificationManager.notify(0, notification);
}
See below code. Opening Activity.
original post credit
NotificationManager notificationManager = (NotificationManager) context
.getSystemService(Context.NOTIFICATION_SERVICE);
Notification notification = new Notification(icon, message, when);
Intent notificationIntent = new Intent(context, HomeActivity.class);
notificationIntent.setFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP
| Intent.FLAG_ACTIVITY_SINGLE_TOP);
PendingIntent intent = PendingIntent.getActivity(context, 0,
notificationIntent, 0);
notification.setLatestEventInfo(context, title, message, intent);
notification.flags |= Notification.FLAG_AUTO_CANCEL;
notificationManager.notify(0, notification);

How to repeat android notifications after some Interval of hours

I am stuck with my app which needs to repeat one notification after one hour (Medical purpose). As my field is totally opposite and I am noob in coding any help will be appreciated. I know I have to add something in notification receiver to repeat notifications. But every time I try to repeat the app crashes.
(This is a little but unique idea to solve a real world problem I will credit everyone from whom I've received even a little help )
Here is my MainActivity
private NotificationManagerCompat manager;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
manager = NotificationManagerCompat.from(this);
}
public void Shownotification(View v) {
String title = "You Did it!";
String message = "Some Text";
Notification notification = new NotificationCompat.Builder(this, CHANNEL_1_ID)
.setSmallIcon(R.drawable.ic_launcher_foreground)
.setContentTitle(title)
.setContentText(message)
.setPriority(NotificationCompat.PRIORITY_HIGH)
.setCategory(NotificationCompat.CATEGORY_MESSAGE)
.build();
manager.notify(0,notification);
}
Notification Channel
public class App extends Application {
public static final String CHANNEL_1_ID = "channel1";
public static final String CHANNEL_2_ID = "channel2";
#Override
public void onCreate() {
super.onCreate();
createNotificationChannels();
}
private void createNotificationChannels() {
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.O) {
NotificationChannel channel1 = new NotificationChannel(
CHANNEL_1_ID,
"Channel 1",
NotificationManager.IMPORTANCE_HIGH
);
channel1.setDescription("This is Channel 1");
NotificationChannel channel2 = new NotificationChannel(
CHANNEL_2_ID,
"Channel 2",
NotificationManager.IMPORTANCE_LOW
);
channel2.setDescription("This is Channel 2");
NotificationManager manager = getSystemService(NotificationManager.class);
manager.createNotificationChannel(channel1);
manager.createNotificationChannel(channel2);
}
}
Notification Reciever
public class NotificationReceiver extends BroadcastReceiver {
#Override
public void onReceive(Context context, Intent intent) {
String title = "You Did it!";
String message = "Some Text";
Notification notification = new NotificationCompat.Builder(context, CHANNEL_1_ID)
.setSmallIcon(R.drawable.ic_launcher_foreground)
.setContentTitle(title)
.setContentText(message)
.setPriority(NotificationCompat.PRIORITY_HIGH)
.setCategory(NotificationCompat.CATEGORY_MESSAGE)
.build();
NotificationManager notificationManager = (NotificationManager) context.getSystemService(Context.NOTIFICATION_SERVICE);
notificationManager.notify(0, notification);
AlarmManager alarmManager = (AlarmManager) context.getSystemService(ALARM_SERVICE);
Calendar calendar = Calendar.getInstance();
calendar.add(Calendar.MINUTE, 1);
Intent i = new Intent("android.action.DISPLAY_NOTIFICATION");
i.addFlags(Intent.FLAG_INCLUDE_STOPPED_PACKAGES);
PendingIntent broadcast = PendingIntent.getBroadcast(context, 100, intent, PendingIntent.FLAG_CANCEL_CURRENT);
alarmManager.setExact(AlarmManager.RTC_WAKEUP, calendar.getTimeInMillis(), broadcast);
}
you can set new notification when previous one triggers.in onReceive Method of BroadcastReceiver.

Android 8.1 notifications showing but not making any sounds

I have a service which runs in foreground with, among other things, a stopwatch. When the service starts the notification appears, and when it ends I update it with sound and some text that indicates that it's finished. The problem is that this works well until api 25, but for 26 and 27 it updates the notification alright, but makes no sound. Here's the relevant code:
The creation of the notification inside the service:
mBuilder = new NotificationCompat.Builder(context, "Main")
.setSmallIcon(R.drawable.ic_notification_temp)
.setContentTitle(step.getDescription())
.setContentText(getString(R.string.notification_text))
.setVisibility(VISIBILITY_PUBLIC)
.setOngoing(true);
.setDeleteIntent(deletePendingIntent);
.setContentIntent(contentPendingIntent);
.addAction(R.drawable.ic_stop_red_24dp, getString(R.string.cancel),finnishPendingIntent);
mNotificationManager = (NotificationManager)context.getSystemService(Context.NOTIFICATION_SERVICE);
mNotificationManager.notify(mId, mBuilder.build());
The update to the notification builder when the "work" is finished:
mBuilder.setSound(RingtoneManager.getDefaultUri(RingtoneManager.TYPE_NOTIFICATION));
mBuilder.setVibrate(new long[]{0, 300, 0, 400, 0, 500});
mBuilder.setOngoing(false);
mBuilder.setAutoCancel(true);
mBuilder.setContentText(getString(R.string.notification_finished_text));
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.O) {
mBuilder.setChannelId("Sound");
mBuilder.setCategory(NotificationCompat.CATEGORY_ALARM);
}
mNotificationManager.notify(mId, mBuilder.build());
The 2 channels created just for api 26 or up on app start:
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.O) {
// Create the normal NotificationChannel
CharSequence name = getString(R.string.app_name);
int importance = NotificationManager.IMPORTANCE_LOW;
NotificationChannel channel = new NotificationChannel("Main", name, importance);
// Register the channel with the system; you can't change the importance
// or other notification behaviors after this
NotificationManager notificationManager = (NotificationManager) getSystemService(
NOTIFICATION_SERVICE);
notificationManager.createNotificationChannel(channel);
// Create theNotificationChannel with sound
importance = NotificationManager.IMPORTANCE_HIGH;
name = getString(R.string.notification_channel_sound);
NotificationChannel sound = new NotificationChannel("Sound", name, importance);
sound.enableVibration(true);
sound.setVibrationPattern(new long[]{0, 300, 0, 400, 0, 500});
AudioAttributes aa = new AudioAttributes.Builder()
.setContentType(AudioAttributes.CONTENT_TYPE_SONIFICATION)
.setLegacyStreamType(AudioManager.STREAM_NOTIFICATION)
.setUsage(AudioAttributes.USAGE_NOTIFICATION_EVENT)
.build();
sound.setSound(RingtoneManager.getDefaultUri(RingtoneManager.TYPE_NOTIFICATION), aa);
notificationManager.createNotificationChannel(sound);
}
And that's where I'm at now. I've tried to not use setsound() as I've read that the notification should just play the default sound with the appropriate importance (and of course I've even uninstalled the app between tries to correctly update the channel settings) but nothing seems to work for api 26 and I just don't know what I'm doing wrong.
I had the exact same problems with most of my emulator AVDs. The following fixed it for me:
start the affected AVD
long press the AVD's power button
restart the AVD
Afterwards it should work again.
Tried to reproduce your issue and finished with created MVP, maybe this will help you to find the problem:
Activity:
public class MainActivity extends AppCompatActivity {
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
View btn = findViewById(R.id.clickMe);
btn.setTag(NotifService.CHANNEL_ID_MAIN);
btn.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
String channelId = (String) v.getTag();
Intent intent = new Intent(v.getContext(), NotifService.class);
intent.putExtra(NotifService.TAG, channelId);
if (channelId.equals(NotifService.CHANNEL_ID_MAIN)) {
v.setTag(NotifService.CHANNEL_ID_SOUND);
} else {
v.setTag(NotifService.CHANNEL_ID_MAIN);
}
v.getContext().startService(intent);
}
});
}
}
Service:
public class NotifService extends IntentService {
public static final String TAG = "NotificationService";
public static final String CHANNEL_ID_MAIN = "Main";
public static final String CHANNEL_ID_SOUND = "Sound";
public static final int NOTIFICATION_ID = 123;
/**
* Creates an IntentService. Invoked by your subclass's constructor.
*/
public NotifService() {
super(TAG);//Used to name the worker thread, important only for debugging.
}
#Override
public void onCreate() {
super.onCreate();
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.O) {
NotificationChannel channel = new NotificationChannel(CHANNEL_ID_MAIN, "Channel Main", NotificationManager.IMPORTANCE_LOW);
NotificationChannel sound = new NotificationChannel(CHANNEL_ID_SOUND, "Channel Sound", NotificationManager.IMPORTANCE_HIGH);
sound.enableVibration(true);
sound.setVibrationPattern(new long[]{0, 300, 0, 400, 0, 500});
AudioAttributes aa = new AudioAttributes.Builder()
.setContentType(AudioAttributes.CONTENT_TYPE_SONIFICATION)
.setLegacyStreamType(AudioManager.STREAM_NOTIFICATION)
.setUsage(AudioAttributes.USAGE_NOTIFICATION_EVENT)
.build();
sound.setSound(RingtoneManager.getDefaultUri(RingtoneManager.TYPE_NOTIFICATION), aa);
NotificationManager notificationManager = (NotificationManager) getSystemService(NOTIFICATION_SERVICE);
if (notificationManager != null) {
notificationManager.createNotificationChannel(channel);
notificationManager.createNotificationChannel(sound);
}
}
}
#Override
protected void onHandleIntent(#Nullable Intent intent) {
String channelId = intent.getStringExtra(TAG);
showNotification(channelId);
}
private void showNotification(String channelId) {
boolean inProgress = channelId.equals(CHANNEL_ID_MAIN);
NotificationCompat.Builder builder = new NotificationCompat.Builder(this, channelId)
.setSmallIcon(R.drawable.ic_launcher_foreground)
.setContentTitle("Work")
.setContentText(inProgress ? "InProgress" : "Finished")
.setOngoing(inProgress)
.setVisibility(VISIBILITY_PUBLIC)
.setAutoCancel(!inProgress);
if (!inProgress) {
builder.setCategory(NotificationCompat.CATEGORY_ALARM);
}
NotificationManager notificationManager = (NotificationManager) getSystemService(Context.NOTIFICATION_SERVICE);
if (notificationManager != null) {
notificationManager.notify(NOTIFICATION_ID, builder.build());
}
}
}
This works good on my device 8.1 and Emulator 8.1 (without sound on first click for first notification and with vibration + sound on second click for work complete notification).

Categories

Resources