毕加索:如何检查单例是否已设置 [英] Picasso: How to check if singleton is already set
问题描述
我正在使用Picasso
来处理我的应用程序中的图像加载.在我的Activity
中我
I am using Picasso
for handling image loading in my app. In my Activity
I do
@Override
protected void onCreate(Bundle savedInstanceState)
{
super.onCreate(savedInstanceState);
setContentView(R.layout.loading_screen);
setupPicasso();
// ...
}
private void setupPicasso()
{
Cache diskCache = new Cache(getDir(CacheConstants.DISK_CACHE_DIRECTORY, Context.MODE_PRIVATE), CacheConstants.DISK_CACHE_SIZE);
OkHttpClient okHttpClient = new OkHttpClient();
okHttpClient.setCache(diskCache);
Picasso picasso = new Picasso.Builder(this)
.memoryCache(new LruCache(CacheConstants.MEMORY_CACHE_SIZE))
.downloader(new OkHttpDownloader(okHttpClient))
.build();
picasso.setIndicatorsEnabled(true); // For debugging
Picasso.setSingletonInstance(picasso);
}
这在第一次启动应用程序时以及通过按主屏幕按钮暂停应用程序时效果很好.但是,通过按后退"按钮关闭应用程序,然后重新打开应用程序时,出现以下错误:
This works fine when first starting the app and when pausing the app by pressing the home button. However, when closing the app by pressing the back button, followed by reopening the app, I get the following error:
java.lang.IllegalStateException: Singleton instance already exists.
之所以会发生这种情况,是因为Picasso
不允许重置全局单例实例.解决此问题的最佳方法是什么?是否可以检查单例是否已设置?还是我需要在我的Activity
中保留一个成员变量,并检查该变量是否为null
?任何对此的最佳实践都将受到赞赏.
This happens because Picasso
does not allow resetting the global singleton instance. What is the best way to work around this? Is it possible to check if the singleton is already set? Or do I need to keep a member variable in my Activity
and check if that is null
? Any best practice on this is appreciated.
推荐答案
在自己的Application
中从onCreate
调用setupPicasso()
方法
班级.扩展 Application
类并覆盖onCreate
.然后,您需要使用完全限定的应用程序类,将name
属性添加到清单的<application>
部分.
Call your setupPicasso()
method from onCreate
in your own Application
class. Extend the Application
class and override onCreate
. Then you will need to add the name
attribute to your manifest's <application>
section with the fully qualified application class.
package my.package
public class MyApplication extends Application {
@Override
public void onCreate() {
super.onCreate();
setupPicasso();
}
然后在您的清单中
<application
android:name="my.package.MyApplication"
... >
这篇关于毕加索:如何检查单例是否已设置的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!