android - 如何从通知中打开 fragment

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

我正在编写一个消息传递应用程序,该应用程序使用各种 View 的 fragment 。在打开的第一个 fragment 上,用户会看到一个联系人列表,当他点击一个联系人时,另一个 fragment 会打开以显示现有的聊天窗口。此 fragment 以以下代码开头:

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");

我还有一个通知,用于通知用户收到的消息。但是,当用户点击通知时,我无法启动预期的聊天 fragment 。我的通知代码如下:

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 intent = getIntent();
try {
  String action = intent.getAction().toUpperCase();
}catch(Exception e){
  Log.e(TAG, "Problem consuming action from intent", e);              
}

但是,getIntent() 似乎总是返回空值。

我做错了什么?谢谢!

最佳答案

我认为这行是不正确的:

intent.setAction("Action1");

你应该使用下面的语句来表明 Intent 的意愿(即打开一个 Activity ):

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

要识别 Intent 来源,您可以使用类似的 putExtra 函数

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

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

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

在您的 Activity 中获取“来源”

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

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

关于android - 如何从通知中打开 fragment ,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/22832971/

相关文章:

android - 限制 google api 项目的 OAuth 2.0 客户端 ID

android - 使用 java 1.8 运行 UI AUTOMATOR 时出错

android - 如何从 Android 上的 Intent 中获取额外数据?

android - AsyncTask、Fragments、Views 和 Backstacks

android - 音乐播放器 :App crashes

android - 在 Android 上使用网络

java - 如何在android中从json数据在ImageView上显示图像

java - 无法使用 ShareIntent 从 Android 中的可绘制文件夹发送图像文件?

android,RESULT_OK 强制 Intent.ACTION_VIEW

android - 使用 fragment xml 文件中的 View