问题
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