【问题标题】:How to open a fragment from a notification如何从通知中打开片段
【发布时间】: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


【解决方案1】:

我认为这行不正确:

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>

在您的活动中获取“原点”

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

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

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2016-10-03
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多