问题描述
我有2 activites(一个ListView和1与图形页面)。这两项活动都刷新按钮获取位置,然后下载一些数据从互联网上。我有重复的code的位置,并在两个活动的数据读取。
I have 2 activites (one with listview and 1 with mapview). Both activities have refresh button that fetches location and then downloads some data from the internet.I have duplicate code for location and data fetch in both activities.
如何有这样的code只是1的地方,并能够从任何活动打电话吗?我可以把它的应用对象?
How to have this code just in 1 place and to be able to call it from any activity? Can i put it in Application object?
推荐答案
创建一个类,例如GPSGetter这使从GPS获得的坐标,通过createInstance建立()该类别的方法然后实例,在你的主要的onCreate方法活动。然后定义在类中的getInstance()方法。
Create a class for example GPSGetter which keeps getting the coordinates from the GPS, Then instantiate via createInstance() method of that class, in the onCreate method of your main activity. Then define a getInstance() method in that class.
例如
class GPSGetter {
GPSGetter obj;
//constructor
private GPSGetter(){
//do some stuff here
}
public GPSGetter createInstance(){
if(obj == null)
obj = new GPSGetter();
}
public getGPSGetter(){
return obj;
}
在这种方式,你可以从两个您的活动类的getInstance调用,不需要担心重复,也这将使创建类的肯定只有一个对象。
In this manner you can call getInstance from both of your Activity classes and do not need to worry about duplication, also this will make sure only one object of class is created.
这篇关于如何避免重复code在每一个活动获取位置和数据?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!