BroadcastReceiver、Service 和 Activity 是否共享 Application 对象?

Do BroadcastReceiver, Service, and Activity share Application object?

我有以下组件:

这些组件在什么情况下共享同一个Application对象?

为什么有时 Activity 可以绑定到 Service 而在其他时候 ServiceonBind() 不被调用而 Activity 接收null IBinderonSuccess()???

涉及的部分太多,现在分享代码。基于讨论,当我们有具体的想法时,我可以分享相关部分。

您的问题的简短回答是 ActivityServiceBroadcastReceiver 对象确实共享相同的 Application 对象

  • 只要他们运行所在的进程还活着.
  • 并且如果这些组件 运行 在 同一进程中 ,这是默认行为 .

有时,一个进程 运行ning 您的 Service 对象可能会被杀死,然后会产生一个新的进程。在这种情况下,内存由内核(而不是 Dalvik VM)回收,因此引用的 Application 对象与之前不同。

在 Android 应用程序的许多地方总是有一些需要的信息。例如,它可以是会话令牌。

有时建议的一种模式是将您的数据转储到 Application 对象中,以便在所有活动和其他组件(例如 Service 或 BroadcastReceiver)中可用。

class MyApplication extends Application {

    String name;

    String getName() {
        return name;
    }

    void setName(String name) {
        this.name = name;
    }
} 

App 组件可以像下面这样使用它:

class NameActivity extends Activity {

    void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.your_layout);

        // Just assume that in the real app we would really ask it!
        MyApplication app = (MyApplication) getApplication();
        app.setName("set name here");   

    }

}

所以,是的,应用程序组件,例如 Activity、服务 etc.share 相同的应用程序对象,只要它们 运行 所在的进程仍然存在。

其次,How come sometimes the Activity can bind to the Service while at other times onBind() of the Service is not called and the Activity receives a null

以上情况可能有不同的原因:
1. 具有 IBinder 实现的服务可能已被 OS
终止 2. 服务已创建,完全初始化可能需要一些时间。在此初始化完成之前,如果 Activity 等组件尝试绑定到它。