【问题标题】:How can I display data obtained with a service in an Activity?如何在 Activity 中显示通过服务获取的数据?
【发布时间】:2017-04-09 18:55:26
【问题描述】:

我有一项服务可以从网络下载一些数据,但是当我尝试将其传递给活动以将其显示给用户时,我收到以下错误:

E/JavaBinder: !!! Binder 交易失败!!!

// This gets populated in the server based on information from a server.
byte[] downloadedData; 
// Instantiated downloadedData from server connection, code removed for brevity. 

// Try to start activity with downloaded data.
Intent i = new Intent(this, MainActivity.class);
i.putExtra("DATA", downloadedData);
i.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
startActivity(i);

【问题讨论】:

  • 为什么你的服务试图启动一个活动?你不知道用户在前台做什么。如果碰巧在前台,请使用事件总线(例如 greenrobot 的 EventBus)将这些数据提供给您的 UI。如果该事件被忽略,服务可以将数据保存到文件并引发Notification 以让用户知道数据已准备好。一般来说,“失败的 BINDER TRANSACTION”是因为你的 Intent 太大了。
  • 感谢@CommonsWare 的快速回复,但是如果我的应用程序不能使用事件总线怎么办?
  • "如果我的应用不能使用事件总线怎么办?" ——你为什么不能?事件总线为成千上万的开发人员工作。
  • 再次感谢@CommonsWare 的回复。我无法使用事件总线,因为我的 UI 和服务在不同的进程上运行。
  • 然后把它们放在同一个进程中。或者,让活动在前台绑定到服务,提供一个回调对象,您可以使用该对象将结果发回。如果活动未绑定,请提出Notification。请注意,即使使用绑定,您也可能需要缩小结果,或将它们保存到磁盘中,以便活动可以将它们加载到自己的进程中。

标签: java android android-activity android-service


【解决方案1】:

试试

1.在您的活动中注册自定义广播接收器

context.registerReceiver (myBroadcastReceiver, new IntentFilter ("CUSTOM_ACTION"));
private final BroadcastReceiver myBroadcastReceiver = new BroadcastReceiver () {

    @Override
    public void onReceive (Context context, Intent intent) {

        //Do something
    }
};

2.从您的服务发送广播

Intent intent = new Intent ("CUSTOM_ACTION");
intent.putExtra("DATA", downloadedData);
context.sendBroadcast (intent)

【讨论】:

  • 感谢您的回答,但是我遇到了同样的问题,我得到“FAILED BINDER TRANSACTION”。
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2021-07-21
  • 2016-10-30
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多