当我按下通知栏中的通知时,我试图打开一个片段。我的应用程序结构是:
- 具有导航抽屉式菜单的基本Activity
- 和一些从菜单中打开的片段
当我按下通知时,Activity重新打开,但不在指示的片段中,并且在LogCat中,来自指示片段的数据看起来打开并加载,但不使用UI。
通知代码:
NotificationCompat.Builder mBuilder =
new NotificationCompat.Builder(this);
mBuilder.setContentTitle("Comanda Noua");
mBuilder.setContentText("S-a introdus o comanda noua");
mBuilder.setTicker("Comanda noua!");
mBuilder.setSmallIcon(R.drawable.calculator_icon);
mBuilder.setAutoCancel(true);//inchide notificare dupa ce s-a dat click pe ea
//creste numar notificare
mBuilder.setNumber(++numMessages);
// cream un intent
Intent resultIntent = new Intent(this, MainActivity.class);
//am setat actiune pentru a deschide fragmentul corespunzator notificartii la apasare
resultIntent.setAction("Action1");
TaskStackBuilder stackBuilder = TaskStackBuilder.create(this);
stackBuilder.addParentStack(MainActivity.class);
// Adds the Intent that starts the Activity to the top of the stack
stackBuilder.addNextIntent(resultIntent);
PendingIntent resultPendingIntent =
stackBuilder.getPendingIntent(0, PendingIntent.FLAG_UPDATE_CURRENT);
mBuilder.setContentIntent(resultPendingIntent);
mNotificationManager =(NotificationManager) getSystemService(Context.NOTIFICATION_SERVICE);
// notificationID allows you to update the notification later on.
mNotificationManager.notify(notificationID, mBuilder.build());
按下通知时打开片段的代码:
Intent intent = getIntent();
try{
String action = intent.getAction();
// Log.d("action:",action);
if(action.equals("Action1")){
//Log.d("deschidem agenda:",action);
AgendaFragment fragment = new AgendaFragment();
FragmentTransaction transaction = getFragmentManager()
.beginTransaction();
transaction.replace(R.id.frame_container, fragment)
.setTransition(FragmentTransaction.TRANSIT_FRAGMENT_OPEN)
.addToBackStack(null).commit();
}else{
Log.d("eroare", "Intent was null");
}
}catch(Exception e){
Log.e("eroare", "Problem consuming action from intent", e);
}
为什么活动打开而片段没有?
2条答案
按热度按时间zzoitvuj1#
尝试下面的代码,这是更简单的显示通知的方式:
lp0sw83n2#
TRY与广播
在通知类中,您必须发送Broadcast这是默认方法
在基本活动中,仅创建广播接收器
在创建BaseActivityResigner广播接收器时
必须添加intentFilter
并且您必须在销毁基本活动时取消注册
@Override protected void onDestroy() { unregisterReceiver(receiver); super.onDestroy(); }