androidapp如何存储数据作为全局变量,在各个activity中调用?
展开全部
Android提供了一个类似于ServletContext的全局变量,叫Application。可以利用它存储一些全局变量!
示例:
import java.util.Collections;
import java.util.HashMap;
import java.util.Map;
import android.app.Application;
public class MyApplication extends Application {
private Map<String, Object> mData;
public Map<String, Object> getmData() {
return mData;
}
@Override
public void onCreate() {
super.onCreate();
mData = new HashMap<String, Object>();
//synchronized the map
mData = Collections.synchronizedMap(mData);
// then restore your map
}
public void onTerminate() {
super.onTerminate();
//save data of the map
}
}
然后在AndroidManifest里面配置<application>节点的属性
<application android:name=".MyApplication">
示例:
import java.util.Collections;
import java.util.HashMap;
import java.util.Map;
import android.app.Application;
public class MyApplication extends Application {
private Map<String, Object> mData;
public Map<String, Object> getmData() {
return mData;
}
@Override
public void onCreate() {
super.onCreate();
mData = new HashMap<String, Object>();
//synchronized the map
mData = Collections.synchronizedMap(mData);
// then restore your map
}
public void onTerminate() {
super.onTerminate();
//save data of the map
}
}
然后在AndroidManifest里面配置<application>节点的属性
<application android:name=".MyApplication">
推荐律师服务:
若未解决您的问题,请您详细描述您的问题,通过百度律临进行免费专业咨询