Search code examples
javaandroidandroid-fragmentsbroadcastreceiverfragment

Cannot resolve Method getSupportFragmentManager() or ((FragmentActivity)activity)getSupportFragmentManager()


I want to launch a fragment from my BroadcastReciver class because I want to launch a fragment on a mobile home screen just like a dialog. using that user will stop or snooze the alarm. how to achieve that?

I tried all solutions available at StackOverflow but I can't get an answer. every time I am getting an error.

Cannot resolve Method getSupportFragmentManager()

or

Cannot resolve FragmentActivity in ((FragmentActivity)activity)getSupportFragmentManager()

any suggestion or question? comment below


Solution

  • You need an Activity to host that Fragment. A Fragment cannot be possible without a hosting Activity. At first, create an Activity (eg. AlarmActivity) with transparent background (You can achieve with themes) which has a FragmentContainerView to host your fragment. When you receive broadcast in your BroadcastReceiver, start this activity:

    Intent intent = new Intent(context, AlarmActivity.class);
    intent.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK); // This is required
    context.startActivity(intent);