【问题标题】:Start a Fragment from a Service从服务启动片段
【发布时间】:2015-04-10 08:21:28
【问题描述】:

我的Activityhosts 3 个标签,每个标签都是一个Fragment
我还有一个Service,它定期查询数据库。根据查询的结果,我提出了一个Notification(来自Service)。

当我点击Notification 时,是否可以启动特定的片段?如果是,我该怎么做?

这是我目前在Service 课堂上所做的:

// When notification is clicked, go back to TabOperations Fragment
Intent i = new Intent(this, TabOperations.class);
PendingIntent pi = PendingIntent.getActivity(this, 0,  i,PendingIntent.FLAG_UPDATE_CURRENT); // Give the phone access to the app
notification.setContentIntent(pi);

// Issue notification
NotificationManager nm = (NotificationManager)getSystemService(NOTIFICATION_SERVICE);
nm.notify(UNIQUE_ID, notification.build());

当然,这是行不通的。

有什么建议吗?

【问题讨论】:

  • 不,您不能“启动片段”。片段不存在于活动之外。要解决您的问题,请启动具有 3 个选项卡的活动并传入一个意图参数,该参数告诉活动应导航到哪个选项卡。然后活动监听这个意图参数并对它做出反应。当然,你必须自己编写所有这些代码。
  • 查看 PendingIntent 文档,了解通知可以通知哪些 android 组件

标签: java android android-intent android-fragments android-service


【解决方案1】:

与其使用Service 发送Notification,不如使用不同的消息传递系统。例如,您可以利用观察者模式(或第三方库,如EventBus)将消息从服​​务发送到关心此类事件的活动。然后,Activity 可以使用该事件来启动并根据需要附加 Fragment。

【讨论】:

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