Click here to Skip to main content
15,879,326 members
Please Sign up or sign in to vote.
1.00/5 (1 vote)
See more:
I try use method OnBackPressed but it is when i click button back from mobile app, it is call back my page splash screen

My application flow like this :
Splash Screen -> Language -> Main Menu

I want when clicked button back from mobile app its like this application flow
Language -> Close App

And i show alert dialog when user click button back in page langugage it is close app

What I have tried:

It is my coding:

Language.xaml.cs
public partial class Language : ContentPage
    {

        private ApiInterface api;

        public static Action BackPressed;

        private bool AcceptBack;

        public Bahasa()
        {
            this.BindingContext = new BahasaViewModel();
            InitializeComponent();

            api = RestService.For<ApiInterface>("http://192.168.0.186/webservice/webservice.asmx");

        }

        [Obsolete]
        private async void btn_lang(object sender, EventArgs e)
        {

            var deviceName = DeviceInfo.Name;
            var deviceType = DeviceInfo.DeviceType.ToString();
            var deviceModel = DeviceInfo.Model;
            var deviceManufacturer = DeviceInfo.Manufacturer;
            var devicePlatform = DeviceInfo.Platform.ToString();
            var deviceOs = DeviceInfo.Version.ToString();
            

            String date = DateTime.Now.ToString();


            Data_Device dtDevice = new Data_MimoDevice();
            dtDevice.Device_name = deviceName;
            dtDevice.Device_type = deviceType;
            dtDevice.Model = deviceModel;
            dtDevice.Manufacturer = deviceManufacturer;
            dtDevice.Platform = devicePlatform;
            dtDevice.Os = deviceOs;
            dtMimoDevice.First_accessed = date;

            DeviceIdQuery devicequery = new DeviceIdQuery(new Device(dtMimoDevice.Id));

            String jsonOfDevice = devicequery.id;

            var deviceQr = await api.CheckIfDeviceImeiExists(devicequery);

            if (deviceQr.isSuccess)
            {
                await Navigation.PushAsync(new Login());
            }
            else
            {
                var respDevice = await api.AddNewDevice(new DeviceQuery(dtMimoDevice));
                if (respDevice.isSuccess)
                {
                    await Navigation.PushAsync(new Login());
                }
            }
  
        }

        private void Button_Clicked(object sender, EventArgs e)
        {
            Navigation.PushAsync(new SettingPage());
        }

        protected override bool OnBackButtonPressed()
        {
            if (AcceptBack)
                return false;

            PromptForExit();
            return true;
        }

        private async void PromptForExit()
        {
            if (await DisplayAlert("", "Are you sure to exit?", "Yes", "No"))
            {
                AcceptBack = true;
                BackPressed();
            }

        }
    }


MainActivity.cs
[Activity(Label = "AppTest", Icon = "@mipmap/icon", Theme = "@style/MainTheme", MainLauncher = true, ConfigurationChanges = ConfigChanges.ScreenSize | ConfigChanges.Orientation)]
    public class MainActivity : global::Xamarin.Forms.Platform.Android.FormsAppCompatActivity
    {
        protected override void OnCreate(Bundle savedInstanceState)
        {
            Language.BackPressed = OnBackPressed;

            //NoHistory = true;

            TabLayoutResource = Resource.Layout.Tabbar;
            ToolbarResource = Resource.Layout.Toolbar;

            base.OnCreate(savedInstanceState);

            Xamarin.Essentials.Platform.Init(this, savedInstanceState);
            global::Xamarin.Forms.Forms.Init(this, savedInstanceState);
            global::Xamarin.Auth.Presenters.XamarinAndroid.AuthenticationConfiguration.Init(this,savedInstanceState);
            UserDialogs.Init(this);
            LoadApplication(new App());
        }
        public override void OnRequestPermissionsResult(int requestCode, string[] permissions, [GeneratedEnum] Android.Content.PM.Permission[] grantResults)
        {
            Xamarin.Essentials.Platform.OnRequestPermissionsResult(requestCode, permissions, grantResults);

            base.OnRequestPermissionsResult(requestCode, permissions, grantResults);
        }
    }
Posted
Updated 22-Jan-20 0:13am
Comments
[no name] 17-Jan-20 23:56pm    
Don't see any code for "OnBackPressed".

Language.BackPressed = OnBackPressed;
Rey21 18-Jan-20 0:13am    
OnBackPressed is already in class Language.xml.cs after private void Button_Clicked(object sender, EventArgs e)
[no name] 18-Jan-20 12:32pm    
protected override bool OnBackButtonPressed()

We're supposed to assume they're the same? Well, you not exiting because your looping. Sloppiness hurts.
Rey21 20-Jan-20 2:11am    
could you help me how to fix it ?

1 solution

Your code is perfect for closing app. It might be becaause of thread can you try this
 if (AcceptBack)
        return false;
Device.BeginInvokeOnMainThread(async () =>{  PromptForExit();});
  return true;


In OnBackButtonPressed.
 
Share this answer
 
Comments
Member 12794918 12-Jun-20 7:50am    
thanks

This content, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)



CodeProject, 20 Bay Street, 11th Floor Toronto, Ontario, Canada M5J 2N8 +1 (416) 849-8900