【问题标题】:How to pass an Activity in an Intent如何在 Intent 中传递 Activity
【发布时间】:2013-09-20 23:37:42
【问题描述】:

我正在尝试实现委托模式以通知 UI 异步操作的过程。所以我有一个这样的界面:

public interface UpdateLibraryDelegate {
    public void startDownloadingLibrary();
    public void endDownloadingLibrary();
    public void processingLibrary(int progress);
    public void endProcessingLibrary();
}

我有一个活动:

public class HomeActivity implements UpdateLibraryDelegate{

   protected void onCreate(Bundle savedInstanceState) {
         ...
          Intent libraryIntent = new Intent(this, MyService.class);
          /*Here is where the problem is*/
          libraryIntent.putExtra(UPDATE_LIBRARY_DELEGATE, this);
         ...
   }

  /*Methods of the interface*/
  ...
  /**/
}

问题显然是我无法按意图发送我的活动,因为它既不是可序列化的也不是可打包的。有没有办法用 Intent 发送活动?我想做的事情很愚蠢,有更合理的方法吗?我对 Android 完全陌生...

谢谢!

【问题讨论】:

  • 你不应该传递活动。有很多关于为什么这在网络上的材料,但无论如何,你不需要。但是,您还没有说 what 您要尝试做什么。您是否尝试将一些值从 HomeActivity 传递给 MyService?顺便说一句,您还必须扩展 Activity - public class HomeActivity extends Activity implements UpdateLibraryDelegate{

标签: android android-intent


【解决方案1】:

有没有办法用 Intent 发送活动?

没有。

我正在尝试做的事情很愚蠢,还有更合理的方法可以做到吗?

契约模式非常好,只是不适用于使用命令模式的活动服务通信。那是一种松耦合模式,与合约(你称之为委托)模式背道而驰。

此外,如果您将命令模式与服务一起使用,那么首先使用该服务的原因是该活动可以消失,而该服务会结束其部分工作。这就是这里使用松耦合的原因。

服务更典型的方法是使用消息传递:

  • LocalBroadcastManager
  • 第三方事件总线,如Square's Otto
  • Messenger

如果活动存在,则让服务引发活动可以订阅的事件。

如果该服务仅在活动期间存在,您可能希望重新考虑为什么首先提供该服务。如果服务有合法需求,您可以使用绑定模式 (bindService()),在这种情况下,您可以谨慎使用您的合约/委托模式。

【讨论】:

    【解决方案2】:

    您必须使用 AsyncTask 类来执行异步操作。

    观看here 了解课程使用情况。

    here 为例。

    【讨论】:

    • 我终于解决了这个问题,避免使用意图,而是使用 AsyncTask。
    猜你喜欢
    • 1970-01-01
    • 2014-09-14
    • 2023-03-14
    • 1970-01-01
    • 2015-10-25
    • 1970-01-01
    • 1970-01-01
    • 2017-08-01
    • 2011-03-18
    相关资源
    最近更新 更多