gpt4 book ai didi

android - 如何从通知中打开 fragment

转载 作者:太空狗 更新时间:2023-10-29 15:05:01 24 4
gpt4 key购买 nike

我正在编写一个消息传递应用程序,该应用程序使用各种 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/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com