Whats the best way to initialize classes in the activity lifecycle

Hello,
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

Answers

  • 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)
    {
        fm.BeginTransaction()
          .Add(retainFragment, tag)
          .CommitAllowingStateLoss();
    }
    

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

    public override void OnCreate(Bundle savedInstanceState)
    {
        base.OnCreate(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.