"smart" android activation from a push notification - android

I have a simple task - activate an app from the push on a particular activity (not on the start activity)
Imaging I have 3 activities in the app:
A (splash)
B (items list)
C (selected item details)
Some pre-requirements:
With push I'm getting the id of item to select.
On the splash I'm forcing an authentication.
One of the conditions - I couldn't move authentication let's say to another activity or to application service for example.
Now I could create several statements. When I tap on push to activate the app:
When push is arrived the PushIntentService generates a notification which specifies item id in intent extras If the app was terminated I should start the app from the activity A (to force authentication)
If the app was backgrounded (works in background) I should re-activate it at the same place (to skip re-authentication)
Once the app is activate I will navigate to Activity C with item id fetched from extras.
Right now I'm using the following code to generate the notification (item 1, Xamarin.Android syntax):
var resultIntent = new Intent(Application.Context, typeof(SplashScreen));
resultIntent.AddFlags(ActivityFlags.ClearTop | ActivityFlags.SingleTop);
if (extras.ContainsKey("ItemId"))
{
var itemId = extras["ItemId"];
resultIntent.PutExtra("ItemId", itemId);
}
var resultPendingIntent = PendingIntent.GetActivity(Application.Context, 0, resultIntent, 0);
builder.SetContentIntent(resultPendingIntent);
var notification = builder.Build();
This notification works absolutely fine in all cases but I see here one issue.
I'm restarting the app from the very beginning every time I'm tapping on a notification.
What I want is when the app is backgrounded I need just to activate it (like iOS does) and navigate to required page (faster activation and avoid re-authentication).
How can I achieve this and modify the code above?

Create a new Activity for this. The notification should start that Activity (without any flags).
In onCreate() of this new Activity, do something like this:
super.onCreate(...);
if (!isTaskRoot() && alreadyAuthenticated) {
// Go directly to details page
Intent redirectIntent = new Intent(this, Details.class)
redirect.putExtra("id", itemId);
startActivity(redirectIntent);
else {
// This means the app was not running, so redirect to Splash
Intent redirectIntent = new Intent(this, Splash.class)
startActivity(redirectIntent);
}
finish();
isTaskRoot() will return true if the app was not running when the user clicked on the Notification. If the app was already running, it should return false.
To test if you are already authenticated, you could call a static method or check a static variable or maybe you have some other method of doing this. Depending on what you want the Activity stack to look like if the user was already in the "item details" or "item list" activites, you may want to add SINGLE_TOP and/or CLEAR_TOP flags when redirecting to the item details Activity.
Hopefully you get the point.

I found the answer on how to simulate launcher icon tap intent. I'm using it to create pending intent for my push:
var launchIntent = PackageManager.GetLaunchIntentForPackage(PackageName);
This is exactly what I wanted and it works perfectly fine in my case.

Related

Building a task stack for activity started after Firebase Notification

Using Firebase Cloud Messaging, when the app is in the background and a message has arrived, the message goes to the system tray. When the user than clicks on the notification, the app gets launched and the launcher activity gets the message data in the Intent.
In my case, this notification is about some new results, so when pressed, I want to start a ResultsActivity.
In order to make this happen I do this in the OnStart of the LauncherActivity
:
Intent intent = getIntent();
String searchId = intent.getStringExtra("search_id");
if(searchId != null){
Intent resultsIntent = new Intent(LauncherActivity.this, ResultsActivity.class);
resultsIntent.putExtra(ResultsActivity.SEARCH_ID_EXTRA, searchId);
startActivity(resultsIntent);
}
This all works great.
The problem is now when clicking on the "up" arrow on the app bar, the app does not go to the parent activity that is defined in the manifest (which is not the launcher activity) but to the launcher activity. This is not surprising since the ResultActivity is started from the LauncherActivity, but this is not the wanted behavior. The wanted behavior is for the back arrow to send to the parent activity, which happens to be MainActivity.
I know there is the TaskStackBuilder for that kind of stuff, but I don't know how I can apply that pattern to my case here where I start the activity "normally" from another activity and not from some Notification Builder.
Is TaskStackBuilder the right solution here? If so, how can I change the code above to use it? if not, what is the right solution for this?
What I ended up doing is on the server side, with the firebase cloud messaging admin, instead of including a firebase_admin.messaging.Notification object in the firebase_admin.messaging.Message object I am then sending, I just put the notification title and text in the Message's data, and then build a notification by myself normally in MyFirebaseMessagingService. Since I'm now building the notification by myself I can add the TaskStackBuilder normally.
I guess this doesn't really answer the question of how to add a back stack when not using Notification.Builder, but it's probably a better solution anyway.

Dynamic Shortcuts to open Fragments in Android

Hi I'm developing an application that has 2 types of user: Admin and normal user; The admin obviously has more actions than the normal user, so I need to use dynamic Shortcuts, depending on the user the Shortcuts are created.
At this point everything is already codified and working. However, at the time of assigning an Intent, even to the MainActivity I receive an error.
Intent intent = new Intent();
intent.setComponent(new ComponentName("com.motusk.Monit", "com.motusk.Monit.activity.MainActivity"));
shortcut.add(new ShortcutInfo.Builder(this, "ub")
.setShortLabel("Location")
.setLongLabel("Location")
.setIcon(Icon.createWithResource(this, R.drawable.bg))
.setIntent(intent)
.build());
I also tried with:
Intent intent = new Intent(this, MainActivity.class);
But, in both I get the error:
java.lang.RuntimeException: Unable to start activity ComponentInfo{com.motusk.Monit/com.motusk.Monit.activity.MainActivity}: java.lang.NullPointerException: intent's action must be set
In what I need help with is:
1) How to create a correct Intent to the MainActivity?
2) How to know which shortcut was pressed? (The process of depending on which shortcut was pressed to open a certain Fragment will be performed in the MainActivity, that's why I need to know which Shortcut was pressed).
As per the error message, your Intent must set an action with setAction:
intent.setAction("LOCATION_SHORTCUT");
You can then check the action in your Activity:
String action = getIntent() != null ? getIntent().getAction() : null;
if ("LOCATION_SHORTCUT".equals(action)) {
// Show the correct fragment
}

Avoid caching Intent Extras after App is closed with back press [duplicate]

I have issue in intent of my launcher activity.Scenerio is:
1. Send intents form notification service to my launcher activity
PendingIntent contentIntent = PendingIntent.getActivity(this, TripLoggerConstants.PENDING_TRIPS_NOTIFICATION_ID, new Intent(this, MainActivity.class).putExtra("is_log", true), Intent.FLAG_ACTIVITY_CLEAR_TOP);
2. In my MainActivity i getting this intent. code is:
if(this.getIntent().getExtras()!=null){
boolean isLogNewTripScreen = (boolean)this.getIntent().getExtras().getBoolean("is_log");
}
}
3. this work fine but when i come from notification service,but when i launch from not notification service ,that data in intentis still there.How can i remove that data from intent.
EDIT: I've created a sample application to test this problem and possible solutions. Here are my findings:
If you launch your app from a notification with extras and then later return to your app by selecting it from the list of recent tasks, Android will launch the app again the same way it was launched from the notification (ie: with the extras). This is either a bug or a feature, depending on who you ask.
You'll need to add additional code to deal with this situation. I can offer 2 suggestions:
1. Use FLAG_ACTIVITY_EXCLUDE_FROM_RECENTS
When you create your notification, set the flag Intent.FLAG_ACTIVITY_EXCLUDE_FROM_RECENTS in the Intent. Then, when the user selects the notification and launches the app from the notification, this will not create an entry for this task in the list of recent tasks. Also, if there was an entry in the list of recent tasks for this application, that entry will also be removed. In this case, it will not be possible for the user to return to this task from the list of recent tasks. This solves your problem by removing the possibility that the user launches the app from the list of recent tasks (but only when the app has been launched from the notification).
2. Detect FLAG_ACTIVITY_LAUNCHED_FROM_HISTORY
When the user launches your app from the list of recent tasks, Android sets the flag Intent.FLAG_ACTIVITY_LAUNCHED_FROM_HISTORY in the Intent that is passed to onCreate() of your launch activity. You can detect the presence of this flag in onCreate() and then you know that the app has been launched from the recent tasks list and not from the notification. In this case, you can just ignore the fact that the extras in the Intent still contain data.
Choose the solution that best suits the workflow for your application. And thanks for the question, this was an interesting challenge to solve :-)
Additional information:
You are creating the PendingIntent incorrectly. You are calling
PendingIntent contentIntent = PendingIntent.getActivity(this,
TripLoggerConstants.PENDING_TRIPS_NOTIFICATION_ID,
new Intent(this, MainActivity.class).putExtra("is_log", true),
Intent.FLAG_ACTIVITY_CLEAR_TOP);
You are passing Intent.FLAG_ACTIVITY_CLEAR_TOP as the 4th parameter to getActivity(). However, that parameter should be PendingIntent flags. If you want to set FLAG_ACTIVITY_CLEAR_TOP on the Intent, you need to do it this way:
PendingIntent contentIntent = PendingIntent.getActivity(this,
TripLoggerConstants.PENDING_TRIPS_NOTIFICATION_ID,
new Intent(this, MainActivity.class).putExtra("is_log", true)
.addFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP), 0);
I noticed that using fragments. I read a QR Code in Activity A that opens fragment 1, send its content to a webservice and if goes right, replace it with fragment 2. When user press back, the onBackPressed in Activity A call finish. If user select the app again in the list, it was opening fragment 1 instead of fragment 2.
I solved that checking in onBackPressed if extra contains a field indicating that fragment 2 was already opened. If true, moveTaskToBack(true) is called instead of finish()
Activity A
#Override
public void onBackPressed() {
Bundle extras = getIntent().getExtras();
if(extras.containsKey(Constants.TICKET_DONT_SHOW_QRCODE_SCREEN)){
moveTaskToBack(true);
}else {
finish();
}
}
Fragment 2
Intent mainIntent = getActivity().getIntent();
mainIntent.putExtra(Constants.TICKET_DONT_SHOW_QRCODE_SCREEN, true);
getActivity().setIntent(mainIntent);
I've tested all the answers of stackoverflow with no luck, what worked for me was this. Create a helper class to check the activity flags. Or a function, it does not matter.
object FlagHelper {
fun notLaunchedFromNotification(activity: AppCompatActivity): Boolean {
return activity.intent.flags and Intent.FLAG_ACTIVITY_LAUNCHED_FROM_HISTORY == Intent.FLAG_ACTIVITY_LAUNCHED_FROM_HISTORY
}
}
Then use as the following code. It returns a boolean so you can check the intent extras when it's false
val notLaunchedFromNotification = FlagHelper.notLaunchedFromNotification(this)
Add android:launchMode="singleInstance" to your launcher activity
and then Use flag Intent.FLAG_ACTIVITY_EXCLUDE_FROM_RECENTS while starting your activity

Android deep-linking. Intent doesn't reset when app is opened from history

I have a problem regarding Android task and intent management.
Scenario
User gets a push with a deep-link into the app.
We show a notification putting the URI into the Intent Data.
User clicks the notification and is taken into the app and redirected to some Feature1Activity described by the deep-link.
User looks around, and backs out of the app.
Later, user opens the app from history (long-press home or multitasking button).
Now the same intent that were used from the notification (with the deep-link in the Intent Data) is used to start the app.
Hence, user is taken into the Feature1Activity again.
Problem:
Starting the app from history (long-press home or multitasking button) does not reset the Task (which it does when launching from app icon).
I understand that starting an app from history is not supposed to reset the task since it is intended to be used as "get-right-back-where-you-were". However, in my case this is an issue since the launch of the app from a notification is a one time thing.
Anyone else encountered this problem? Anyone know any solution?
More in-depth
The intent inside the PendingIntent is built like this:
Intent intent = new Intent (Intent.ActionView);
intent.addFlags (Intent.FLAG_ACTIVITY_NEW_TASK);
intent.addFlags (Intent.FLAG_ACTIVITY_CLEAR_TOP);
intent.addFlags (Intent.FLAG_ACTIVITY_CLEAR_WHEN_TASK_RESET);
intent.setData (Uri.Parse (DEEP_LINK_URL));
I found out about the FLAG_ACTIVITY_CLEAR_WHEN_TASK_RESET just this day and really thought that it would git rid of my problem but it made no difference.
There are three activities of interest:
SplashActivity (main launcher & listener of the deep-linking schema -- this activity just redirects either to login or OverviewActivity)
OverviewActivity (authorized user's main activity)
Feature1Activity (any feature that the deep-link is pointing to)
What happens when the user clicks the notification is that the SplashActivity acts as a listener for the schema and converts the deep-link url to two intents to start up OverviewActivity and Feature1Activity using Activity.startActivities (Intent[]).
When I look at the intent from the notification inside SplashActivity it always contain the deep-link in the Data.
One work around
There is a work around, setting some booleanExtra field to the notification intent (for instance "ignoreWhenLaunchedFromHistory" = true) and then check in SplashActivity before redirecting
boolean fromHistory = (getIntent().getFlags() & FLAG_ACTIVITY_LAUNCHED_FROM_HISTORY) == FLAG_ACTIVITY_LAUNCHED_FROM_HISTORY;
if (fromHistory && getIntent().getBooleanExtra ("ignoreWhenLaunchedFromHistory", false))
// Don't follow deep-link even if it exists
else
// Follow deep-link
Except that it hackish and ugly, can you see any problems with this work around?
EDIT: The work around only works when I am responsible for sending the Intent with the deep-link. Since no external source can know about the "ignoreWhenLaunchedFromHistory" extra.
From what I get, maybe using android:excludeFromRecents="true"on your manifest (as a property for the Activity declaration) might ameliorate the issue?

Activity opened twice

I have an application that uses Urban Airship for push notification. When a notification arrives and the user clicks on it, activity A in my application should open and do something.
I've installed the BroadcastReceiver as is shown in the docs, and it's almost working.
When my app is in the foreground I don't let the user see the notification at all, and just handle it automatically.
When my app is not running at all, the activity opens up just fine.
When my app is in the background (which always happens when A is the top activity), a second instance of Activity A is created.
This is, of course, a problem. I don't want two A activities, I just want one of them. Here's the relevant BroadcastReceiver code:
#Override
public void onReceive(Context ctx, Intent intent)
{
Log.i(tag, "Push notification received: " + intent.toString());
String action = intent.getAction();
int notificationId = intent.getIntExtra(PushManager.EXTRA_NOTIFICATION_ID, -1);
if(action.equals(PushManager.ACTION_NOTIFICATION_OPENED))
{
Intent intentActivity = new Intent(ctx, ActivityA.class);
intentActivity.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
UAirship.shared().getApplicationContext().startActivity((intentActivity);
}
}
UPDATE:
I tried to bypass this bug by calling System.exit(0) when the user presses Back on Activity A. The process ended, but then it was restarted immediately! My BroadcastReceiver is not called again in the second instance. What's happening?
UPDATE 2:
#codeMagic asked for more information about the app and activity A.
This app lets its user review certain items and comment on them. Activity A is started when the app is launched. If the user's session isn't valid any more, a Login activity is started. Once the user logs in, activity A becomes active again. A only has a "No items to review" message and a "Try now" button.
When the user logs in, the server starts sending push notifications whenever a new item is available for review. When the app gets the notification, activity A accesses the server and gets the next item to review. The item is shown in activity B. Once the review is submitted to the server, activity B finishes and activity A is again the top activity.
The server knows when a user is reviewing an item (because activity A fetched it), and doesn't send push notifications until the review is submitted - meaning a notification can't come if the user isn't logged in or if the user is viewing activity B.
While I agree there is a subtle race condition here, it is not causing the problem I'm seeing - in testing I am 100% positive there's no race condition - the push notification is only sent after Activity A becomes active again.
The solution was to add a launchMode='singleTask' to the activity in AndroidManifest.xml . As a result, instead of a new activity, onNewIntent of the same activity instance is called.
You can use one of several Intent Flags. FLAG_ACTIVITY_REORDER_TO_FRONT being one of them. This will bring the Activity to the front of the stack if it is already in the stack and if not then it will create a new instance. I believe you will still need FLAG_ACTIVITY_NEW_TASK if you aren't calling it from an Activity
Intent.FLAG_ACTIVITY_CLEAR_TOP should also work. But this will clear any other Activities on the stack. It just depends on what other functionality you need. Look through the Intent Flags and see which of these will work best for you
There are multiple scenarios when this could happen. One of them can be handled this way. Please see my answer here: https://stackoverflow.com/a/44117025/2959575
Ok, two notes on this :
You can register a broadcast receiver via the manifest so it is independent of any parts of your app. and use a Singleton pattern (keep a static reference to your activity somewhere in your app) that way you can check if their is an activity viewing or not and process accordingly.
// your activity A
#Override
public void onCreate(Bundle bundle) {
super.onCreate(bundle);
myActivityReference = this;
}
public void onPause() {
super.onPause();
if (isFinishing()) {
myActivityReference = null;
}
}
or you can keep everything as it is and use activity lunching modes flags in your manifest such as singleTop, singleInstance ... etc. take a look here android activity lunch modes

Categories

Resources