我需要在应用程序的不同屏幕中检索用户位置。我编写了代码来获取屏幕活动中的位置,但是,现在我想在另一个屏幕活动中获取该位置。有什么办法可以避免再次编写相同的代码吗?
// variables
// These variables will be repeated
LocationProvider locationProvider;
double latitude;
double longitude;
private String userPostcode;
// ===============
@Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
// This code will be repeated
locationProvider = new LocationProvider(getActivity());
latitude = locationProvider.getLatitude();
longitude = locationProvider.getLongitude();
if (isNetworkAvailable(getContext())) {
getPostcode();
} else {
Toast.makeText(getActivity(), "Internet or GPS is not available. To get the best location one or both of these must be on",
Toast.LENGTH_LONG).show();
}
// =============
return inflater.inflate(R.layout.fragment_location, container, false);
}
// These two methods will be repeated
private void getPostcode(){
Geocoder geoCoder = new Geocoder(getActivity().getApplicationContext(), Locale.getDefault());
List<Address> address = null;
if (geoCoder != null) {
try {
address = geoCoder.getFromLocation(latitude, longitude, 1);
} catch (IOException e1) {
e1.printStackTrace();
}
if (address.size() > 0) {
userPostcode = address.get(0).getPostalCode();
}
}
}
private boolean isNetworkAvailable(final Context context) {
final ConnectivityManager connectivityManager = ((ConnectivityManager) context.getSystemService(Context.CONNECTIVITY_SERVICE));
return connectivityManager.getActiveNetworkInfo() != null && connectivityManager.getActiveNetworkInfo().isConnected();
}
// ====================
如果可以避免重复,请有人给我看/告诉我如何才能做到。我是android新手,可能错过了一些愚蠢的东西。
答案 0 :(得分:1)
在单独的类中添加getPostcode()。您可以按照以下方式修改它。
yum install php-cli
Loaded plugins: fastestmirror, security
Loading mirror speeds from cached hostfile
* base: centos.syn.co.il
* epel: mirror.nonstop.co.il
* extras: centos.syn.co.il
* rpmforge: apt.sw.be
* updates: centos.syn.co.il
Setting up Install Process
Resolving Dependencies
--> Running transaction check
---> Package php-cli.x86_64 0:5.3.3-48.el6_8 will be installed
--> Processing Dependency: php-common(x86-64) = 5.3.3-48.el6_8 for package: php-cli-5.3.3-48.el6_8.x86_64
--> Running transaction check
---> Package php-common.x86_64 0:5.3.3-48.el6_8 will be installed
--> Finished Dependency Resolution
Dependencies Resolved
=============================================================================================================================
Package Arch Version Repository Size
=============================================================================================================================
Installing:
php-cli x86_64 5.3.3-48.el6_8 updates 2.2 M
Installing for dependencies:
php-common x86_64 5.3.3-48.el6_8 updates 530 k
Transaction Summary
=============================================================================================================================
Install 2 Package(s)
Total download size: 2.7 M
Installed size: 9.1 M
Is this ok [y/N]:
片段/活动中的执行此操作
public class Utils {
public static String getPostcode(Context context, double lat, double lng){
Geocoder geoCoder = new Geocoder(context, Locale.getDefault());
List<Address> address = null;
if (geoCoder != null) {
try {
address = geoCoder.getFromLocation(lat, lng, 1);
} catch (IOException e1) {
e1.printStackTrace();
}
if (address.size() > 0) {
return address.get(0).getPostalCode();
}
}
return null;
}
public static boolean isNetworkAvailable(final Context context) {
final ConnectivityManager connectivityManager = ((ConnectivityManager) context.getSystemService(Context.CONNECTIVITY_SERVICE));
return connectivityManager.getActiveNetworkInfo() != null && connectivityManager.getActiveNetworkInfo().isConnected();
}
}
如果在片段中,将if(Utils.isNetworkAvailable(this)) {
String postCode = Utils.getPostcode(this, yourLat, yourLng);
}
更改为this
。
答案 1 :(得分:1)
只是简单地返回一些值的方法,你需要经常重复使用它们并且不依赖于任何对象或状态,你可以使它们保持静态。
创建某种实用类。例如
public class Utils {
public static boolean isNetworkAvailable(final Context context) {
final ConnectivityManager connectivityManager = ((ConnectivityManager) context.getSystemService(Context.CONNECTIVITY_SERVICE));
return connectivityManager.getActiveNetworkInfo() != null && connectivityManager.getActiveNetworkInfo().isConnected();
}
public static String getPostCode(Activity activity) {
...
}
}
然后你可以在任何你喜欢的地方重复使用它。
boolean isNetworkAvailable = Utils.isNetworkAvailable(context);
答案 2 :(得分:1)
创建新的类文件并将这些函数放在该类文件中
private String getPostcode(Activity activity, Double latitude, Double longitude) {
String userPostcode = null;
Geocoder geoCoder = new Geocoder(activity.getApplicationContext(), Locale.getDefault());
List<Address> address = null;
if (geoCoder != null) {
try {
address = geoCoder.getFromLocation(latitude, longitude, 1);
} catch (IOException e1) {
e1.printStackTrace();
}
if (address.size() > 0) {
userPostcode = address.get(0).getPostalCode();
}
}
return userPostcode;
}
private static boolean isNetworkAvailable(final Context context) {
final ConnectivityManager connectivityManager = ((ConnectivityManager) context.getSystemService(Context.CONNECTIVITY_SERVICE));
return connectivityManager.getActiveNetworkInfo() != null && connectivityManager.getActiveNetworkInfo().isConnected();
}
要访问这些功能,请创建该类的对象并调用这些功能
答案 3 :(得分:1)
您可以创建一个实用程序类来执行所需的所有位置工作。将活动/上下文对象作为构造函数参数传递给实用程序类。然后使用类方法来获得你想要的东西。查看实用程序类的以下代码:
public class LocationHelper {
private double mLatitude;
private double mLongitude;
private Context mContext;
private LocationProvider mLocationProvider;
// Dont know if you need Activity or Context object.
// Pass whatever as per requirement
public LocationHelper(Context context) {
this.mContext = context;
initLocation();
}
// Set the latitude and longitude here.
// You can get the latitude and longitude using
// getter methods.
private void initLocation() {
mLocationProvider = new LocationProvider(mContext);
mLatitude = mLocationProvider.getLatitude();
mLongitude = mLocationProvider.getLongitude();
}
public double getLatitude() {
return mLatitude;
}
public double getLongitude() {
return mLongitude;
}
// Get the post code as a string. Empty if failed to get any.
public String getPostcode(){
String userPostcode = "";
Geocoder geoCoder = new Geocoder(mContext, Locale.getDefault());
List<Address> address = null;
//It is a redundant check since it will always be true
if (geoCoder != null) {
try {
address = geoCoder.getFromLocation(mLatitude, mLongitude, 1);
} catch (IOException e1) {
e1.printStackTrace();
}
// Also make sure to put a null check to avoid NullPointerException
if (address != null && address.size() > 0) {
userPostcode = address.get(0).getPostalCode();
}
}
return userPostcode;
}
//To check if device is offline/online.
public boolean isNetworkAvailable() {
final ConnectivityManager connectivityManager = ((ConnectivityManager) mContext.getSystemService(Context.CONNECTIVITY_SERVICE));
return connectivityManager.getActiveNetworkInfo() != null && connectivityManager.getActiveNetworkInfo().isConnected();
}
}
答案 4 :(得分:0)
是的,折射器进入一个单独的类。或者找到一种方法将数据从一个活动转移到另一个活动。 (putExtra(),Singleton,DataBase,SharedPreferences等)