【发布时间】:2014-04-03 09:12:52
【问题描述】:
我正在编写一个消息应用程序,该应用程序将片段用于各种视图。在打开的第一个片段上,向用户显示了联系人列表,当他单击联系人时,另一个片段打开以显示现有的聊天窗口。该片段以以下代码开头:
FragmentManager fragmentManager = getFragmentManager();
msgChat msgChatFragment = new msgChat();
Bundle bundle = new Bundle();
bundle.putString("userSelected", manageContact.getName());
msgChatFragment.setArguments(bundle);
fragmentManager.beginTransaction().replace(R.id.content_frame, msgChatFragment).addToBackStack(null).commit();
getActivity().setTitle("Message Chat");
我还有一个通知来通知用户收到的消息。但是,当用户点击通知时,我无法启动预期的聊天片段。我的通知代码如下:
Intent intent = new Intent(context, MainActivity.class);
String notificationMessage = "My notification message";
intent.setAction("Action1");
intent.setFlags(Intent.FLAG_ACTIVITY_SINGLE_TOP);
intent.addCategory(Intent.CATEGORY_LAUNCHER);
PendingIntent pIntent = PendingIntent.getActivity(context, 0, intent, PendingIntent.FLAG_UPDATE_CURRENT);
NotificationCompat.Builder noti = new NotificationCompat.Builder(
context).setContentTitle("My App")
.setContentText(notificationMessage)
.setSmallIcon(R.drawable.ic_stat_notify)
.setContentIntent(pIntent).setAutoCancel(true)
.setDefaults(Notification.DEFAULT_ALL);
notificationManager.notify(notifyId, noti.build());
在我的 MainActivity 的 onResume() 中,我有以下代码来捕捉意图:
Intent intent = getIntent();
try {
String action = intent.getAction().toUpperCase();
}catch(Exception e){
Log.e(TAG, "Problem consuming action from intent", e);
}
然而,getIntent() 似乎总是返回一个空值。
我做错了什么?谢谢!
【问题讨论】:
-
您可以在您的 Intent 中添加额外的信息,该信息会在按下通知时触发。当您的应用程序收到此额外信息时,只需对其做出反应,不要通过聊天加载您的联系人。
-
您好,我将如何输入用户名等额外信息,应用程序将如何处理这些额外信息?
-
ChatFragment 需要哪些信息?还是一个独立的 ChatFragment?
-
我意识到点击通知实际上并没有做任何事情。我认为它把我带到了联系人片段,因为当我点击通知时我已经在那里了。无论如何,根据片段的打开方式,它似乎需要用户名。
-
好吧,您可以将任何您想要的信息添加到单击通知时触发的 Intent。是否要包含用户名是您的决定。这也可以保存在首选项中。
标签: android android-intent android-fragments android-notifications