Different behavior of notification fullScreenPendingIntent in Android 10 and Android 13 - android

I am working on an Android application in which I want to open fullScreenPendingIntent from the notification when app is in the background (user press HOME button). It is an application which will not be uploaded to Google Store and has granted permissions for android.permission.USE_FULL_SCREEN_INTENT, android.permission.SYSTEM_ALERT_WINDOW, android.permission.REQUEST_IGNORE_BATTERY_OPTIMIZATIONS, android.permission.FOREGROUND_SERVICE, android.permission.POST_NOTIFICATIONS for Android 13 and more.
Part of the code from manifest
# just Splash activity on start and for permissions
<activity
android:name=".ui.splash.SplashActivity"
android:hardwareAccelerated="true"
android:screenOrientation="portrait"
android:exported="true">
<intent-filter>
<action android:name="android.intent.action.MAIN" />
<category android:name="android.intent.category.DEFAULT" />
<category android:name="android.intent.category.LAUNCHER" />
</intent-filter>
</activity>
# Main Activity
<activity
android:name=".MainActivity"
android:hardwareAccelerated="true"
android:screenOrientation="portrait"
android:launchMode="singleInstance"
android:exported="false">
<intent-filter>
<category android:name="android.intent.category.DEFAULT" />
</intent-filter>
</activity>
# Activity for call when app in background
<activity
android:name=".ui.activity.call.CallFromBackground"
android:screenOrientation="portrait"
android:launchMode="singleTop"
android:noHistory="true"/>
When the call is received from the core service (.so lib) I trigger Broadcast message and receiver is defined in MainActivity. In the next steps notification is created with contentPendingIntent, fullScreenPendingIntent and an Action.
val notificationBuilder = NotificationCompat.Builder(context, CALL_CHANNEL_ID)
.setSmallIcon(R.mipmap.ic_launcher)
.setContentTitle("$callWay - $callState - ${sessionState.callName}")
.setAutoCancel(false)
.setOngoing(true)
.setSilent(callNotificationAdditionalData.silent)
.setContentIntent(contentIntent)
.setPriority(NotificationCompat.PRIORITY_MAX)
.setCategory(NotificationCompat.CATEGORY_CALL)
if (callNotificationAdditionalData.fullScreenPendingIntent != null) {
notificationBuilder.setFullScreenIntent(callNotificationAdditionalData.fullScreenPendingIntent, true)
}
if (callNotificationAdditionalData.answerActionPendingIntent != null) {
notificationBuilder.addAction(NotificationCompat.Action(null, context.getString(R.string.msg_answer), callNotificationAdditionalData.answerActionPendingIntent))
}
if (callNotificationAdditionalData.includeDeclinePendingIntent) {
notificationBuilder.addAction(NotificationCompat.Action(null, context.getString(R.string.msg_decline), declineIntent(context, sessionId)))
}
val channel = NotificationChannel(
CALL_CHANNEL_ID, context.getString(R.string.msg_call_in_progress), NotificationManager.IMPORTANCE_HIGH
).apply {
lockscreenVisibility = Notification.VISIBILITY_PUBLIC
}
val notificationManagerCompat = NotificationManagerCompat.from(context)
notificationManagerCompat.createNotificationChannel(channel)
notificationManagerCompat.notify(sessionId, notificationBuilder.build())
Such notification on Android 10 is displayed and fullScreenPendingIntent (android:name=".ui.activity.call.CallFromBackground") is shown.
In Android 13 only notification is displayed and fullScreenPendingIntent does not appear. If I click on notification, contentPendingIntent is displayed (this is ok).
I tried a lot of stuff and my workaroud is not nice. For now if running version is Android 13 I manually (before notification is created) start MainActivity (with flags Intent.FLAG_ACTIVITY_REORDER_TO_FRONT or Intent.FLAG_ACTIVITY_BROUGHT_TO_FRONT - have no idea if this is needed) and then CallFromBackground activity.
val mainActivityToFront = Intent(context, MainActivity::class.java)
mainActivityToFront.flags = Intent.FLAG_ACTIVITY_REORDER_TO_FRONT or Intent.FLAG_ACTIVITY_BROUGHT_TO_FRONT
context.startActivity(mainActivityToFront)
context.startActivity(!! Intent which is also used in fullScreenPendingIntent !!)
Is there a solution for this problem or it is not possible to fix this?
Maybe my architecture is completely wrong and I have to start foreground service for each call (multiple parallel calls are possible). Can foreground notification open fullScreenPendingIntent? There are also limitations when the app can start the foreground service. I already have one and it used for GPS locations.

Related

Flutter app does not come to foreground when tapped on native android background service notification

I am new to learning flutter. My flutter app has a native android background service on kotlin where I have a socket running and whenever the socket listens to something I generate a notification using NotificationCompat.Builder.
But I am unable to bring the Flutter app back to foreground when ever the user taps on the notification.
I have tried creating a pendingintent and passing it to notificationbuilder setContentIntent() but nothing happens on tap.
shownotification function on Native background service:
fun shownotification (){
packageNamer = this.getPackageName()
launchIntent = this.getPackageManager().getLaunchIntentForPackage(packageName)
var className = launchIntent?.getComponent()!!.className.javaClass
intent.action = "SELECT_NOTIFICATION"
intent.setClass(this,className)
pendingIntent = PendingIntent.getActivity(this, 1, intent, PendingIntent.FLAG_UPDATE_CURRENT)
var builder = NotificationCompat.Builder(this, "notifications")
.setOngoing(true)
.setContentIntent(pendingIntent)
.setFullScreenIntent(pendingIntent, true)
.setSmallIcon(R.drawable.common_google_signin_btn_icon_dark)
.setContentTitle("My notification")
.setContentText("Much longer text that cannot fit one line...")
.setStyle(NotificationCompat.BigTextStyle()
.bigText("Much longer text that cannot fit one line..."))
.setPriority(NotificationCompat.PRIORITY_HIGH)
manager?.notify(456,builder.build())
}
AndroidManifest.xml file:
<uses-permission android:name="android.permission.INTERNET"/>
<uses-permission android:name="android.permission.FOREGROUND_SERVICE"/>
<!-- io.flutter.app.FlutterApplication is an android.app.Application that
calls FlutterMain.startInitialization(this); in its onCreate method.
In most cases you can leave this as-is, but you if you want to provide
additional functionality it is fine to subclass or reimplement
FlutterApplication and put your custom class here. -->
<application
android:name=".MyApplication"
android:label="bizzyb_demo"
android:icon="#mipmap/ic_launcher">
<service android:name=".MyService" android:exported="true" android:enabled="true"/>
<activity
android:name=".MainActivity"
android:launchMode="singleTop"
android:theme="#style/LaunchTheme"
android:configChanges="orientation|keyboardHidden|keyboard|screenSize|locale|layoutDirection|fontScale|screenLayout|density|uiMode"
android:hardwareAccelerated="true"
android:windowSoftInputMode="adjustResize">
<!-- This keeps the window background of the activity showing
until Flutter renders its first frame. It can be removed if
there is no splash screen (such as the default splash screen
defined in #style/LaunchTheme). -->
<meta-data
android:name="io.flutter.app.android.SplashScreenUntilFirstFrame"
android:value="true" />
<intent-filter>
<action android:name="android.intent.action.MAIN"/>
<category android:name="android.intent.category.LAUNCHER"/>
</intent-filter>
<intent-filter>
<action android:name="FLUTTER_NOTIFICATION_CLICK" />
<category android:name="android.intent.category.DEFAULT" />
</intent-filter>
</activity>
</application>
What am I doing wrong here. I believe I am missing something very obvious here as I am new to mobile apps development.
Your expert feedbacks will be appreciated.
Thanks
You need to include click_action: FLUTTER_NOTIFICATION_CLICK as a "Custom data" key-value-pair in the notification payload.
Bundle bundle = new Bundle();
bundle.putString(Constants.EXAM_ID,String.valueOf(lectureDownloadStatus.getExamId()));
var builder = NotificationCompat.Builder(this, "notifications")
.setOngoing(true)
.setContentIntent(pendingIntent)
.setFullScreenIntent(pendingIntent, true)
.setSmallIcon(R.drawable.common_google_signin_btn_icon_dark)
.setContentTitle("My notification")
.setContentText("Much longer text that cannot fit one line...")
.setStyle(NotificationCompat.BigTextStyle()
.bigText("Much longer text that cannot fit one line..."))
.setPriority(NotificationCompat.PRIORITY_HIGH)
.setExtras(bundle) // Set the bundle

Bring a singleInstance Activity Back Using a Notification

I have a normal activity, let's call it A, and it's the first activity presented to the user when opening the app. Activity A has a button that launches an activity, let's call it B, with launchMode set to singleInstance in the manifest. Activity B does some processing.
Users can press the home button and open the app again, which will present them with the starting activity, aka activity A. If users click on the button again (in activity A), they will be presented with activity B. In the case, activity B will not be restarted, i.e., onCreate will not be called, since it is singleInstance, which is what I want.
I want to make it easier for the users to come back to activity B once it started if they pressed the home button. So, I created an ongoing notification that lets the users bring activity B back. The ongoing notification will be canceled once activity B is finished.
Now to the problem, clicking the ongoing notification recreates activity B again, i.e., the onCreate is being called again. I don't know why the behavior here is not the same as clicking on the button on activity A. Here is how I created the notification:
Intent notifyIntent = new Intent(mContext, CallActivity.class);
PendingIntent notifyPendingIntent = PendingIntent.getActivity(
mContext, 0, notifyIntent, PendingIntent.FLAG_NO_CREATE);
NotificationCompat.Builder builder = new NotificationCompat.Builder(mContext, CHANNEL_ID)
.setSmallIcon(R.drawable.baseline_call_white_18)
.setContentTitle(title)
.setContentText(text)
.setOngoing(true)
.setPriority(NotificationCompat.PRIORITY_HIGH)
.setContentIntent(notifyPendingIntent);
NotificationManagerCompat notificationManager = NotificationManagerCompat.from(mContext);
notificationManager.notify(NOTIFICATION_ID, builder.build());
Can anyone tell me why this is not working and how can I get it to work the way I described?
EDIT
Here is a snippet of my manifest:
<application
android:name="com.mnm.caller.IMApplication"
android:allowBackup="true"
android:icon="#mipmap/ic_launcher"
android:label="#string/app_name"
android:roundIcon="#mipmap/ic_launcher"
android:supportsRtl="true"
android:theme="#style/AppTheme"
tools:ignore="GoogleAppIndexingWarning">
<activity
android:name="com.mnm.caller.activities.SplashActivity"
android:configChanges="orientation|keyboardHidden"
android:noHistory="true"
android:screenOrientation="portrait"
android:theme="#style/AppTheme.Splash">
<intent-filter>
<action android:name="android.intent.action.MAIN" />
<category android:name="android.intent.category.LAUNCHER" />
</intent-filter>
</activity>
<activity
android:name="com.mnm.caller.activities.LoginActivity"
android:configChanges="orientation|keyboardHidden"
android:theme="#style/AppTheme.NoTitleBar"
android:screenOrientation="portrait" />
<activity
android:name="com.mnm.caller.activities.HomeActivity"
android:configChanges="orientation|keyboardHidden"
android:theme="#style/AppTheme.NoTitleBar"
android:screenOrientation="portrait" />
<activity
android:name="com.mnm.caller.activities.CallActivity"
android:configChanges="orientation|keyboardHidden"
android:launchMode="singleInstance"
android:screenOrientation="portrait"
android:theme="#style/AppTheme.NoTitleBar" />
<service
android:name="com.mnm.caller.services.IMFirebaseMessagingService"
android:stopWithTask="false">
<intent-filter>
<action android:name="com.google.firebase.MESSAGING_EVENT" />
</intent-filter>
</service>
</application>
In a comment you wrote:
I'm actually developing a calling app. Activity A is the home screen,
while B is the calling activity. I want to let the users navigate back
to the home screen during a call, so I intentionally and knowingly
chose to create two instances of the app in recent apps (you can see
the exact behavior in the default phone app on Android)
If this is the case, you probably do want to have 2 separate tasks that you can switch between. To do this, you need to use taskAffinity. Your CallActivity should have launch mode of singleTask or singleInstance and you should set android:taskAffinity="call" or something like that. In order not to confuse your users, you should also provide a different android:label and a different android:icon for CallActivity so that when this task appears in the list of recent tasks it looks different than the rest of your app. Make sure that when you launch CallActivity you also set FLAG_ACTIVITY_NEW_TASK. You should also set this flag when you build the Notification.
You need to set FLAG_ACTIVITY_SINGLE_TOP to the Intent instance (in your case notifyIntent) before creating the PendingIntent object.
In other words:
Intent notifyIntent = new Intent(mContext, CallActivity.class).addFlags(Intent.FLAG_ACTIVITY_SINGLE_TOP);
PendingIntent notifyPendingIntent = PendingIntent.getActivity(
mContext, 0, notifyIntent, PendingIntent.FLAG_NO_CREATE);
NotificationCompat.Builder builder = new NotificationCompat.Builder(mContext, CHANNEL_ID)
.setSmallIcon(R.drawable.baseline_call_white_18)
.setContentTitle(title)
.setContentText(text)
.setOngoing(true)
.setPriority(NotificationCompat.PRIORITY_HIGH)
.setContentIntent(notifyPendingIntent);
NotificationManagerCompat notificationManager = NotificationManagerCompat.from(mContext);
notificationManager.notify(NOTIFICATION_ID, builder.build());

Android - redirect a fragment in main activity from notification

I have a loginActivity and MainActivity with multiple fragments and one of them is called NotificationFragment.
Requirement: Assuming user is already logged in and is currently on Home Fragment (inside Main Activity) and app is in background. Now they receive a push notification, user should be redirected to Notification Fragment (on Main Activity).
As of now, Login Activity is receiving intent data from notification. Login Activity is our launch activity currently.
Question: How should Login Activity (on back stack) inform Main Activity to redirect user from Home Fragment to Notification Fragment?
Manifest looks like this:
<activity
android:name="com.X.LoginActivity"
android:configChanges="orientation"
android:icon="#mipmap/ic_launcher"
android:screenOrientation="portrait"
android:windowSoftInputMode="adjustPan">
<intent-filter>
<action android:name="android.intent.action.MAIN" />
<category android:name="android.intent.category.LAUNCHER" />
</intent-filter>
<intent-filter>
<!-- Sets the intent action to view the activity -->
<action android:name="android.intent.action.VIEW" />
<!-- Allows the link to be opened from a web browser -->
<category android:name="android.intent.category.BROWSABLE" />
<!-- Allows the deep link to be used without specifying the app name -->
<category android:name="android.intent.category.DEFAULT" />
</intent-filter>
</activity>
<activity
android:name="com.X.MainActivity"
android:configChanges="orientation"
android:launchMode="singleTop"
android:screenOrientation="portrait"
android:theme="#style/AppTheme.NoActionBar"
android:windowSoftInputMode="adjustPan" />
Try this
private void sendMyNotification(String title,String message) {
//On click of notification it redirect to this Activity
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);
Uri soundUri= RingtoneManager.getDefaultUri(RingtoneManager.TYPE_NOTIFICATION);
Bitmap icon = BitmapFactory.decodeResource(getResources(),
R.mipmap.ic_appicon);
NotificationCompat.Builder notificationBuilder = new NotificationCompat.Builder(this,"Default")
.setSmallIcon(R.drawable.ic_noti_new)
.setLargeIcon(icon)
.setContentTitle(title)
.setContentText(message)
.setAutoCancel(true)
.setSound(soundUri)
.setContentIntent(pendingIntent);
NotificationManager notificationManager =
(NotificationManager) getSystemService(Context.NOTIFICATION_SERVICE);
notificationManager.notify(0, notificationBuilder.build());
}
it will trigger the main activity.
Add
android:launchMode="singleTask" in your mainactivity to avoid running mutiple instance of MainActivity.
<activity
android:name=".MainActivity"
android:launchMode="singleTask" />

Android notification Reorder to front doesn't work. Copied from APP that it has worked in

I've copied a code from dummy project testing Services and Notifications in which reoder to font worked like a charm.
Here is the code for notification (pretty same as in tutorials)
NotificationCompat.Builder nBuilder = new NotificationCompat.Builder(this)
.setSmallIcon(R.drawable.ic_launcher)
.setAutoCancel(true)
.setContentTitle("Request awaiting")
.setContentText("There is a service request awaiting for Your reaction");
Intent resultIntent = new Intent(this, MainActivity.class);
resultIntent.setAction(Intent.ACTION_MAIN);
resultIntent.addCategory(Intent.CATEGORY_LAUNCHER);
resultIntent.addFlags(Intent.FLAG_ACTIVITY_REORDER_TO_FRONT);
TaskStackBuilder stackBuilder = TaskStackBuilder.create(this);
stackBuilder.addParentStack(MainActivity.class);
stackBuilder.addNextIntent(resultIntent);
PendingIntent resultPendingIntent = PendingIntent.getActivity(this, 0, resultIntent, Intent.FLAG_ACTIVITY_REORDER_TO_FRONT);//stackBuilder.getPendingIntent(0, Intent.FLAG_ACTIVITY_REORDER_TO_FRONT);
nBuilder.setContentIntent(resultPendingIntent);
NotificationManager mNotificationManager = (NotificationManager)getSystemService(Context.NOTIFICATION_SERVICE);
Notification notification = nBuilder.build();
mNotificationManager.notify(1, notification);
Manifest looks like :
<application android:allowBackup="true" android:icon="#drawable/ld"
android:label="#string/app_name" android:theme="#style/AppTheme">
<activity
android:name="com.iraasta.cloudcab.driver.MainActivity"
android:launchMode="singleTop"
android:label="#string/app_name"
android:screenOrientation="portrait">
<intent-filter>
<action android:name="android.intent.action.MAIN" />
<category android:name="android.intent.category.LAUNCHER" />
</intent-filter>
</activity>
</application>
It looks exactly same in my other app, in which it perfectly brings app to front like when selecting from the home screen.
But in this one it calls OnCreate every time and loses whole state.
To bring your application to the front (if it is in the background) in whatever state it is in, or to launch your app (if it isn't aleady running), you need to launch your "root activity" (the one with ACTION=MAIN and CATEGORY=LAUNCHER) and set the flag Intent.FLAG_ACTIVITY_NEW_TASK. This will launch the activity in a new task (if your app isn't already running), or bring the existing task to the foreground (if your app is already running).
Since you are doing this from a Notification, you should be setting Intent.FLAG_ACTIVITY_NEW_TASK in the Intent you pass to the Notification. However, Android is nice enough to set this flag for you if you forget to do it.
I'm not exactly sure why setting Intent.FLAG_ACTIVITY_REORDER_TO_FRONT caused your problem, but I can imagine that this somehow confuses Android.
Not using any flag fixed it.
To people looking at this post in future.
If Your app uses single activity and You want to bring it to front after clicking the Notification just leave flags as integer 0.
It fixed my problem.
Thanks for suggestions
Bounty goes to the person that will explain why is this flag ruining everything.
Setting android:launchMode="singleTask" in a manifest for an activity you wanna bring to the front works for me

Android starting an intent doesn't set the action

I'm working with push notifications. Receiving and displaying notifications is currently working, however the on-click event isn't acting as it should.
int NOTIFICATION_ID = 1593;
NotificationManager notificationManager = (NotificationManager) getSystemService(NOTIFICATION_SERVICE);
Notification notification = new Notification(R.drawable.notification, title, System.currentTimeMillis());
notification.flags |= Notification.FLAG_AUTO_CANCEL;
Intent notificationIntent = new Intent(this, MyMainActivity.class);
notificationIntent.putExtra("test", "test");
notificationIntent.setAction("load_notifications");
PendingIntent intentNotification = PendingIntent.getActivity(this, 999, notificationIntent, 0);
notification.setLatestEventInfo(this, title, body, intentNotification);
notificationManager.notify(NOTIFICATION_ID, notification);
That's how I display my notification and it also includes starting/resuming my main activity.
However, the putExtra("test", "test") and the setAction seem to have no effect if I click on a notification while I'm in the app. If my app isn't working, launching it from the notification works fine.
My onResume function at my main activity:
public void onResume() {
super.onResume();
if(this.getIntent().getAction().equalsIgnoreCase("load_notifications")) {
//Do stuff
}
}
My app config is as following:
<application
android:icon="#drawable/ic_launcher"
android:label="#string/app_name" >
<activity
android:name=".Activity"
android:label="#string/app_name"
android:configChanges="orientation"
android:launchMode="singleInstance"
>
<intent-filter>
<action android:name="android.intent.action.MAIN" />
<category android:name="android.intent.category.LAUNCHER" />
</intent-filter>
</activity>
<!-- Push notifications -->
<receiver android:name="com.google.android.gcm.GCMBroadcastReceiver" android:permission="com.google.android.c2dm.permission.SEND" >
<intent-filter>
<action android:name="com.google.android.c2dm.intent.RECEIVE" />
<action android:name="com.google.android.c2dm.intent.REGISTRATION" />
<category android:name="com.app.android" />
</intent-filter>
</receiver>
<service android:name=".GCMIntentService" />
</application>
the answer maybe be here : Action buttons are not shown in notification
Notification Actions were introduced in API 16.
This means that you should be setting your target SDK to 16 or above.
However, only Jelly Bean and above can take advantage of the Notification Actions - make sure to test this feature on those platforms.
NotificationCompat.Builder takes care of generating a Notification compatible with whatever API it is running on, so keep using it if you are going to be supporting Ice Cream Sandwich and older. If not, simply using Notification.Builder will suffice (after changing the target SDK of course).

Categories

Resources