How to send a request when push notification is cancelled in Android - android

When an application receives push notification from FCM, it calls onMessageReceived. (See 1, 2 or 3.)
When a user taps the notification, it launches the applications, then it sends a request to a server that the user has read the notification.
I want to know when a device received a push notification, but the user swiped it (or cleared all notifications). I want to send a request to the server that the user simply cancelled the notification.
I tried to send BroadcastReceiver and show logs (see 4 or 5), but it works when the application was opened when the notification delivered. I suppose, that
MyFirebaseMessagingService:
override fun onMessageReceived(remoteMessage: RemoteMessage) {
...
// An event when a user swipes a notification.
val intent = Intent(this, NotificationBroadcastReceiver::class.java)
intent.action = "notification_cancelled"
val deleteIntent = PendingIntent.getBroadcast(this, 0, intent, PendingIntent.FLAG_CANCEL_CURRENT)
notificationBuilder.setDeleteIntent(deleteIntent)
// Navigation to an activity when a user taps the notification.
// It doesn't matter to this question.
val intent2 = Intent(this, MainActivity::class.java)
val navigateIntent = PendingIntent.getActivity(this, notificationId, intent2,
PendingIntent.FLAG_UPDATE_CURRENT)
notificationBuilder.setContentIntent(navigateIntent)
...
}
NotificationBroadcastReceiver:
class NotificationBroadcastReceiver : BroadcastReceiver() {
override fun onReceive(context: Context, intent: Intent) {
Timber.d("NotificationBroadcastReceiver onReceive")
Toast.makeText(context, "Notification dismissed", Toast.LENGTH_LONG).show()
// Send a request to the server.
}
}
AndroidManifest:
<uses-permission android:name="com.uremont.NOTIFICATION_PERMISSION" />
<receiver
android:name=".receiver.NotificationBroadcastReceiver"
android:exported="true"
android:permission="NOTIFICATION_PERMISSION"
>
<intent-filter>
<action android:name="notification_cancelled" />
</intent-filter>
</receiver>
works only when the application is opened. But when the application is in background or killed, it doesn't react to swipe. Probably we shouldn't use BroadcastReceiver, for instance, use PendingIntent.getService or PendingIntent.getForegroundService.
Can we send a request to the server?

After a short time it worked right (though I hardly changed much). After a lot of research I made this solution. Tested on several Android emulators and devices from API 19 to API 30.
Because using BroadcastReceiver is not safe, add in AndroidManifest:
<receiver
android:name=".NotificationBroadcastReceiver"
android:exported="false"
/>
NotificationBroadcastReceiver:
class NotificationBroadcastReceiver : BroadcastReceiver() {
override fun onReceive(context: Context, intent: Intent) {
Timber.d("NotificationBroadcastReceiver onReceive")
if (intent.extras != null) {
// Receive parameters of a cancelled notification.
val authToken = intent.getStringExtra(EXTRA_TOKEN)
val code = intent.getStringExtra(EXTRA_CODE)
Timber.d("token = $authToken, code = $code")
// We can access context even if the application was removed from the recent list.
Toast.makeText(context, "Notification $code was cancelled", Toast.LENGTH_SHORT).show()
// Send data to a server.
}
}
companion object {
const val EXTRA_TOKEN = "EXTRA_TOKEN"
const val EXTRA_CODE = "EXTRA_CODE"
}
}
MyFirebaseMessagingService:
override fun onMessageReceived(remoteMessage: RemoteMessage) {
...
// Get notification code from data.
val code = remoteMessage.data["code"]
val notificationBuilder = NotificationCompat.Builder(this,
...
val notificationId = Random.nextInt()
val intent = Intent(this, NotificationBroadcastReceiver::class.java).apply {
putExtra(EXTRA_TOKEN, authToken)
putExtra(EXTRA_CODE, code)
}
val deleteIntent = PendingIntent.getBroadcast(this, notificationId, intent,
PendingIntent.FLAG_CANCEL_CURRENT)
notificationBuilder.setDeleteIntent(deleteIntent)
val notification = notificationBuilder.build()
notificationManager.notify(notificationId, notification)
}
Send a push message to Android device with it's push token, for instance:
{
"to": "ddSOGiz4QzmY.....:APA91bHgoincFw.......",
"data": {
"title": "Test",
"message": "Test",
"code": "ABCDEF"
}
}
You can see different schemes of delivering push messages here. If a user presses "Force stop" at the application, it won't receive push messages (except "AliExpress", ha-ha).
When the user dismisses push notification, NotificationBroadcastReceiver::onReceive() is called. An application gets parameters of the push message. Then we can see a toast message and send these parameters to the server.
When the user presses "Clear all" notifications, all dismiss events are fired. So, you will see a sequence of toasts. The server will receive several requests simultaneously (check that it can handle, for instance, 10 requests in 0.01 second).

Related

How to send a reply from a notification?

I'm doing an app that manages the received notifications. Currently, I'm implementing a feature that the user can reply through the reply action, but I couldn't find a way to properly set the reply message and send the message.
Here is what I have tried
fun sendReplyMessage(sbn: StatusBarNotification, replyMessage: String) {
sbn.notification.actions.firstOrNull { it.remoteInputs != null }?.let { action ->
action.remoteInputs?.get(0)?.extras
?.putCharSequence(action.remoteInputs?.get(0)?.resultKey, replyMessage)
action.actionIntent.send()
}
}
You have to get the notification action to access the pending intent, add the remote input on this intent, and then, call the method PendingIntent#send(context, requestCode, intent)
val notificationAction: android.app.Notification.Action = "Get the Action here"
val bundle = Bundle().apply{
putString(remoteInput.resultKey, "Add the text here")
}
val intent = Intent().addFlags(Intent.FLAG_RECEIVER_FOREGROUND)
RemoteInput.addResultsToIntent(notificationAction.getRemoteInputs(), intent, bundle)
notificationAction.actionIntent.send(context, 0, intent)

How to repeat an action every day in an Android app?

I want to repeat an action every day; it must continue working even if the app is not running or the device has been restarted (rebooted).
In my code I'm trying to show a TOAST message every 1 minute (as a test); it's working fine in the emulator but on a real device it doesn't work( i tried to do some changes to fixed as i see in some answers but still the same thing)
MyReceiver
class MyReceiver : BroadcastReceiver() {
private val channelId = "com.medanis.hikamwahimam"
override fun onReceive(context: Context, intent: Intent) {
Log.i("TAG","/////////////////// SHOW NOTIFICATION NOW //////////////////////")
val builder = NotificationCompat.Builder(context, channelId)
.setSmallIcon(R.drawable.ic_stat_name)
.setLargeIcon(BitmapFactory.decodeResource(context.resources,R.mipmap.ic_launcher_round))
.setContentTitle("My notification")
.setContentText("Much longer text that cannot fit one line...")
.setStyle(
NotificationCompat.BigTextStyle()
.bigText("Much longer text that cannot fit one line...Much longer text that cannot fit one line..."))
.setPriority(NotificationCompat.PRIORITY_DEFAULT)
with(NotificationManagerCompat.from(context)) {
notify(12345, builder.build()) }
Toast.makeText(context,"This toast will be shown every X minutes", Toast.LENGTH_LONG).show()
}
}
MainActivity
class MainActivity : AppCompatActivity() {
private var mAlarmManager : AlarmManager? = null
override fun onCreate(savedInstanceState: Bundle?) {
super.onCreate(savedInstanceState)
setContentView(R.layout.activity_main)
// showNotification()
val mIntent = Intent(this, MyReceiver::class.java)
val mPendingIntent = PendingIntent.getBroadcast(this, 0, mIntent, PendingIntent.FLAG_UPDATE_CURRENT)
mAlarmManager = this
.getSystemService(Context.ALARM_SERVICE) as AlarmManager
mAlarmManager!!.setRepeating(
AlarmManager.RTC_WAKEUP, System.currentTimeMillis(),
60000, mPendingIntent
)
}
}
AndroidManifest.xml
<receiver android:name=".MyReceiver" >
</receiver>
The Issues are :
1/- This code does not work with REAL DEVICE.
2/- This code does not work if the user restart his device.
A sample on GitHub (i had made some changes as my friend had suggested but still the same errors)
1/- This code does not work with REAL DEVICE.
I've downloaded your project, run on my device and it works, it shows the Toast when I click start, and every minute is showing.
I recommend you to take a look on this question
2/- This code does not work if the user restart his device.
If you want to restart your BroadcastReceiver once the device is rebooted or shut downed, you may want to add this code :
Add this in your manifest.xml
<uses-permission android:name="android.permission.RECEIVE_BOOT_COMPLETED" />
Create another receiver in manifest.xml
<receiver android:name=".BootCompletedIntentReceiver">
<intent-filter>
<action android:name="android.intent.action.BOOT_COMPLETED" />
</intent-filter>
</receiver>
And then create a BroadcastReceiver as you did previously for showing the Toast
class BootCompletedIntentReceiver : BroadcastReceiver() {
override fun onReceive(context: Context, intent: Intent) {
if ("android.intent.action.BOOT_COMPLETED" == intent.action) {
//Start your old broadcastreceiver
}
}
}
For more information you can take a look at this post
Hope it helps.

What happens to a PendingIntent if the target app was force-closed?

I'm actually working on an app that should post a notification 5 days in the future.
Using AlarmManager, I send a PendingIntent to my Receiver class.
Everything works fine until I force close my app. In this case, the notification doesn't appear.
So my question:
What happens to this PendingIntent, which was fired and did not reach its target?
When my app is finally restarted, can I check for PendingIntents, that did not reach its target?
EDIT 1:
These are the essential parts of my Broadcast Receiver:
override fun onReceive(context: Context?, intent: Intent?) {
if (context != null && intent?.action != null) {
when (intent.action) {
INTENT_ACTION_BOOT_COMPLETED -> handleDeviceBoot()
INTENT_ACTION_REMINDER -> handleReminder(context, intent.getLongExtra(EXTRA_ITEM_ID, -1))
}
}
}
private suspend fun schedule(context: Context, itemId: Long, fireDate: LocalDateTime) = withContext(Dispatchers.IO) {
AlarmManagerCompat.setAndAllowWhileIdle(
getAlarmManager(context),
AlarmManager.RTC,
fireDate.atZone(ZoneId.systemDefault()).toInstant().toEpochMilli(),
makePendingIntent(context, itemId)
)
with(AppDatabase.get(context).reminderDao()) {
val oldReminder = getItemReminder(itemId)
if (oldReminder == null) {
insert(Reminder(itemId = itemId, fireDate = fireDate))
} else {
update(Reminder(id = oldReminder.id, itemId = itemId, fireDate = fireDate))
}
}
}
private suspend fun cancel(context: Context, itemId: Long) = withContext(Dispatchers.IO) {
val reminderDao = AppDatabase.get(context).reminderDao()
val reminder = reminderDao.getItemReminder(itemId)
reminder?.let {
getAlarmManager(context).cancel(makePendingIntent(context, itemId))
reminderDao.delete(it)
}
}
private fun getAlarmManager(context: Context) = context.getSystemService(Context.ALARM_SERVICE) as AlarmManager
private fun makePendingIntent(context: Context, itemId: Long): PendingIntent {
val alarmIntent = Intent(context, ReminderManager::class.java).apply {
action = INTENT_ACTION_REMINDER
putExtra(EXTRA_ITEM_ID, itemId)
}
return PendingIntent.getBroadcast(context, itemId.toInt(), alarmIntent, PendingIntent.FLAG_UPDATE_CURRENT)
}
As defined in Official Android Documentation
A PendingIntent itself is simply a reference to a token maintained by the system describing the original data used to retrieve it. This means that, even if its owning application's process is killed, the PendingIntent itself will remain usable from other processes that have been given it. If the creating application later re-retrieves the same kind of PendingIntent (same operation, same Intent action, data, categories, and components, and same flags), it will receive a PendingIntent representing the same token if that is still valid, and can thus call cancel() to remove it.
Revisit your code to check if there is anything else that would be causing this issue.
When you "force close" an application, the application gets set to the "stopped state". In the "stopped state" your application will NOT be automatically started by Android until the user manually restarts the application. This means that if you "force close" your app, your app will not receive any broadcast Intents until it is manually restarted by the user.
I expect (although I have not tried it myself), that if you schedule an alarm to go off at time X and before time X you "force close" the app, when time X happens, the alarm manager will try to send the PendingIntent, however Android will refuse to actually execute the BroadcastReceiver because the app is in the "stopped state". In this case I expect the trigger is lost. Android will not retry or reschedule it.
Basically, when a user "force close"s an app, he is telling Android that he doesn't want that app to run anymore, including any background processes that the app might have, or want to start in the future.
The answer is short: Active PendingIntents are cancelled on an application force-stop.

How to monitor geofences in background on Oreo?

I followed this tutorial: https://developer.android.com/training/location/geofencing and works fine on Android < 8, but in Oreo i have problems due to new OS background limitations.
How can I get geofence transition triggers when app is in background?
I also tried to use a BroadcastReceiver instead of IntentService, but the result is the same.
Pending Intent:
private val geofencePendingIntent: PendingIntent by lazy {
val intent = Intent(context, GeofenceBroadcastReceiver::class.java)
intent.action = "com.example.GEOFENCE_TRANSITION"
PendingIntent.getBroadcast(context, 0, intent, PendingIntent.FLAG_UPDATE_CURRENT)
}
Register geofence:
geofencingClient.addGeofences(request, geofencePendingIntent).run {
addOnSuccessListener {
Log.d(TAG, "Geofence added")
}
addOnFailureListener {
Log.e(TAG, "Failed to create geofence")
}
}
Broadcast Receiver:
class GeofenceBroadcastReceiver : BroadcastReceiver() {
override fun onReceive(p0: Context?, p1: Intent?) {
Log.d(TAG, "onReceive")
}
}
Receiver in Manifest:
<receiver android:name=".GeofenceBroadcastReceiver">
<intent-filter>
<action android:name="com.example.GEOFENCE_TRANSITION"/>
</intent-filter>
</receiver>
Thanks
EDIT: IntentService version
Pending Intent:
private val geofencePendingIntent: PendingIntent by lazy {
val intent = Intent(context, GeofenceIntentService::class.java)
PendingIntent.getService(context, 0, intent, PendingIntent.FLAG_UPDATE_CURRENT)
}
Intent Service:
class GeofenceIntentService : IntentService("GeofenceIntentService") {
override fun onHandleIntent(p0: Intent?) {
Log.d(TAG, "onHandleIntent")
}
}
Service in Manifest:
<service android:name=".GeofenceIntentService"/>
You should get an Intent every couple of minutes on Android 8 when your geofence transition is reached in background.
See: https://developer.android.com/training/location/geofencing#java
Handle geofence transitions
When Location Services detects that the user has entered or exited a geofence, it sends out the Intent contained in the PendingIntent you included in the request to add geofences. This Intent is received by a service like GeofenceTransitionsIntentService, which obtains the geofencing event from the intent, determines the type of Geofence transition(s), and determines which of the defined geofences was triggered. It then sends a notification as the output.
Note: On Android 8.0 (API level 26) and higher, if an app is running in the background while monitoring a geofence, then the device responds to geofencing events every couple of minutes. To learn how to adapt your app to these response limits, see Background Location Limits.
Once the geofence service is registered it´s still there and you have nothing else to do and only check your IntentService for the specific PendingIntent, exclude when the device is rebooted you need to reregister your geofence service.
Also check: https://developer.android.com/about/versions/oreo/background-location-limits
i use dexter library for permission geofence and this work for android 8 9 10 and above you must add background permission
Dexter.withActivity(this#Activity_Map)
.withPermissions(
Manifest.permission.ACCESS_COARSE_LOCATION
,Manifest.permission.ACCESS_FINE_LOCATION
,Manifest.permission.ACCESS_BACKGROUND_LOCATION
)
.withListener(object: MultiplePermissionsListener {
override fun onPermissionsChecked(report: MultiplePermissionsReport?) {
report?.let {
if(report.areAllPermissionsGranted()){
//put your code here
}
}

FCM Push Notification Android receiving 2 notifications in the background

I'm having a problem using the FCM Push Notification Messaging Service, as I've overridden the handleIntent() method to receive the notification when the app is in the foreground. I am also using the onMessageReceived() method.
But when the app is in the background, I will receive 2 notifications, which one of them only opens up the app and runs the MainActivity while the other is opening up the app how I want it to.
FYI: The notification I receive when I am in the foreground is exactly how I want it to open.
This is the code I've written below :
public class MyFirebaseMessagingService extends FirebaseMessagingService {
private final String NOTIFICATION_TYPE = "type";
private final String NOTIFICATION_ID = "id";
private final String NOTIFICATION_TYPE_PRODUCT_DETAIL = "productdetail";
#Override
public void onMessageReceived(RemoteMessage remoteMessage) {
super.onMessageReceived(remoteMessage);
String title = remoteMessage.getNotification().getTitle();R
String body = remoteMessage.getNotification().getBody();
String token = remoteMessage.getFrom();
Log.d("FireBase TAG: ", token);
// Check if message contains a data payload.
if (remoteMessage.getData().size() > 0) {
Log.d("FireBaseMessageService","FireBase Data payload : " + remoteMessage.getData());
}
// Check if message contains a notification payload.
if (remoteMessage.getNotification() != null) {
Log.d(TAG, "Message Notification Body: " + remoteMessage.getNotification().getBody());
}
}
#Override
public void handleIntent(Intent intent) {
super.handleIntent(intent);
String type = intent.getExtras().getString(NOTIFICATION_TYPE, "");
int id = 0;
try {
id = Integer.valueOf(intent.getExtras().getString(NOTIFICATION_ID, ""));
} catch (NumberFormatException e) {
e.printStackTrace();
}
//Intents
Intent mainIntent = MainActivity.newIntent(this);
Intent editProfileIntent = EditProfileActivity.newIntent(this);
Intent settingsIntent = SettingsActivity.newIntent(this);
Intent productIntent = ProductActivity.newNotificationIntent(this, id, false, true);
if (UserManager.getSingleton().isUserLoggedIn(getApplicationContext())) {
PendingIntent pendingIntent;
if (type.equalsIgnoreCase(NOTIFICATION_TYPE_PRODUCT_DETAIL)) {
TaskStackBuilder stackBuilder = TaskStackBuilder.create(this);
stackBuilder.addParentStack(MainActivity.class);
stackBuilder.addNextIntent(mainIntent);
stackBuilder.addNextIntent(productIntent);
editProfileIntent.addFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP);
pendingIntent = stackBuilder.getPendingIntent(0, PendingIntent.FLAG_ONE_SHOT);
}
else {
pendingIntent = PendingIntent.getActivity(this, 0, productIntent,
PendingIntent.FLAG_ONE_SHOT);
}
NotificationCompat.Builder builder = new NotificationCompat.Builder(this)
.setSmallIcon(R.mipmap.ic_launcher)
.setContentTitle(intent.getExtras().getString("gcm.notification.title"))
.setContentText(intent.getExtras().getString("gcm.notification.body"))
.setDefaults(NotificationCompat.DEFAULT_VIBRATE)
.setPriority(NotificationCompat.PRIORITY_MAX)
.setContentIntent(pendingIntent);
NotificationManager manager = (NotificationManager) getSystemService(NOTIFICATION_SERVICE);
manager.notify(0, builder.build());
}
}
}
I have deleted the NotificationCompat.Builder from the onMessageReceived() method.
But I am still receiving two notifications in the background.
App Gradle :
compile 'com.google.firebase:firebase-core:11.4.2' //Firebase
compile 'com.google.firebase:firebase-messaging:11.4.2' //Firebase Cloud Messaging
I've tried searching for a solution online but unluckily there isn't a solution pointing to Android.
You are handling your Notification stuff into handleIntent(Intent intent). You should probably remove super.handleIntent(intent); to prevent the Firebase system to handle notification while the app is in background.
Solution: remove super.handleIntent(intent);
Just make a sendnotification() method and set whatever parameters you want to pass like body i.e sendnotification(String body). Use pending intent to start you activity and when you click on notification your app parse the data to the launcher activity which is defined in manifest, so once you have data in your launcher activity you can send data to other activity using intent.
I think the .setContentText("") is getting called more than 1 times and are you getting same notification two times?
The notification which works perfectly is generated by your code but when your application is not in foreground android system will generate the notification for you. In this case when you don't have the control to send data in your intent that you were sending to open your desired Activity.
In this case, you have to do some modification on your servers payload. You have to add click_action in your payload, this is how android system will identify the destination activity.
Payload Example:
{ "notification": {
"title":"Notification title",
"body":"Notification body",
"click_action":"<Your_destination_activity>",
}, "data":{
"param1":"value1",
"param2":"value2"
},
"priority":"high",
}
Reference:
https://firebase.google.com/docs/cloud-messaging/http-server-ref
yes,
When you app in background you will receive the push at system tray so system tray will create push with notification title and message.
and when you click on the push your initial launcher activity (which mentioned as launcher in manifest) will open.
you can get your notification data at you launcher activity (bundle).
private void handlePush() {
Intent intent = null;
if (bundle.getString("push_type") != null && bundle.getString("push_type").length() > 0) {
switch (bundle.getString("push_type")) {
case PUSH_TYPE_FOLLOW_USER: {
intent = new Intent(this, ProfileExternalActivity.class);
intent.putExtra(Constants.USER_ID, Integer.parseInt(bundle.getString("id")));
intent.putExtra(Constants.FROM_PUSH_NOTIFICATION_SPLASH, true);
intent.addFlags(Intent.FLAG_ACTIVITY_CLEAR_TASK | Intent.FLAG_ACTIVITY_NEW_TASK);
break;
}
}
if (intent != null)
startActivity(intent);
finish();
}
}
and you need to check activty have data or not
if (bundle != null)
handlePush();
else //your next activity
FYI : https://firebase.google.com/docs/cloud-messaging/android/receive
or
you can get payload object instead of data object inside notification , if you have payload object in your notification object, push all time received at your onMessageReceived().
for people still having this issue:
Here is a hack to prevent this behavior. I've looked all over and there seems to be minimal info about this, but if you save the actual message being sent in shared preferences and then do a check against that value in onRecieve, you can easily prevent this. The only downside is that your user can't send the exact same message two times in a row in the form of a notification (but that would be annoying anyway). example:
#Override
public void onMessageReceived(RemoteMessage remoteMessage) {
SharedPreferences Settings = getDefaultSharedPreferences(context);
SharedPreferences.Editor editor = Settings.edit();
message = remoteMessage.getNotification().getBody();
from = remoteMessage.getFrom(); //this comes through as the topic, oddly...
if(from.equals("/topics/"+userID+deviceID+"all")) {
if(!message.equals(Settings.getString("messageall",null))) {//this filters any dupe messages
utils.postNotification(title, message, context, extra, "messages");//create notification
editor.putString("messageall", message);//always update to the last message
editor.commit();
}
}
}

Categories

Resources