Android 中的全局初始化
我正在编写一些作为 jar 文件分发的库代码,开发人员需要在使用前使用应用程序 ID 进行初始化。初始化只是一个函数调用,就像
MyLibrary.initialize("16ea53b");
棘手的事情是我不确定如何指示开发人员进行此初始化调用。起初,我认为主活动中的单个静态初始化程序块将是最简单的方法。问题是用户可以通过某些其他活动或意图进入应用程序,并且不会加载主活动。是否有一种通用方法可以确保无论应用程序如何启动,一行代码都会在应用程序启动时运行?
初始化调用是幂等的,所以我可以告诉人们在每个可以使用它的地方进行这个初始化调用,但这会很麻烦。
I'm writing some library code distributed as a jar file that developers will need to initialize with an application id before using. Initialization is just a function call, like
MyLibrary.initialize("16ea53b");
The tricky thing is that I am not sure how to instruct developers to make this initialization call. At first I thought a single static initializer block in the main activity would be the easiest way to do it. The problem is a user could enter the application through some other activity or intent, and the main activity would not be loaded. Is there a general way to ensure that a line of code is run at the application's startup regardless of how the application was started?
The initialize call is idempotent so I could just tell people to make this initialization call in every place it could be used, but that would be bothersome.
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(2)
一种简单的方法是在初始化库代码时在 SharedPrefences 中保存某些内容。然后,无论您认为重要,您都可以检查该值,如果存在则继续,或者提示初始化或任何内容(错误消息等)。这也将使您的开发人员不必初始化多次。
请务必向开发人员提供 API 来重置此值。
另外,此处是 Joshua Bloch 发表的关于 API 设计的精彩演讲,可能会对您有所帮助。
One easy way is to save something in SharedPrefences when your library code is initialized. And then, wherever you deem important, you can check for this value, and continue if it exists or prompt for initialization or anything (error messages etc). This will also allow your developers to not have to initialize more than once.
Be sure to provide the developers an API to reset this value.
Also, here is a good talk on API design that may help you, by Joshua Bloch.
这听起来像是一个可以通过扩展创建一个扩展应用程序的类并将其放置在那里来解决的问题,该类对于整个应用程序是全局的。
This sounds like a problem that can be resolved by extending creating a class that extends Application and placing it there, which is global for the entire Application.