i want to ask about FCM. I have an FCM service that is running as it should this is my code
Intent intent = new Intent(this, MainActivity.class);
intent.addFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP);
PendingIntent pendingIntent = PendingIntent.getActivity(this, 0, intent, PendingIntent.FLAG_UPDATE_CURRENT);
NotificationCompat.Builder notificationBuilder = new NotificationCompat.Builder(this, "ch1")
.setSmallIcon(R.mipmap.ic_launcher)
.setContentTitle(getString(R.string.app_name))
.setContentText(remoteMessage.getNotification().getBody())
.setAutoCancel(true)
.setContentIntent(pendingIntent);
NotificationManager mNotificationManager = (NotificationManager) getSystemService(Context.NOTIFICATION_SERVICE);
if (android.os.Build.VERSION.SDK_INT >= android.os.Build.VERSION_CODES.O) {
notificationBuilder.setDefaults(Notification.DEFAULT_VIBRATE);
NotificationChannel channel = new NotificationChannel("ch1",
getString(R.string.app_name), NotificationManager.IMPORTANCE_HIGH);
channel.enableLights(true);
channel.enableVibration(true);
mNotificationManager.createNotificationChannel(channel);
}
mNotificationManager.notify(0, notificationBuilder.build());
but i want to disable this notification on spesific activity, for example i have ChatActivity. where if i get notificatin on this activity, the fcm service is not showing a notification. I have tried implement this code but still not work
if(!(this.getApplicationContext() instanceof ChatActivity)){
//build the notification
}
anyone have solution for my problem? thank you.
First of all keep a flag in your SharedPreferences for ChatActivity to know if it's open or not.
Now inside ChatActivity set this flag true in onResume() and false in onStop(). Like this:
#Override
protected void onResume() {
super.onResume();
AppPreferences.getInstance().setBoolean("IS_CHAT_ACTIVITY", true);
}
#Override
protected void onStop() {
super.onStop();
AppPreferences.getInstance().setBoolean("IS_CHAT_ACTIVITY", true);
}
If you don't know anything about SharedPreferences check This Tutorial.
Now in your FCM Service class, you have onMessageReceived() callback, which is triggered every time a notification comes.
Now Do this in your onMessageReceived() callback:
#Override
public void onMessageReceived(RemoteMessage remoteMessage) {
if(remoteMessage.getNotification() != null) {
if (AppPreferences.getInstance().getBoolean("IS_CHAT_ACTIVITY", false)) {
//Do Nothing, Ignore Notification
} else {
//Write code to show notification here
//Show Notification
generateNotification(remoteMessage.getNotification());
}
}
}
That's it, that's how you can prevent the notification while you’re on ChatActivity.
Related
How can I open an activity on the lock screen without the user having to click on it? Like for example an alarm or a call.
In my code I can get the FCM notification and if the user clicks on the notification it is possible to open an activity, but I wanted the user not to have to click on it.
FirebaseService.java
//--- Notificacao
public void createNotificationChannel(){
mNotifyManager = (NotificationManager) getSystemService(NOTIFICATION_SERVICE);
if(Build.VERSION.SDK_INT >= Build.VERSION_CODES.O){
//create a notification channel
NotificationChannel notificationChannel = new NotificationChannel(PRIMARY_CHANNEL_ID,
"Mascot Notification", NotificationManager
.IMPORTANCE_HIGH);
notificationChannel.enableLights(true);
notificationChannel.setLightColor(Color.RED);
notificationChannel.enableVibration(true);
notificationChannel.setDescription("Notification from Mascot");
mNotifyManager.createNotificationChannel(notificationChannel);
}
}
public void sendNotification(String taskName){
NotificationCompat.Builder notifyBuilder = getNotificationBuilder(taskName);
//agora temos que entregar a notificacao
mNotifyManager.notify(NOTIFICATION_ID, notifyBuilder.build());
}
public NotificationCompat.Builder getNotificationBuilder(String taskName){
Intent intent = new Intent(this, TesteActivity.class);
PendingIntent p = getPendingIntent(NOTIFICATION_ID, intent, getApplicationContext());
return new NotificationCompat.Builder(this, PRIMARY_CHANNEL_ID)
.setSmallIcon(R.drawable.notification_icon)
.setContentText("titulo teste")
.setContentIntent(p)
.setCategory(NotificationCompat.CATEGORY_ALARM)
.setPriority(NotificationCompat.PRIORITY_HIGH)
.setVisibility(NotificationCompat.VISIBILITY_PUBLIC);
}
private PendingIntent getPendingIntent(int id, Intent intent, Context context){
TaskStackBuilder stackBuilder = TaskStackBuilder.create(context);
stackBuilder.addParentStack(intent.getComponent());
stackBuilder.addNextIntent(intent);
PendingIntent p = stackBuilder.getPendingIntent(id, PendingIntent.FLAG_UPDATE_CURRENT);
return p;
}
TesteActivity.java
public class TesteActivity extends AppCompatActivity {
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_teste);
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.O_MR1) {
setTurnScreenOn(true);
setShowWhenLocked(true);
KeyguardManager keyguardManager = (KeyguardManager) getSystemService(Context.KEYGUARD_SERVICE);
keyguardManager.requestDismissKeyguard(this, null);
}
instead of mNotifyManager.notify( call, which shows your Notification, just use startActivity(..? you may need also WakeLock and showOnLockScreen attribute set for this Activity in manifest
edit: and HERE you can find article with exactly your case tutorial
How can I create simple notification, which will close the application (in multitasking) after click? Thanks. (Java, Android)
first we should create notification that call an activity :
Intent intent = new Intent(this, YourClass.class);
intent.putExtra("NotiClick",true);
PendingIntent pIntent = PendingIntent.getActivity(this, 0, intent, PendingIntent.FLAG_UPDATE_CURRENT);
if (android.os.Build.VERSION.SDK_INT >= android.os.Build.VERSION_CODES.JELLY_BEAN) {
Notification Noti;
Noti = new Notification.Builder(this)
.setContentTitle("YourTitle")
.setContentText("YourDescription")
.setSmallIcon(R.mipmap.ic_launcher)
.setContentIntent(pIntent)
.setAutoCancel(true).build();
NotificationManager notificationManager =
(NotificationManager) getSystemService(NOTIFICATION_SERVICE);
notificationManager.notify(0, Noti);
}
Then in the onCreate() of your class do this:
Bundle extras = getIntent().getExtras();
if(extras == null)
{
//not being clicked on
}
else if (extras.getBoolean("NotiClick"))
{
//being clicked
}
and for completely close application you can kill process :
android.os.Process.killProcess(android.os.Process.myPid());
I have implemented push notifications using Azure's Notification Hub. I have noticed that they only have three override methods when extending NotificationHandler:
public void onReceive(Context context, Bundle bundle)
public void onUnregistered(Context context, String gcmRegistrationId)
public void onRegistered(Context context, String gcmRegistrationId)
Most push notification services have an onPushOpen() or onOpen() callback method which is called when a user presses on the push notification they received. How do I know when someone has clicked on the received push notification? I am experimenting with the demo. Everything works minus the concern I have said.
Link: https://github.com/Azure/azure-notificationhubs-samples/blob/master/Android/GetStartedFirebase/app/src/main/java/com/example/microsoft/getstartednh/MyHandler.java
public class MyHandler extends NotificationsHandler {
public static final int NOTIFICATION_ID = 1;
private NotificationManager mNotificationManager;
NotificationCompat.Builder builder;
Context ctx;
#Override
public void onReceive(Context context, Bundle bundle) {
ctx = context;
String nhMessage = bundle.getString("message");
sendNotification(nhMessage);
if (MainActivity.isVisible) {
MainActivity.mainActivity.ToastNotify(nhMessage);
}
}
private void sendNotification(String msg) {
Intent intent = new Intent(ctx, MainActivity.class);
intent.addFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP);
mNotificationManager = (NotificationManager)
ctx.getSystemService(Context.NOTIFICATION_SERVICE);
PendingIntent contentIntent = PendingIntent.getActivity(ctx, 0,
intent, PendingIntent.FLAG_ONE_SHOT);
Uri defaultSoundUri = RingtoneManager.getDefaultUri(RingtoneManager.TYPE_NOTIFICATION);
NotificationCompat.Builder mBuilder =
new NotificationCompat.Builder(ctx)
.setSmallIcon(R.mipmap.ic_launcher)
.setContentTitle("Notification Hub Demo")
.setStyle(new NotificationCompat.BigTextStyle()
.bigText(msg))
.setSound(defaultSoundUri)
.setContentText(msg);
mBuilder.setContentIntent(contentIntent);
mNotificationManager.notify(NOTIFICATION_ID, mBuilder.build());
}
}
For anyone else trying to figure this out, it is actually pretty simple. In the sendNotification() method, whatever information you want to keep track of when the push notification is opened add it as extras to your intent. For example.
private void sendNotification(String msg) {
Intent intent = new Intent(ctx, MainActivity.class);
intent.addFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP);
// seeking to do something specific when notification is opened if flag is set
intent.putExtra("onPushOpen", "performSomeAction");
mNotificationManager = (NotificationManager)
ctx.getSystemService(Context.NOTIFICATION_SERVICE);
PendingIntent contentIntent = PendingIntent.getActivity(ctx, 0,
intent, PendingIntent.FLAG_ONE_SHOT);
Uri defaultSoundUri = RingtoneManager.getDefaultUri(RingtoneManager.TYPE_NOTIFICATION);
NotificationCompat.Builder mBuilder =
new NotificationCompat.Builder(ctx)
.setSmallIcon(R.mipmap.ic_launcher)
.setContentTitle("Notification Hub Demo")
.setStyle(new NotificationCompat.BigTextStyle()
.bigText(msg))
.setSound(defaultSoundUri)
.setContentText(msg);
mBuilder.setContentIntent(contentIntent);
mNotificationManager.notify(NOTIFICATION_ID, mBuilder.build());
}
Now that you have done this. In onResume() check for that information. It will be empty (null) when push notification is not invoked, otherwise, it will have your information.
Bundle b = getIntent().getExtras();
// now retrieve what you want from the bundle.
I want a method to be executed when I press a button on my notification. For that purpose I am adding an action with a PendingIntent to my notification:
Intent intent = new Intent(context, AlertActivity.class);
PendingIntent pendingIntent = PendingIntent.getActivity(context, 0, intent, 0);
Notification notification = new Notification.Builder(MainActivity.this)
.setContentTitle("New Notification")
.setContentText("Click Here")
.setSmallIcon(R.mipmap.ic_launcher)
.setContentIntent(pendingIntent)
.addAction(R.mipmap.ic_launcher, "Test2", pendingIntent)
.build();
notification.flags |= Notification.FLAG_AUTO_CANCEL;
NotificationManager manager = (NotificationManager) getSystemService(NOTIFICATION_SERVICE);
manager.notify(0, notification);
That works, however I don't want to start an Activity when the user invokes the action. I just need to do some work.
For that purpose I implemented a Service which should be targeted by the PendingIntent instead:
public class MyServices extends IntentService {
public MyServices() {
super("MyServices");
}
#Override
protected void onHandleIntent(Intent intent) {
clearNotification();
}
public void clearNotification() {
NotificationManager notificationManager = (NotificationManager) getSystemService(NOTIFICATION_SERVICE);
notificationManager.cancel(0);
Intent intent = new Intent(MyServices.this, MainActivity.class);
//Starting new activity just to check
startActivity(intent);
}
}
I create the PendingIntent like this:
final Intent intent = new Intent(context, MyServices.class);
final PendingIntent pendingIntent = PendingIntent.getService(context, 0, intent, 0);
However when I invoke the action on my notification nothing happens. What am I doing wrong?
A Notification is not part of your application. It is managed by the OS. It just so happens that there are APIs you can use to show/cancel/etc notifications.
A pending intent allows for external code (Notifications for example) to launch your app/activity/service/broadcastreceiver. This cannot be done without a pending intent.
What my task is to execute some piece of code when a specific action button is clicked, and clear notification; without starting any activity
You don't have to start an activity. You can do it in a broadcastreceiver that has no UI. Or, as CommonsWare suggested, use an IntentService, depending on what what you are doing in your "piece of code". IntentServices handle work in a separate thread.
I have the following code in an android app. What it currently does is, at the specified time passed with the Calendar when variable, it opens up the RunningActivity (which is blank), vibrates, and sends a notification. Even if I've pressed the home button and it's running in the background, it starts a new blank RunningActivity and vibrates and sends a notification. I'm trying to figure out how to do all the stuff in the RunningActivity (Vibrate and send a notification) without opening up the blank RunningActivity, allowing the application to stay in the background.
I do NOT need help with actually calling the notification or vibration. I just need to know how to run the actions in the RunningActivity onCreate at a specific time witout opening/showing the RunningActivity. As seen below, I setup a PendingIntent with an AlarmManagager, the issue is that it is launching an Activity and showing it when all I want it to do is vibrate/send a notification.
public void startAlarm(Activity activity, Calendar when){
currentTimerHour = when.get(Calendar.HOUR);
currentTimerMin = when.get(Calendar.MINUTE);
Intent intent = new Intent(activity, RunningActivity.class);
PendingIntent pendingIntent = PendingIntent.getActivity(activity, 12345, intent, PendingIntent.FLAG_CANCEL_CURRENT);
AlarmManager am = (AlarmManager)activity.getSystemService(Activity.ALARM_SERVICE);
am.set(AlarmManager.RTC_WAKEUP, when.getTimeInMillis(), pendingIntent);
}
RunningActivity Class:
public class RunningActivity extends Activity {
#Override
public void onCreate(Bundle bundle){
super.onCreate(bundle);
Vibrator v = (Vibrator) getSystemService(Context.VIBRATOR_SERVICE);
v.vibrate(500);
NotificationCompat.Builder mBuilder;
mBuilder = new NotificationCompat.Builder(this)
.setSmallIcon(R.drawable.ic_launcher)
.setContentTitle("My notification")
.setContentText("Hello World!");
Intent resultIntent = new Intent(this, MainActivity.class);
TaskStackBuilder stackBuilder = TaskStackBuilder.create(this);
stackBuilder.addParentStack(MainActivity.class);
stackBuilder.addNextIntent(resultIntent);
PendingIntent resultPendingIntent =
stackBuilder.getPendingIntent(
0,
PendingIntent.FLAG_UPDATE_CURRENT
);
mBuilder.setContentIntent(resultPendingIntent);
NotificationManager mNotificationManager =
(NotificationManager) getSystemService(Context.NOTIFICATION_SERVICE);
mNotificationManager.notify(0, mBuilder.build());
}
}
To send Notification From Background:
public void createNotification(Context context) {
// Prepare intent which is triggered if the
// notification is selected
Intent intent = new Intent(context,Myexample.class);
PendingIntent pIntent = PendingIntent.getActivity(context, 0, intent, 0);
Notification noti = new Notification.Builder(context)
.setContentTitle("My Title")
.setContentText("My message.")
.setSmallIcon(R.drawable.app_icon)
.setContentIntent(pIntent).build();
#SuppressWarnings("static-access")
NotificationManager notificationManager =
(NotificationManager)context.getSystemService(context.NOTIFICATION_SERVICE);
// Hide the notification after its selected
noti.flags |= Notification.FLAG_AUTO_CANCEL;
noti.flags |= Notification.FLAG_SHOW_LIGHTS;
notificationManager.notify(0, noti);
}
You can use service. Add your vibrator class on Service and call it when you need need it. You can also create a method on your class and call it when you need it.
Vibrator v = (Vibrator) getSystemService(Context.VIBRATOR_SERVICE);
v.vibrate(500);