How can I launch fragment in broadcast receiver

无人久伴 提交于 2019-11-28 11:09:15

问题


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


回答1:


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




回答2:


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.




回答3:


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.



来源:https://stackoverflow.com/questions/22223298/how-can-i-launch-fragment-in-broadcast-receiver

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!