Closing Android Activity opened from Forms.Context.StartActivity - xamarin

I am working on facebook authentication in a Xamarin forms app and want to use "native" login on each device.
The Facebook SDK (by Xamarin) is not designed for forms since it requires passing in an Android activity that implements some specific interfaces.
However; I was able to get the UI to display using a custom page renderer and then in that renderer calling StartActitivty with an activity that uses the exact implementation described in the Facebook SDK getting started. https://components.xamarin.com/view/facebookandroid
So far everything works perfect. The android app starts, xamarin forms kicks in, the custom page renderer is loaded the login android activity starts and the user logs in with facebook and we get to the console.writeline below.
So, how do I dismiss this intent or otherwise get back to xamarin forms?
Do I:
Dismiss this intent? - if so then what?
Inject something to "reset" the main page?
Other?
public void OnCompleted (Xamarin.Facebook.Model.IGraphUser user, Response response)
{
//TODO: show user details with welcome and button that takes them to main app.
//TODO: switch back to xam forms from here on out.
//TODO: figure out how to change the `main` activity to xam forms.
// 'Me' request callback
if (user != null) {
//How do I get back to Xamarin forms from here?
Console.WriteLine ("GOT USER: " + user.Name);
} else {
Console.WriteLine ("Failed to get 'me'!");
}
}

You should call Finish();
Anyway, if you want to see exactly how I did it, you can check it here:
https://github.com/IdoTene/XamarinFormsNativeFacebook

Related

How to hide TimePicker and DatePicker on lifecycle events in Xamarin Forms

I'm running into an issue on android where our TimePicker and DatePicker stay visible when we navigate OnPause(). We need to redirect our users back to the login screen when they background the application, but if the TimePicker or DatePicker is active when they do this it stays on the screen. It appears above the login screen and pressing cancel or ok crashes the app.
We are hooking into the native android lifecycle events (not just using Xamarins built in hooks) and we redirect OnResume(). I've tested this in a barebones app though and it still happens OnPause().
Here is our TimePicker causing us the issue:
<TimePicker x:Name="VitalTimePicker" HorizontalOptions="Fill" VerticalOptions="Fill" IsVisible="false" PropertyChanged="OnTimePickerPropertyChanged"/>
And here is an example of changing screens on a lifecycle event:
protected override void OnSleep()
{
App.Current.MainPage = new NavigationPage(new NotesPage());
}
Any ideas? I was thinking of clearing the Pickers but I can't seem to find how to do that
Edit
Just to add a little more context
The Application class (app.xaml.cs) has lifecycle hooks that we use to catch when our users background the app. In here we call MainPage = new NavigationPage(new LoginPage()); which takes the app back to the login page.
I've added
protected override void OnDisappearing()
{
VitalTimePicker.Unfocus();
VitalDatePicker.Unfocus();
}
to the view i'm working from and it seems to be called when we background the application, but for some reason the TimePicker is staying on the screen when our login page pops up again.
You can programmatically close DatePickers and TimePickers using the method Unfocus(). I'd recommend closing them before you call the next page, as I don't know if they will be able to be referenced and closed after the other screen has been initialized.
Create a method that calls VitalTimePicker.Unfocus() and the same for any other picker you have, and call this method before changing to login screen and you should be good to go.

App Center in-app updates not showing up in Xamarin Android app

I'm attempting to configure AppCenter.Distribute for in-app updates within my Xamarin Android app. Here is the very basic setup code, which I have in my main launcher activity's OnCreate method (AFTER the base.OnCreate call):
AppCenter.Start (Resources.GetString (Resource.String.appcenter_app_secret), typeof (Analytics), typeof (Crashes), typeof (Distribute));
I was able to get the in-app updates to supposedly initialize. When I first install and open the app, it shows a browser window for one second that says "In-app updates enabled! Returning to app in 1...", then it redirects back to my app. Unfortunately, when I then bump the version name and code and distribute a new build, I don't get a dialog within the app prompting me to update to the new version.
I even tried handling the Distribute.ReleaseAvailable action and showing a custom dialog, and that action isn't invoked either:
Distribute.ReleaseAvailable = OnReleaseAvailable;// Called before AppCenter.Start
private bool OnReleaseAvailable(ReleaseDetails releaseDetails)
{
// Show custom dialog.
Droid.ApplicationContext.Activity.CustomDialogBuilder().Show(new NotificationArgs
{
Title = "New update available!",
Message = "A new version of RPR Mobile, {0} ({1}) is available. Release notes: {2}"
.WithFormat(releaseDetails.ShortVersion, releaseDetails.Version, releaseDetails.ReleaseNotes),
PositiveButtonText = "Update",
PositiveAction = () =>
{
// Notify SDK that user selected to update...
Distribute.NotifyUpdateAction(UpdateAction.Update);
},
HideNegativeButton = releaseDetails.MandatoryUpdate,
NegativeButtonText = "Postpone Update",
NegativeAction = () =>
{
// Notify SDK that user selected to postpone (for 1 day)...
// Note that this method call is ignored by the SDK if the update is mandatory.
Distribute.NotifyUpdateAction(UpdateAction.Postpone);
}
});
// Return true if you are using your own dialog, false otherwise.
return true;
}
I'm wondering what I'm missing. Some questions that may or may not be relevant...
Does it matter whether the AppCenter.Start code executes before or after the base.OnCreate call?
Does it matter whether the activity that AppCenter.Start is called from is running or finished? Because in our case, the main launcher is just a splash screen that closes after a couple seconds.
Is the App Center SDK supposed to poll every few seconds for an update? Or does it check only when opening and closing activities?
It turns out that you have to close and relaunch your app for it to check for new updates. The documentation could be more clear on this...

Xamarin Forms - How to open specific page after clicking on notification when the app is closed?

I'm actually working on a Xamarin Forms application that need push notifications. I use the Plugin.PushNotification plugin.
When the app is running in the foreground or is sleeping (OnSleep), I have no problem to open a specific page when I click on a notification that I receive. But I was wondering how can I do that when the app is closed. Thanks!
I finally found the answer by myself and I want to share it in case someone needs it.
Nota bene: according to the official documentation of the plugin, it's Xam.Plugin.PushNotification that is deprecated. I use the new version of this plugin, Plugin.PushNotification which uses FCM for Android and APS for iOS.
There is no significant differences to open a notif when the app is running, is sleeping or is closed. Just add the next callback method in the OnCreate method (MyProject.Droid > MainApplication > OnCreate) and FinishedLaunching method (MyProject.iOS > AppDelegate > FinishedLaunching):
CrossPushNotification.Current.OnNotificationOpened += (s, p) =>
{
// manage your notification here with p.Data
App.NotifManager.ManageNotif(p.Data);
};
Common part
App.xaml.cs
// Static fields
// *************************************
public static NotifManager NotifManager;
// Constructor
// *************************************
public App()
{
...
NotifManager = new NotifManager();
...
}
NotifManager.cs
public class NotifManager
{
// Methods
// *************************************
public void ManageNotif(IDictionary<string, object> data)
{
// 1) switch between the different data[key] you have in your project and parse the data you need
// 2) pass data to the view with a MessagingCenter or an event
}
}
Unfortunately there is no succinct answer for either platform. Generally speaking, you need to tell the OS what to do when it starts the app as a result of the push notification. On both platforms, you should also consider what API level you are targeting, otherwise it won't work or even crash the app.
On iOS, you will need to implement this method in AppDelegate appropriately: FinishedLaunching(UIApplication application, NSDictionary launchOptions). The launchOptions will have the payload from the push notification for you to determine what to do with it (e.g. what page to open). For more information on iOS, Xamarin's documentation is a good place to start.
Android has a more complicated topology in terms of more drastic differences between API levels, whether you are using GCM/FCM, as well as requiring more code components. However, to answer the question directly, you will need to handle this in OnCreate(Bundle savedInstanceState) of your main Activity. If you are using Firebase, the push notification payload is available in Intent.Extras. Again, Xamarin's documentation has a good walkthrough.
Finally, note that the Plugin.PushNotification library you are using has been deprecated. I suggest you either change your library and/or your implementation soon. Part of the reason that library has been deprecated is because Google has deprecated the underlying Google Cloud Messaging (GCM) service, which will be decommissioned on April 11, 2019.

How to Close/Exit current instance of Xamarin.Forms app while loading a new one

We are facing a strange issue. Not sure if it is design flaw of the existing application. Your help/suggestion is appreciated.
We have a Xamarin.forms app. Targeted both for iOS and Android.
Problem is coming mainly in Android app.
Application flow:
once we logout from the application, app opens an logout activity and delete user info and other data.
opens a new activity for login which contains client SSO implementation
on successful login, app is setting user info and fetch data from web service.
then it calls LoadApplication method so that flow comes back in main application
Now if user perform logout/login several times, its opening a new application instance by calling LoadApplication method and then displaying home screen
So when user is tapping back button in home page, app is not closing and displays previous instance of same application.
User need to press back button several times (depending how many time user perform logout-login).
Is there any goodway to stop this?
Can we close current instance of the application before LoadApplication being called?
Stuck for a long time.
I'd try to avoid to call LoadApplication more then once. You should control the navigation stack.
Given you are on the LogoutPage
remove all views via PopToRootAsync
show the LoginPage
await Navigation.PopToRootAsync(false);
await Navigation.PushAsync(new LoginPage(), true);
This blog post may be worth a reading: https://jfarrell.net/2015/01/22/understanding-xamarin-forms-navigation/
Kindly try this.
https://stackoverflow.com/a/36885388/1941942
[Activity (NoHistory = true)]
public class LoginActivity : Activity { }
The saving instance error has gone a while after I implement it on MainActivity.

How can i use NavigationServices in Application_Activated windows phone 7?

im developin an app for wp7 that it holds pictures and notes with password login. But when app running if user press windows button app is running at background and if user press back button it resumes without asking password again.
i tried to Navigate when app activated but i couldnt manage it in Application_Activated method. is there a way to do that? Or could you advice me sth else that solve my problem.
ty.
here is my code im using to navigate,
(Application.Current.RootVisual as PhoneApplicationFrame).Navigate(new Uri("/MainPage.xaml", UriKind.Relative));
I got around this issue by using UserControls on the MainPage, showing one if the user had not yet logged in and the other if they had, I set these controls up to show/hide based on certains states in the MainPage and then bind that to the MainViewModel:
private void Application_Activated(object sender, ActivatedEventArgs e)
{
// Ensure that application state is restored appropriately
....your code here to load stuff...
App.ViewModel.MainPageState = "ShowThemTheLogin";
}
}

Resources