简体   繁体   中英

How can I launch fragment in broadcast receiver

How can I use broadcast receiver to start/lunch fragment for example : if I need to start/luanch activity , I can use intent :

public void onReceive(final Context context, Intent intent) {

    this.context = context;
    this.intent = intent;

    try {
        Bundle bundle = intent.getExtras();

        int messageID = bundle.getInt("id");

        intent = new Intent(context, GetAlarm.class);

        intent.putExtra("id",messageID);

        intent.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
        context.startActivity(intent);

    } catch (Exception e) {
        Toast.makeText(context, "There was an error ", Toast.LENGTH_SHORT)
                .show();
        e.printStackTrace();
    }
}

but I don't know how about fragment

You must luanch intent and putextera and sendactivity . Then you can launch fragment from activity.

Fragment is a part of Activity . Without Activity you cannot launch a separate Fragment . You can launch an Activity with Fragment .

One way is to create BroadcastReceiver inner class in Activity to launch Fragment .

Does this work? Put this in your Broadcast Receiver:

activityIntent = new Intent(context, MainActivity.class);
activityIntent.putExtra("fragment", "fragment2");
activityIntent.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
context.startActivity(activityIntent);

and beneath the code you use to set your fragment pager adapter :

Bundle bundle = getIntent().getExtras();
if (bundle != null) {
    if (bundle.getString("fragment") != null) {
        /*Log.w(getClass().toString(), bundle.getString("fragment"));*/
        viewPager.setCurrentItem(2);
    }
}

This code is usually below something like this:

        final ViewPager viewPager = (ViewPager) findViewById(R.id.pager);
        final PagerAdapter adapter = new FragmentPagerAdapter
                (getSupportFragmentManager(), tabLayout.getTabCount());
        viewPager.setAdapter(adapter);
        viewPager.addOnPageChangeListener(new TabLayout.TabLayoutOnPageChangeListener(tabLayout));
        tabLayout.setOnTabSelectedListener(new TabLayout.OnTabSelectedListener() {
            @Override
            public void onTabSelected(TabLayout.Tab tab) {
                viewPager.setCurrentItem(tab.getPosition());
            }

            @Override
            public void onTabUnselected(TabLayout.Tab tab) {

            }

            @Override
            public void onTabReselected(TabLayout.Tab tab) {

            }

        });

Just make sure it's beneath where you set your adapter, and not just your viewpager, or else you won't be able to navigate to any fragments via the viewpager.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM