Android 是否在活动之间共享正在下载的arraylist?
我不熟悉安卓系统。在我的应用程序中,我有一个arrayList,它由从internet下载的对象填充。同时,我需要两个活动来访问arraylist,无论它是否已完成。我知道一些关于服务的事情,但我不知道如何编写代码。有什么帮助吗?我的代码如下所示:Android 是否在活动之间共享正在下载的arraylist?,android,service,Android,Service,我不熟悉安卓系统。在我的应用程序中,我有一个arrayList,它由从internet下载的对象填充。同时,我需要两个活动来访问arraylist,无论它是否已完成。我知道一些关于服务的事情,但我不知道如何编写代码。有什么帮助吗?我的代码如下所示: class A extends Service { void foo(){ //uses a loop to get elements from internet //then adds the elements to my
class A extends Service {
void foo(){
//uses a loop to get elements from internet
//then adds the elements to myArraylist in each loop
}
}
class B extends Activity {
//needs to have access to myArraylist asynchronously
}
class C extends Activity {
//needs to have access to myArraylist asynchronously
}
顺便说一下,对于任何活动,这两个活动不会同时调用myArrayList。我也不确定是否要使用服务。还有其他优惠吗?我认为最好的方法是使用
应用程序类:
创建类,将其称为MyApplication,并使用getter和setter创建ArrayList的字段成员,类似于:
class MyApplication extends Application {
ArrayList<Object> downloadedArray;
public void setDownloadedArray(ArrayList<Object> downloadedArray) {
this.downloadedArray = downloadedArray;
}
public ArrayList<Object> getDownloadedArray() {
return downloadedArray;
}
}
4现在,您可以通过以下方式从任何活动
访问此阵列:
ArrayList<Object> downloadedArray = ((MyApplication)getApplication()).getDownloadedArray();
ArrayList downloadedArray=((MyApplication)getApplication()).getDownloadedArray();
只是别忘了检查ArrayList
是否为空。请参见此处,否则SharedRef和arraylists都不关我的事!在那里没有发现有用的东西。不过谢谢!这似乎是一个很好的解决办法。但是我需要访问arraylist,即使在它被填充的时候(当元素被下载和添加的时候)。那么这可能吗?它是否会导致异步访问arrayList(同时多个访问)的结果出错?因此,在创建数组之后立即调用setter。关于异步,只要你不改变,就我所知,这不应该是一个问题。我试图在我的应用程序中实现你的解决方案,但存在一些主要缺陷。就像我需要下载过程一样,当用户在活动之间切换时,下载过程保持活动状态。所以这可能只是通过服务来完成的。因此,我提出了一个新问题。你可能很忙,但我想你能看看吗?
void foo(){
//uses a loop to get elements from internet
//then adds the elements to myArraylist in each loop
((MyApplication)getApplication()).setDownloadedArray(yourArray);
}
ArrayList<Object> downloadedArray = ((MyApplication)getApplication()).getDownloadedArray();