您的申请应该是单身人士.它避免了与共享数据或模型相关的许多其他问题.
在manifest.xml中:
<application android:icon="@drawable/icon"
android:label="@string/app_name" android:debuggable="false"
android:name="<class of your application see below>"
android:launchMode="singleTop">
..... all activities/services/receivers/etc... as usual
</application>
Run Code Online (Sandbox Code Playgroud)
而你的android:name引用了这个类:
public class MyApp extends Application {
//singleton, but use onCreate more than constructor to build shared resources.
....
}//class
Run Code Online (Sandbox Code Playgroud)
然后,从任何活动中,您可以通过执行以下操作来检索您的单例以获取共享资源:
((MyApp)getApplicationContext()).getSharedResources()....
Run Code Online (Sandbox Code Playgroud)
要么
MyApp.getInstance().getSharedResources()....
Run Code Online (Sandbox Code Playgroud)
将单例作为应用程序是android中常用的设计模式,它对于处理设备轮换特别有用(因为它往往会破坏活动并重新创建它们),因为它提供了一个稳定的实体,可以在应用程序生命周期中持久存在.
| 归档时间: |
|
| 查看次数: |
1789 次 |
| 最近记录: |