GPS coordinates (using location manager) get printed as null(GPS坐标(使用位置管理器)打印为空)
问题描述
OnCreateMethod,
OnCreateMethod,
LocationManager manager = (LocationManager) this.getSystemService(Context.LOCATION_SERVICE);
LocationListener listener = new LocationListener() {
@Override
public void onStatusChanged(String provider, int status, Bundle extras) {
// TODO Auto-generated method stub
}
@Override
public void onProviderEnabled(String provider) {
// TODO Auto-generated method stub
}
@Override
public void onProviderDisabled(String provider) {
// TODO Auto-generated method stub
}
@Override
public void onLocationChanged(Location location) {
// TODO Auto-generated method stub
coordinates = new GeoPoint((int)location.getLatitude(), (int)location.getLongitude()).toString();
}
};
manager.requestLocationUpdates(LocationManager.GPS_PROVIDER, 0, 0, listener);
}
当我尝试在 TextView 中显示坐标(setText)时,它显示null"
and when i try to show coordinates (setText) in a TextView, it says "null"
Android 清单,
Android Manifest,
<uses-permission android:name="android.permission.ACCESS_FINE_LOCATION" />
<uses-permission android:name="android.permission.ACCESS_COARSE_LOCATION"/>
即使我的 TextView 显示null",我也会在状态栏上收到一条通知,上面写着正在搜索 GPS"
Even though my TextView displays "null", i get a notification on my status bar which says "Searching for GPS"
推荐答案
这是我的方法:
这是因为 GPS 锁定等需要时间,而且您不想让主 UI 线程陷入困境.使用异步任务可以让您在后台抛出一个进程,并在方法有效执行后自动更新 UI 字段.
This is because GPS locking etc takes time and you don't want to bog down your main UI thread. Using a asynch task will enable you to throw a process in the background and auto update the UI field once the method has effectively executed.
这是一个代码片段:用于异步任务的后台执行部分
Here is a code snippet: For the do in background part of the Asynch task
protected String doInBackground(Location... params) {
/*
* Get a new geocoding service instance, set for localized addresses.
* This example uses android.location.Geocoder, but other geocoders that
* conform to address standards can also be used.
*/
// Show user progress bar
pd.show();
Geocoder geocoder = new Geocoder(mContext, Locale.getDefault());
// Get the current location from the input parameter list
Location location = params[0];
// Create a list to contain the result address
List<Address> addresses = null;
// Try to get an address for the current location. Catch IO or network
// problems.
try {
/*
* Call the synchronous getFromLocation() method with the latitude
* and longitude of the current location. Return at most 1 address.
*/
addresses = geocoder.getFromLocation(location.getLatitude(),
location.getLongitude(), 1);
// Catch network or other I/O problems.
} catch (IOException exception1) {
// Log an error and return an error message
Log.e(LocationUtils.APPTAG,
mContext.getString(R.string.IO_Exception_getFromLocation));
// print the stack trace
exception1.printStackTrace();
// Return an error message
return (mContext.getString(R.string.IO_Exception_getFromLocation));
// Catch incorrect latitude or longitude values
} catch (IllegalArgumentException exception2) {
// Construct a message containing the invalid arguments
String errorString = mContext.getString(
R.string.illegal_argument_exception,
location.getLatitude(), location.getLongitude());
// Log the error and print the stack trace
Log.e(LocationUtils.APPTAG, errorString);
exception2.printStackTrace();
//
return errorString;
}
// If the reverse geocode returned an address
if (addresses != null && addresses.size() > 0) {
// Get the first address
Address address = addresses.get(0);
// Format the first line of address
addressText = mContext.getString(
R.string.address_output_string,
// If there's a street address, add it
address.getMaxAddressLineIndex() > 0 ? address
.getAddressLine(0) : "",
// Locality is usually a city
address.getLocality(),
// The country of the address
address.getCountryName());
// Return the text
return addressText;
// If there aren't any addresses, post a message
} else {
return mContext.getString(R.string.no_address_found);
}
}
后台任务执行完毕后,您可以运行 onPostExecute 方法.
After the background task has finished executing you can run a onPostExecute method.
protected void onPostExecute(String result) {
delegate.processFinished(result);
// Update the EditText on the UI Thread.
ed.setText(result);
// Hide progress bar
pd.hide();
}
然后,您可以在相关的主类中调用 Aysch 任务并要求它显示结果.
public void getAddress(View v) {
// In Gingerbread and later, use Geocoder.isPresent() to see if a
// geocoder is available.
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.GINGERBREAD
&& !Geocoder.isPresent()) {
// No geocoder is present. Issue an error message
Toast.makeText(getActivity(), R.string.no_geocoder_available,
Toast.LENGTH_LONG).show();
return;
}
if (servicesConnected()) {
// Get the current location
Location currentLocation = mLocationClient.getLastLocation();
Lat = currentLocation.getLatitude();
Lng = currentLocation.getLongitude();
LatLng = Double.toString(Lat) + "," + Double.toString(Lng);
// Message to show results
Toast.makeText(getActivity(), LatLng, 0).show();
// Turn the indefinite activity indicator on
// Start the background task
GetAddressTask getAddressTask = new GetAddressTask(getActivity(),
locationAddress, pd);
getAddressTask.delegate = this;
getAddressTask.execute(currentLocation);
} else {
Toast.makeText(getActivity(), "servicesConnected() == false",
Toast.LENGTH_SHORT).show();
}
}
注意:这只是您需要的相关代码片段.如果您需要更详细的方法,请参阅我的 github.不要忘记投票并接受答案!
Note: this is only the relevant code snippets you need. Refer to my github if you require more detailed approach. Don't forget to upvote and accept answer!
我附上了几张我制作的应用程序的图片,以说明代码可以做什么,不用担心地图和其他东西.它仅显示我通过 Google 云服务器添加并与手机上拥有相同应用的朋友共享的事件.
I included a couple of pictures of an app I made to illustrate what the code can do don't worry about the map and stuff. It just shows events I have added and shared with friends who have the same app on their phone via a Google Cloud Server.
这篇关于GPS坐标(使用位置管理器)打印为空的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持编程学习网!
本文标题为:GPS坐标(使用位置管理器)打印为空
基础教程推荐
- 如何让对象对 Cocos2D 中的触摸做出反应? 2022-01-01
- 如何在没有IB的情况下将2个按钮添加到右侧的UINavigationbar? 2022-01-01
- android 应用程序已发布,但在 google play 中找不到 2022-01-01
- UIWebView 委托方法 shouldStartLoadWithRequest:在 WKWebView 中等效? 2022-01-01
- 在 gmail 中为 ios 应用程序检索朋友的朋友 2022-01-01
- Android:对话框关闭而不调用关闭 2022-01-01
- 当从同一个组件调用时,两个 IBAction 触发的顺序是什么? 2022-01-01
- Kivy Buildozer 无法构建 apk,命令失败:./distribute.sh -m “kivy"d 2022-01-01
- 如何在 iPhone 上显示来自 API 的 HTML 文本? 2022-01-01
- 如何在 UIImageView 中异步加载图像? 2022-01-01