我正在开发一个在主要活动中运行3个标签(片段)的android项目。我想在通知选项卡中打开从解析发送的通知,而不是打开主要活动。已经阅读了与此相关的所有答案,但没有奏效。这是我的代码如下。 这是接收通知的代码
Intent launchActivity = new Intent(context, MainActivity.class);
launchActivity.setAction("op_notify");
PendingIntent pi = PendingIntent.getActivity(context, 0, launchActivity, 0);
NotificationCompat.InboxStyle inboxStyle = new NotificationCompat.InboxStyle();
Notification noti = new NotificationCompat.Builder(context)
.setContentTitle(title)
.setContentText(message)
.setSmallIcon(R.drawable.ic_push)
.setStyle(inboxStyle)
.setLargeIcon(icon)
.setContentIntent(pi)
.setSound(RingtoneManager.getDefaultUri(RingtoneManager.TYPE_NOTIFICATION))
.setAutoCancel(true)
.build();
NotificationManager nm = (NotificationManager)context.getSystemService(Context.NOTIFICATION_SERVICE);
nm.notify(0, noti);
MainActivity中的代码
protected void onCreate(Bundle savedInstanceState) {
Intent intent = getIntent();
String action = intent.getAction();
if(action!=null)
{
Log.e("Received action",action);
FragmentManager fragmentManager = getSupportFragmentManager();
FragmentTransaction fragmentTransaction = fragmentManager.beginTransaction();
Shownotifications shownotifications = new Shownotifications();
fragmentTransaction.replace(R.id.pager, shownotifications);
}
super.onCreate(savedInstanceState);
setContentView(R.layout.main);
toolbar = (Toolbar) findViewById(R.id.toolbar);
setSupportActionBar(toolbar);
FragmentManager manager = getSupportFragmentManager();
viewPager = (ViewPager) findViewById(R.id.pager);
tabLayout= (SlidingTabLayout) findViewById(R.id.tabs);
viewPager.setAdapter(new PagerAdapter(manager));
tabLayout.setDistributeEvenly(true);
tabLayout.setCustomTabColorizer(new SlidingTabLayout.TabColorizer() {
@Override
public int getIndicatorColor(int position) {
return getResources().getColor(R.color.tabsScrollColor);
}
});
tabLayout.setViewPager(viewPager);
}
@Override
public boolean onCreateOptionsMenu(Menu menu) {
// Inflate the menu; this adds items to the action bar if it is present.
getMenuInflater().inflate(R.menu.menu_main, menu);
return true;
}
@Override
public boolean onOptionsItemSelected(MenuItem item) {
int id = item.getItemId();
//noinspection SimplifiableIfStatement
if (id == R.id.action_settings) {
return true;
}
return super.onOptionsItemSelected(item);
}
class PagerAdapter extends FragmentStatePagerAdapter
{
public PagerAdapter(FragmentManager fm)
{
super(fm);
}
@Override
public Fragment getItem(int i)
{
Fragment frag=null;
if(i==0)
{
frag = new PostsView();
}
if(i==1)
{
frag= new Favourite();
}
if(i==2)
{
frag= new Shownotifications();
}
return frag;
}
@Override
public int getCount() {
return 3;
}
@Override
public CharSequence getPageTitle(int position) {
if(position==0){
return "Posts";
}
if(position==1){
return "Favourite";
}
if(position==2){
return "Notifications";
}
return "Default";
}
}