Forum Xamarin.Android
We are excited to announce that the Xamarin Forums are moving to the new Microsoft Q&A experience. Q&A is the home for technical questions and answers at across all products at Microsoft now including Xamarin!

We encourage you to head over to Microsoft Q&A for .NET for posting new questions and get involved today.

how to close previous activity from current activity in xamarin.android ?

After specific process finished , I want to close previous activity from current activity that is visible on my screen using xamarin.android

Tagged:

Answers

  • jezhjezh Member, Xamarin Team Xamurai

    A simple method is to use MessagingCenter.

    The steps is as follows:

    1.In your current activity,send message:

            mSendBtn.Click += delegate {
                Xamarin.Forms.MessagingCenter.Send<Object>(this, "Hi");
            };
    

    2.In your previous activity,subscribe to a message:

            Xamarin.Forms.MessagingCenter.Subscribe<object>(this, "Hi", (sender) =>
            {
                Log.Info("MainActivity", "receive message...");
    
                Finish();               
            });
    

    3.Unsubscribe from a message once you don't need to send message in your current activity,for example:

         protected override void OnDestroy()
        {
            base.OnDestroy();
    
            Xamarin.Forms.MessagingCenter.Unsubscribe<object>(this, "Hi");
        }
    
  • jezhjezh Member, Xamarin Team Xamurai

    Another method is to use Handler:

    1.define MyHandler which implement Handler.ICallback

      public class MyHandler : Java.Lang.Object, Handler.ICallback
            {
                Activity activity;
                public MyHandler(Activity context) {
                    activity = context;
                }
    
                public bool HandleMessage(Message msg)
                {
                    // add your code
                    activity.Finish();
    
                    return true;
                }
            }
    

    2.In your previous activity:

        public static Activity context;
    

    and init value for it in method OnCreate

      context = this;
    

    3.In your current activity

    private Handler handler = new Handler(Looper.MainLooper, new MyHandler( PreviousActivity.context));
    
     handler.SendMessage(new Message());
    
  • jezhjezh Member, Xamarin Team Xamurai

    Hi @GASRON , have you resolved your question?

    If my reply is useful for you,could you please mark it as answered? Thanks in advance. :)

Sign In or Register to comment.