【问题标题】:Starting activity from a service and updating its content, is there a way?从服务开始活动并更新其内容,有没有办法?
【发布时间】:2014-07-26 08:34:01
【问题描述】:

我正在使用一项服务来接收来自罐头的一些 GCM 消息。我将消息放入 extra 并将其传递给我要启动的类,然后在对话框中显示消息。

但是下次我收到一条消息时它应该更新之前打开的意图的内容,问题是我得到一个异常并且我的应用程序崩溃了,eclipse 迫使我使用“FLAG_ACTIVITY_NEW_TASK”来解决崩溃,但是这样我的“PendingIntent.FLAG_UPDATE_CURRENT”将被忽略。

如何更新之前打开的意图?在我看来,创建第三个活动并将数据传递回来和堡垒似乎是一个糟糕的解决方案。

服务类:

      ...

private void sendNotification(String msg, Bundle extras)
        {
        mNotificationManager = (NotificationManager) this.getSystemService(Context.NOTIFICATION_SERVICE);

        Intent intent = new Intent(this, DriverDetails.class);
        intent.setFlags(Intent.FLAG_ACTIVITY_SINGLE_TOP | Intent.FLAG_ACTIVITY_NEW_TASK);
        // If this is a notification type message include the data from the message 
        // with the intent
        if (extras != null)
        {
            intent.putExtras(extras);
            intent.putExtra("message", msg);
            intent.setAction("com.myGcm.NOTIFICATION");
            startActivity(intent);
        }
        PendingIntent contentIntent = PendingIntent.getActivity(this, 0, intent,
            PendingIntent.FLAG_UPDATE_CURRENT);

        NotificationCompat.Builder mBuilder = 
            new NotificationCompat.Builder(this)
            .setSmallIcon(R.drawable.ic_stat_cloud)
            .setContentTitle("GCM Notification")
            .setStyle(new NotificationCompat.BigTextStyle().bigText(msg))
            .setContentText(msg)
            .setTicker(msg)
            .setAutoCancel(true)
            .setSound(Settings.System.DEFAULT_NOTIFICATION_URI);

        mBuilder.setContentIntent(contentIntent);
        mNotificationManager.notify(NOTIFICATION_ID, mBuilder.build());
        }

...

【问题讨论】:

  • 您想在活动中更新什么样的内容?
  • @Aashish - 我需要以列表的形式向最终用户显示所有传入的消息。
  • 从服务中触发通知。将该通知设置为在单击时启动活动。

标签: android android-intent android-activity notifications google-cloud-messaging


【解决方案1】:

您的解决方案应该是LocalBroadcastManager。这非常简单:只需在您的 Activity 的onResume 中注册一个侦听器,然后从其他任何地方使用 Update-Information 触发一个 Intent。我附上了两个链接,应该可以指导你;)

how to use LocalBroadcastManager?

http://www.intertech.com/Blog/using-localbroadcastmanager-in-service-to-activity-communications/

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2019-07-28
    • 1970-01-01
    • 2018-05-20
    • 1970-01-01
    • 1970-01-01
    • 2021-09-11
    相关资源
    最近更新 更多