简体   繁体   English

为什么需要Context才能在Android中启动活动

[英]Why is Context needed to start activitites in Android

我了解什么是上下文,以及为什么需要它,但是为什么需要它来启动活动,为什么不能仅通过静态加载它们或调用其构造函数来完成它。

Why I cannot create and launch an activity like this: ActivityToLaunch activity = new ActivityToLaunch() 为什么我不能创建和启动这样的活动: ActivityToLaunch activity = new ActivityToLaunch()

Short answer: because you don't own an Activity . 简短答案:因为您没有Activity

That is, an Activity is a special component managed by the Android framework, but that allows you to add your application logic in predefined methods like onCreate() , onResume() , etc, etc, that are called later by the system. 也就是说, Activity是由Android框架管理的特殊组件,但是允许您将应用程序逻辑添加到预定义的方法中,例如onCreate()onResume()等,稍后由系统调用。

... ...

Imagine that you want to lunch a third party app from your application, for example the default file manager to allow the user to pick a file from the SD Card. 想象一下,您想在应用程序中使用第三方应用程序,例如默认的文件管理器,以允许用户从SD卡中选择文件。 Obviously you will not be able to do something like this: 显然,您将无法执行以下操作:

  FileManager manager = new FileManager()

because the FileManager classes (or any other third-party app's classes) are not accessible in your application code, so... hopefully you can see already a limitation with this approach. 因为FileManager类(或任何其他第三方应用程序的类)在您的应用程序代码中不可访问,所以...希望您已经看到这种方法的局限性。 That's why Android allows us to create an Intent where metadata about an Activity is given, pass it to startActivity(...) , and afterwards the system takes care of creating the started activity. 这就是Android允许我们创建一个Intent ,其中给出了有关Activity元数据,然后将其传递给startActivity(...) ,然后系统负责创建启动的Activity。

This was just one example, pretty sure there are other reasons why Android was designed like this. 这只是一个例子,可以肯定的是,Android的设计还有其他原因。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM