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
Related
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.
I'm creating a ClockApp for Android. I have AlarmBroadcastReceiver which gives me a notification with the button close alarm and when an user clicks by that button the notification will be disappeared. However, it doesn't work when my app was closed. For example, I set alarm at 7:00 am and I closed my app then I waked up and I found on my phone a notification close alarm I clicked by that button but I just was redirected to a main activity then I clicked again and only then the notification will be disappeared. Why do I have to click two times? However, if my app isn't closed I have to click only one time and the notification will be disappeared. I hope you'll help me with my problem)
Code: (I have MainActivity with tabs)
MainActivity:
#Override
protected void onNewIntent(Intent intent) {
super.onNewIntent(intent);
// cancel notifications
NotificationManager notificationManager =
(NotificationManager) getSystemService(Context.NOTIFICATION_SERVICE);
if (intent.getBooleanExtra("alarm_cancel_notification", false)) {
if (notificationManager != null) {
notificationManager.cancel(1);
}
}
}
AlarmFragment:
private void startAlarm() {
Intent intent = new Intent(getContext(), AlarmManagerBroadcastReceiver.class);
PendingIntent pendingIntent = PendingIntent.getBroadcast(
getContext(),
1,
intent,
PendingIntent.FLAG_UPDATE_CURRENT);
if (Build.VERSION.SDK_INT >= 23) {
AlarmManager.AlarmClockInfo alarmClockInfo =
new AlarmManager.AlarmClockInfo(mCalendar.getTimeInMillis(), pendingIntent);
mAlarmManager.setAlarmClock(alarmClockInfo, pendingIntent);
} else if (Build.VERSION.SDK_INT >= 19) {
mAlarmManager.setExact(AlarmManager.RTC_WAKEUP, mCalendar.getTimeInMillis(), pendingIntent);
} else {
mAlarmManager.set(AlarmManager.RTC_WAKEUP, mCalendar.getTimeInMillis(), pendingIntent);
}
}
BroadcastReceiver:
public class AlarmManagerBroadcastReceiver extends BroadcastReceiver {
private static final int ALARM_EXPIRED_NOTIFICATION_ID = 1;
#Override
public void onReceive(Context context, Intent intent) {
NotificationManager notificationManager =
(NotificationManager) context.getSystemService(Context.NOTIFICATION_SERVICE);
Intent notificationIntent = new Intent(context, MainActivity.class);
notificationIntent.putExtra("alarm_cancel_notification", true);
PendingIntent notificationPendingIntent = PendingIntent.getActivity(
context,
1,
notificationIntent,
PendingIntent.FLAG_UPDATE_CURRENT);
RemoteViews remoteViews = new RemoteViews(
context.getPackageName(),
R.layout.partial_notification);
remoteViews.setTextViewText(
R.id.cancel_button_notification,
context.getString(R.string.alarm_notification));
remoteViews.setOnClickPendingIntent(
R.id.cancel_button_notification,
notificationPendingIntent);
NotificationCompat.Builder builder = new NotificationCompat.Builder(
context,
ChannelIdApp.CHANNEL_ID);
builder.setAutoCancel(true)
.setTicker("Alarm")
.setCustomContentView(remoteViews)
.setSound(RingtoneManager.getDefaultUri(RingtoneManager.TYPE_ALARM))
.setSmallIcon(R.drawable.ic_stat_notify_clock);
Notification notification = builder.build();
notification.flags = notification.flags | Notification.FLAG_INSISTENT;
if (notificationManager != null) {
notificationManager.notify(ALARM_EXPIRED_NOTIFICATION_ID, notification);
}
}
}
Channel Id:
public class ChannelIdApp extends Application {
public static final String CHANNEL_ID = "clock_channel_id";
#Override
public void onCreate() {
super.onCreate();
if (android.os.Build.VERSION.SDK_INT >= android.os.Build.VERSION_CODES.O) {
NotificationManager notificationManager =
(NotificationManager) getSystemService(Context.NOTIFICATION_SERVICE);
NotificationChannel notificationChannel = new NotificationChannel(
CHANNEL_ID,
"Clock notifications",
NotificationManager.IMPORTANCE_HIGH);
notificationChannel.enableVibration(true);
notificationChannel.enableLights(true);
if (notificationManager != null) {
notificationManager.createNotificationChannel(notificationChannel);
}
}
}
}
Manifest:
<activity
android:launchMode="singleTop"
android:name=".activities.MainActivity"
android:screenOrientation="portrait" />
<receiver
android:exported="false"
android:name=".AlarmManagerBroadcastReceiver" />
try adding .setAutoCancel(true); in your AlarmManagerBroadcastReceiver class after this line
NotificationCompat.Builder builder = new NotificationCompat.Builder(
context,
ChannelIdApp.CHANNEL_ID);
builder.setAutoCancel(true)
.setTicker("Alarm")
.setCustomContentView(remoteViews)
.setSound(RingtoneManager.getDefaultUri(RingtoneManager.TYPE_ALARM))
.setSmallIcon(R.drawable.ic_stat_notify_clock)
// <<here>> ;
I want to set notification number on the app icon by button click. I have tried to understand and follow several methods but none of them worked.
I can send notification using simply using channel but I also want to set notification numbers on app icon.
Here below my code:
public class MainActivity extends AppCompatActivity {
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
Button Gn = (Button) findViewById(R.id.gn);
Gn.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
shownotifications();
}
});
}
private void shownotifications() {
//channel
String id = "main_channel";
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.O) {
NotificationManager notificationManager = (NotificationManager) getSystemService(Context.NOTIFICATION_SERVICE);
CharSequence name = "Channel Name";
String description = "Channel Description";
int importance = NotificationManager.IMPORTANCE_HIGH;
NotificationChannel notificationChannel = new NotificationChannel(id, name, importance);
notificationChannel.setDescription(description);
notificationChannel.enableLights(true);
notificationChannel.setLightColor(Color.WHITE);
notificationChannel.enableVibration(false);
if (notificationManager != null) {
notificationManager.createNotificationChannel(notificationChannel);
}
}
//notifications
NotificationCompat.Builder notificationBuilder = new NotificationCompat.Builder(this, id)
.setSmallIcon(R.mipmap.ic_launcher)
.setLargeIcon(BitmapFactory.decodeResource(getResources(), R.drawable.icon))
.setContentTitle("Notification Title")
.setContentText("This is the description of this notification......")
.setLights(Color.WHITE, 500, 5000)
.setColor(Color.RED)
.setDefaults(Notification.DEFAULT_SOUND);
Intent nI = new Intent(this, MainActivity.class);
PendingIntent contentIntent = PendingIntent.getActivity(this, 0, nI, PendingIntent.FLAG_UPDATE_CURRENT);
notificationBuilder.setContentIntent(contentIntent);
NotificationManagerCompat notificationManagerCompat = NotificationManagerCompat.from(this);
notificationManagerCompat.notify(1000, notificationBuilder.build());
}
}
You can only do it by changing your app's icon everytime you want to update the notification number.
Try this.
use this link https://github.com/leolin310148/ShortcutBadger
set count on button click whenever you want to update count user previous count incremented
In my application i want open custom activity (not MainActivity) and putExtra to this activity when click on Firebase notification.
I write below codes, but when click on notification open MainActivity, But i want open my another activity (AuctionDetailActivity).
My NotificationManager class :
public class MyNotificationManager {
private Context mCtx;
private Uri soundUri;
private static MyNotificationManager mInstance;
public MyNotificationManager(Context context) {
mCtx = context;
}
public static synchronized MyNotificationManager getInstance(Context context) {
if (mInstance == null) {
mInstance = new MyNotificationManager(context);
}
return mInstance;
}
public void displayNotification(String title, String body) {
soundUri = RingtoneManager.getDefaultUri(RingtoneManager.TYPE_NOTIFICATION);
Intent intent = new Intent(mCtx, MainActivity.class);
intent.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK | Intent.FLAG_ACTIVITY_SINGLE_TOP | Intent.FLAG_ACTIVITY_CLEAR_TOP);
intent.putExtra("fcm_notification", "Y");
PendingIntent pendingIntent = PendingIntent.getActivity(mCtx, 0, intent, PendingIntent.FLAG_UPDATE_CURRENT);
NotificationCompat.Builder mBuilder = new NotificationCompat.Builder(mCtx, Constants.NOTIF_CHANNEL_ID)
.setSmallIcon(R.mipmap.ic_launcher)
.setContentTitle(title)
.setSound(soundUri)
.setAutoCancel(true)
.setVibrate(new long[]{100, 200, 300, 400, 500, 400, 300, 200, 400})
.setContentText(body)
.setContentIntent(pendingIntent);
NotificationManager mNotifyMgr = (NotificationManager) mCtx.getSystemService(NOTIFICATION_SERVICE);
if (mNotifyMgr != null) {
mNotifyMgr.notify(1, mBuilder.build());
}
}
}
And MyFirebaseMessagingService class :
public class MyFirebaseMessagingService extends FirebaseMessagingService {
#Override
public void onMessageReceived(RemoteMessage remoteMessage) {
showNotify(remoteMessage.getFrom(), remoteMessage.getNotification().getBody());
}
private void showNotify(String title, String body) {
MyNotificationManager myNotificationManager = new MyNotificationManager(getApplicationContext());
//myNotificationManager.displayNotification(title, body);
myNotificationManager.displayNotification(title, body);
}
}
MainActivity codes:
#Override
protected void onResume() {
super.onResume();
String fcm_notification = getIntent().getStringExtra("fcm_notification");
Log.d("FireBaseIntentLog", " FCM : " + fcm_notification);
if (getIntent().getExtras() != null) {
for (String key : getIntent().getExtras().keySet()) {
String value = getIntent().getExtras().getString(key);
Log.d("FireBaseIntentLog", "Key: " + key + " Value: " + value + " FCM : " + fcm_notification);
}
}
}
How can i fix it?
If you are sending the notification from Firebase console or inside the notification field using FCM API, the app behaves in two ways -
If your app is in foreground, the method onMessageReceived of your FCM service class will be called.
If your app is in background, nothing will happen inside your FCM service class. Rather, the notification will be handled internally by the FCM library itself and the notification with launcher activity in the intent will be shown.
And if you use FCM API to send notification and use the data field, the library does nothing itself and instead calls the method onMessageReceived regardless of whether your app is in foreground or background.
So in order to solve your issue, you can use one of the following two solutions:
Use FCM API to send notifications and use the data field instead of the notification field. Check the documentation to read more about FCM API.
In your launcher (main) activity, check for intent inside onCreate and if it is coming from notification, read the extras, finish the main activity and open your required activity.
Example for second case:
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
if (checkIntent()) return;
// other code.
}
#Override
protected void onNewIntent(Intent intent) {
super.onNewIntent(intent);
checkIntent();
}
private boolean checkIntent() {
// to receive the value, send the value as custom data from Firebase console.
String value = getIntent().getStringExtra("your_key");
if (value == null) return false;
if (value.equals("something")) {
// open one activity.
} else if (value.equals("another_thing")) {
// open another activity.
}
finish();
return true;
}
Change this below line
Intent intent = new Intent(click_action);
to this
Intent intent = new Intent(getActivity(), YourClass.class);
You just need modify in sendNotification function
public void sendNotification(String messageBody, String messageTitle, int user_id, String click_action) {
Intent intent = new Intent(mCtx, AuctionDetailActivity.class); // Need modify this line
intent.putExtra(Extras.bidID.name(), user_id);
PendingIntent pendingIntent = PendingIntent.getActivity(mCtx, 0, intent,
PendingIntent.FLAG_ONE_SHOT);
Uri defaultSoundUri = RingtoneManager.getDefaultUri(RingtoneManager.TYPE_NOTIFICATION);
NotificationCompat.Builder notificationBuilder = new NotificationCompat.Builder(mCtx, Constants.NOTIF_CHANNEL_ID);
notificationBuilder.setSmallIcon(R.mipmap.ic_launcher)
.setContentTitle(messageTitle)
.setContentText(messageBody)
.setAutoCancel(true)
.setSound(defaultSoundUri)
.setContentIntent(pendingIntent);
NotificationManager notificationManager = (NotificationManager) mCtx.getSystemService(Context.NOTIFICATION_SERVICE);
notificationManager.notify(0, notificationBuilder.build());
}
Change your MyFirebaseMessagingService class as shown below replace OtherApp.class with your activity name
public class MyFirebaseMessagingService extends FirebaseMessagingService {
#Override
public void onMessageReceived(RemoteMessage remoteMessage) {
Intent intent=new Intent(this,OtherApp.class);
intent.setFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP);
PendingIntent pendingIntent = PendingIntent.getActivity(this,0,intent,PendingIntent.FLAG_ONE_SHOT);//newbg PendingIntent.getActivity(this,0,intent,PendingIntent.FLAG_ONE_SHOT);
NotificationCompat.Builder notificationBuilder= new NotificationCompat.Builder(this);
notificationBuilder.setContentTitle("FCM NOTIFICATION"); notificationBuilder.setContentText(remoteMessage.getNotification().getBody());
notificationBuilder.setAutoCancel(true);
notificationBuilder.setSmallIcon(R.mipmap.ic_launcher);
notificationBuilder.setContentIntent(pendingIntent);
NotificationManager notificationManager =(NotificationManager) getSystemService(Context.NOTIFICATION_SERVICE);
notificationManager.notify(0,notificationBuilder.build());
}
}
I want to cancel/delete the notification after I click the addAction.
However it's not working. The notification is still there after the click.
I'm pretty sure this worked in an other project.
Can anyone see a stupid error I made, why its not working?
Actual code:
public class AlarmReceiver extends BroadcastReceiver {
#Override
public void onReceive(Context context, Intent arg1) {
showNotification(context);
}
private void showNotification(Context context){
String onderwerp = ("Medicatietijd");
String name = ("Het is tijd om je medicitie in te nemen.");
// Geluid notificatie
Uri soundUri = RingtoneManager.getDefaultUri(RingtoneManager.TYPE_NOTIFICATION);
// Notificatie trigger
PendingIntent contentIntent = PendingIntent.getActivity(context, 0,
new Intent(context, Test.class), 0);
// De notificatie
Notification mNotification = new Notification.Builder(context)
.setContentTitle(onderwerp)
.setContentText(name)
.setSmallIcon(R.drawable.ninja)
.setSound(soundUri)
.addAction(R.drawable.ja, "Ja, ik heb ze ingenomen.", contentIntent)
.setAutoCancel(true)
.build();
NotificationManager notificationManager
= (NotificationManager) context.getSystemService(Context.NOTIFICATION_SERVICE);
mNotification.vibrate = new long[]{100, 200, 100, 500};
mNotification.flags |= Notification.FLAG_AUTO_CANCEL;
notificationManager.notify(0, mNotification);
}
Solution:
In test activity OnCreate added this:
NotificationManager notificationManager
= (NotificationManager) getSystemService(Context.NOTIFICATION_SERVICE);
notificationManager.cancel(0);
If you decided to use Test activity to receive the intent of your addAction call, then you must cancel notification when you receive the intent in the activity.
I also recommend that you add requestCode for the intent.
Here is the code :
to set the requestCode modify this :
static final int REQ_CODE = 101; // some number
// Notificatie trigger
PendingIntent contentIntent = PendingIntent.getActivity(context, REQ_CODE,
new Intent(context, Test.class), 0);
to Handle intent in activity and dismiss the notification, in Test activity class :
#Override
protected void onActivityResult (int requestCode, int resultCode, Intent data) {
if (requestCode == REQ_CODE) {
// dismiss notification
notificationManager.cancel(0);
// handle your action
// ...
}
}
Hope that helps