如何从通知中打开片段

时间:2014-04-03 09:12:53

标签: android android-intent android-fragments android-notifications

我正在编写一个消息传递应用程序,它利用各种视图的片段。在打开的第一个片段上,向用户显示联系人列表,当他点击联系人时,将打开另一个片段以显示现有的聊天窗口。该片段使用以下代码启动:

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()似乎总是返回一个空值。

我做错了什么?谢谢!

1 个答案:

答案 0 :(得分:0)

我认为这条线不正确:

intent.setAction("Action1");

您应该使用以下声明来表明意图的意愿(即开展活动):

intent.setAction(Intent.ACTION_MAIN);
intent.addCategory(Intent.CATEGORY_LAUNCHER);

要识别意图来源,您可以像这样使用putExtra函数

intent.putExtra("origin", "incoming_message__open_chat")

不要忘记在您的活动中启用接收:

<activity android:name="MainActivity">
    <!-- This activity is the main entry, should appear in app launcher -->
    <intent-filter>
        <action android:name="android.intent.action.MAIN" />
        <category android:name="android.intent.category.LAUNCHER" />
    </intent-filter>
</activity>

在您的活动中获取&#34;来源&#34;

protected void onCreate(Bundle savedInstanceState)
{
   ...
   String origin = savedInstanceState.getString("origin");
   ...
}

我没有完整的解决方案,但你应该深入这个方向并阅读: http://developer.android.com/guide/components/intents-filters.html