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.

Whats the best way to initialize classes in the activity lifecycle

I come from a Desktop background and I think my approach with my android app reflects that.
My App basically consists of one Mainactivity which holds amongst other things a tcp and bluetooth member. The problem is that every time the activity is recreated the members are reset and everything will be restarted. Is there a way to keep my tcp and bluetooth instances through the lifetime of my app and not my activity.

Best Answer


  • TedRogersTedRogers USMember ✭✭✭✭

    @BenHlzemer A bit more on the retained fragment.

    I derive all my UI fragments from a ContainerFragment class where T is my view model object.

    In the OnCreate() of ContainerFragment, I grab the retain tag from the savedInstanceState or created the retain tag using Guid.NewGuid().ToString();

    In OnViewCreated() of the ContainerFragment, I basically find or create my retained fragment. My retain fragment is RetainFragment where once again T is my view model.

    Find or create looks like this:

    public static RetainFragment<T> FindOrCreate(FragmentManager fm, string tag)
        RetainFragment<T> retainFragment = fm.FindFragmentByTag(tag) as RetainFragment<T>;
        if (retainFragment == null)
            retainFragment = new RetainFragment<T>();
            AddRetainedFragment(fm, tag, retainFragment);
        return retainFragment;
    static void AddRetainedFragment(FragmentManager fm, string tag, RetainFragment<T> retainFragment)
          .Add(retainFragment, tag)

    Also, key is the OnCreate() of the retained fragment:

    public override void OnCreate(Bundle savedInstanceState)
        RetainInstance = true;
  • BenHlzemerBenHlzemer USMember ✭✭

    Thank you for the answer. I think I will go with a singleton.

  • Hi @BenHlzemer

    Can you please post a sample working activity with the ContainerFragment and RetainFragment? This will be of great help. Thanks.

Sign In or Register to comment.