在Android中使用GPS获取当前位置 [英] Get current location using GPS in Android
问题描述
我在,我想利用GPS用户的当前位置的一个项目现在的工作。我看过很多教程,并试着写了code。在code在模拟器中运行良好。每次我发送邮件使用DDMS的latittude和经度,仿真器会检测到。主要的问题是,它不与实际设备的工作。虽然,我试图在其上的设备有互联网接入和GPS是开放的。我已经添加了必要的权限清单文件。
公共类MainActivity延伸活动{TextView的纬度;
TextView的LON;
@覆盖
保护无效的onCreate(捆绑savedInstanceState){
super.onCreate(savedInstanceState);
的setContentView(R.layout.activity_main);
纬度=(的TextView)findViewById(R.id.textView2);
LON =(的TextView)findViewById(R.id.textView4);
LM的LocationManager =(的LocationManager)getSystemService(Context.LOCATION_SERVICE);
LocationListener的LL =新myLocationListener();
lm.requestLocationUpdates(LocationManager.GPS_PROVIDER,0,0,LL);
}@覆盖
公共布尔onCreateOptionsMenu(菜单菜单){
//充气菜单;如果是present这增加了项目操作栏。
。getMenuInflater()膨胀(R.menu.main,菜单);
返回true;
}
类myLocationListener实现LocationListener的{@覆盖
公共无效onLocationChanged(地点){
// TODO自动生成方法存根
如果(位置!= NULL){
双PLAT = location.getLatitude();
双PLONG = location.getLongitude();
lat.setText(Double.toString(高原));
lon.setText(Double.toString(PLONG));
}
}@覆盖
公共无效onProviderDisabled(字符串提供商){
// TODO自动生成方法存根}@覆盖
公共无效onProviderEnabled(字符串提供商){
// TODO自动生成方法存根}@覆盖
公共无效onStatusChanged(字符串提供商,INT地位,捆绑演员){
// TODO自动生成方法存根} }
}
在清单文件的权限
<使用许可权的android:NAME =android.permission.ACCESS_FINE_LOCATION/>
<使用许可权的android:NAME =android.permission.ACCESS_COARSE_LOCATION/>
<使用许可权的android:NAME =android.permission.INTERNET对/>
我需要帮助,请。
GPSTracker GPS =新GPSTracker(本);
双纬度= gps.getLatitude();
双经度= gps.getLongitude();
使用GPS服务:
进口android.app.AlertDialog;
进口android.app.Service;
进口android.content.Context;
进口android.content.DialogInterface;
进口android.content.Intent;
进口android.location.Location;
进口android.location.LocationListener;
进口android.location.LocationManager;
进口android.os.Bundle;
进口android.os.IBinder;
进口android.provider.Settings;
进口android.util.Log;公共类GPSTracker扩展服务实现LocationListener的{ 私人最终上下文mContext; //标志GPS状态
布尔isGPSEnabled = FALSE; //标志网络状态
布尔isNetworkEnabled = FALSE; //标志GPS状态
布尔canGetLocation = FALSE; 地点位置; // 位置
双纬度; //纬度
双经度; //经度 //最小距离改变米的更新
私有静态最后长MIN_DISTANCE_CHANGE_FOR_UPDATES = 10; //10米 //毫秒更新之间的最短时间
私有静态最后长MIN_TIME_BW_UPDATES = 1000 * 60 * 1; // 1分钟 //声明一个位置管理
受保护的LocationManager的LocationManager; 公共GPSTracker(上下文的背景下){
this.mContext =背景;
的getLocation();
} 公共场所的getLocation(){
尝试{
的LocationManager =(的LocationManager)mContext
.getSystemService(LOCATION_SERVICE); //获取GPS状态
isGPSEnabled =的LocationManager
.isProviderEnabled(LocationManager.GPS_PROVIDER); //获取网络状态
isNetworkEnabled =的LocationManager
.isProviderEnabled(LocationManager.NETWORK_PROVIDER);
如果(isGPSEnabled&安培;!&安培;!isNetworkEnabled){
//没有启用网络供应商
}其他{
this.canGetLocation = TRUE;
如果(isNetworkEnabled){
locationManager.requestLocationUpdates(
LocationManager.NETWORK_PROVIDER,
MIN_TIME_BW_UPDATES,
MIN_DISTANCE_CHANGE_FOR_UPDATES,这一点);
Log.d(网络,网络);
如果(的LocationManager!= NULL){
位置= locationManager.getLastKnownLocation(LocationManager.NETWORK_PROVIDER);
如果(位置!= NULL){
纬度= location.getLatitude();
经度= location.getLongitude();
}
}
}
//如果GPS功能的获得纬度/长期使用GPS服务
如果(isGPSEnabled){
如果(位置== NULL){
locationManager.requestLocationUpdates(
LocationManager.GPS_PROVIDER,
MIN_TIME_BW_UPDATES,
MIN_DISTANCE_CHANGE_FOR_UPDATES,这一点);
Log.d(GPS已启用,GPS功能的);
如果(的LocationManager!= NULL){
位置=的LocationManager
.getLastKnownLocation(LocationManager.GPS_PROVIDER);
如果(位置!= NULL){
纬度= location.getLatitude();
经度= location.getLongitude();
}
}
}
}
} }赶上(例外五){
}
返回的位置;
} / **
*停止使用GPS监听器调用该函数将停止使用您的GPS
*应用程序。
* * /
公共无效stopUsingGPS(){
如果(的LocationManager!= NULL){
locationManager.removeUpdates(GPSTracker.this);
}
} / **
*函数来获取纬度
* * /
公共双getLatitude(){
如果(位置!= NULL){
纬度= location.getLatitude();
}
//返回纬度
返回纬度;
} / **
*函数来获取经度
* * /
公共双getLongitude(){
如果(位置!= NULL){
经度= location.getLongitude();
} //返回经度
返回经度;
} / **
*功能检查启用GPS / WIFI
*
* @返回布尔
* * /
公共布尔canGetLocation(){
返回this.canGetLocation;
} / **
*功能,以显示设置警告对话框在pressing设置按钮会
*劳克设置选项
* * /
公共无效showSettingsAlert(){
AlertDialog.Builder alertDialog =新AlertDialog.Builder(mContext); //设置DialogHelp标题
alertDialog.setTitle(GPS是设置); //设置DialogHelp留言
alertDialog
.setMessage(GPS未启用你想要去设置菜单?); //在pressing设置按钮
alertDialog.setPositiveButton(设置,
新DialogInterface.OnClickListener(){
公共无效的onClick(DialogInterface对话,诠释它){
意向意图=新意图(
Settings.ACTION_LOCATION_SOURCE_SETTINGS);
mContext.startActivity(意向);
}
}); //在pressing取消按钮
alertDialog.setNegativeButton(取消,
新DialogInterface.OnClickListener(){
公共无效的onClick(DialogInterface对话,诠释它){
dialog.cancel();
}
}); //显示警报信息
alertDialog.show();
} @覆盖
公共无效onLocationChanged(地点){
浮bestAccuracy = -1f;
如果(location.getAccuracy()!= 0.0
&功放;&安培; (location.getAccuracy()&下; bestAccuracy)|| bestAccuracy == -1f){
locationManager.removeUpdates(本);
}
bestAccuracy = location.getAccuracy();
} @覆盖
公共无效onProviderDisabled(字符串提供商){
} @覆盖
公共无效onProviderEnabled(字符串提供商){
} @覆盖
公共无效onStatusChanged(字符串提供商,INT地位,捆绑演员){
} @覆盖
公众的IBinder onBind(意向为arg0){
返回null;
} 公众持股量getAccurecy()
{
返回location.getAccuracy();
}}
I'm working now in a project which i want to get the current location of user using gps. I have read many tutorial and tried to write the code. The code works well in the emulator. Every time i send the latittude and longitude using DDMS, the emulator will detect that. The main problem is that it doesn't work with the real devices. Although, the devices that i tried on it has internet access and the GPS is open. I have added the required permissions to the manifest file.
public class MainActivity extends Activity {
TextView lat;
TextView lon;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
lat=(TextView)findViewById(R.id.textView2);
lon=(TextView)findViewById(R.id.textView4);
LocationManager lm=(LocationManager)getSystemService(Context.LOCATION_SERVICE);
LocationListener ll=new myLocationListener();
lm.requestLocationUpdates(LocationManager.GPS_PROVIDER,0,0, ll);
}
@Override
public boolean onCreateOptionsMenu(Menu menu) {
// Inflate the menu; this adds items to the action bar if it is present.
getMenuInflater().inflate(R.menu.main, menu);
return true;
}
class myLocationListener implements LocationListener{
@Override
public void onLocationChanged(Location location) {
// TODO Auto-generated method stub
if(location!=null){
double pLat=location.getLatitude();
double pLong=location.getLongitude();
lat.setText(Double.toString(pLat));
lon.setText(Double.toString(pLong));
}
}
@Override
public void onProviderDisabled(String provider) {
// TODO Auto-generated method stub
}
@Override
public void onProviderEnabled(String provider) {
// TODO Auto-generated method stub
}
@Override
public void onStatusChanged(String provider, int status, Bundle extras) {
// TODO Auto-generated method stub
}
}
}
the permission in manifest file
<uses-permission android:name="android.permission.ACCESS_FINE_LOCATION"/>
<uses-permission android:name="android.permission.ACCESS_COARSE_LOCATION"/>
<uses-permission android:name="android.permission.INTERNET"/>
I need a help please.
GPSTracker gps = new GPSTracker(this);
double latitude = gps.getLatitude();
double longitude = gps.getLongitude();
use this GPS service:
import android.app.AlertDialog;
import android.app.Service;
import android.content.Context;
import android.content.DialogInterface;
import android.content.Intent;
import android.location.Location;
import android.location.LocationListener;
import android.location.LocationManager;
import android.os.Bundle;
import android.os.IBinder;
import android.provider.Settings;
import android.util.Log;
public class GPSTracker extends Service implements LocationListener {
private final Context mContext;
// flag for GPS status
boolean isGPSEnabled = false;
// flag for network status
boolean isNetworkEnabled = false;
// flag for GPS status
boolean canGetLocation = false;
Location location; // location
double latitude; // latitude
double longitude; // longitude
// The minimum distance to change Updates in meters
private static final long MIN_DISTANCE_CHANGE_FOR_UPDATES = 10; // 10 meters
// The minimum time between updates in milliseconds
private static final long MIN_TIME_BW_UPDATES = 1000 * 60 * 1; // 1 minute
// Declaring a Location Manager
protected LocationManager locationManager;
public GPSTracker(Context context) {
this.mContext = context;
getLocation();
}
public Location getLocation() {
try {
locationManager = (LocationManager) mContext
.getSystemService(LOCATION_SERVICE);
// getting GPS status
isGPSEnabled = locationManager
.isProviderEnabled(LocationManager.GPS_PROVIDER);
// getting network status
isNetworkEnabled = locationManager
.isProviderEnabled(LocationManager.NETWORK_PROVIDER);
if (!isGPSEnabled && !isNetworkEnabled) {
// no network provider is enabled
} else {
this.canGetLocation = true;
if (isNetworkEnabled) {
locationManager.requestLocationUpdates(
LocationManager.NETWORK_PROVIDER,
MIN_TIME_BW_UPDATES,
MIN_DISTANCE_CHANGE_FOR_UPDATES, this);
Log.d("Network", "Network");
if (locationManager != null) {
location = locationManager.getLastKnownLocation(LocationManager.NETWORK_PROVIDER);
if (location != null) {
latitude = location.getLatitude();
longitude = location.getLongitude();
}
}
}
// if GPS Enabled get lat/long using GPS Services
if (isGPSEnabled) {
if (location == null) {
locationManager.requestLocationUpdates(
LocationManager.GPS_PROVIDER,
MIN_TIME_BW_UPDATES,
MIN_DISTANCE_CHANGE_FOR_UPDATES, this);
Log.d("GPS Enabled", "GPS Enabled");
if (locationManager != null) {
location = locationManager
.getLastKnownLocation(LocationManager.GPS_PROVIDER);
if (location != null) {
latitude = location.getLatitude();
longitude = location.getLongitude();
}
}
}
}
}
} catch (Exception e) {
}
return location;
}
/**
* Stop using GPS listener Calling this function will stop using GPS in your
* app.
* */
public void stopUsingGPS() {
if (locationManager != null) {
locationManager.removeUpdates(GPSTracker.this);
}
}
/**
* Function to get latitude
* */
public double getLatitude() {
if (location != null) {
latitude = location.getLatitude();
}
// return latitude
return latitude;
}
/**
* Function to get longitude
* */
public double getLongitude() {
if (location != null) {
longitude = location.getLongitude();
}
// return longitude
return longitude;
}
/**
* Function to check GPS/wifi enabled
*
* @return boolean
* */
public boolean canGetLocation() {
return this.canGetLocation;
}
/**
* Function to show settings alert dialog On pressing Settings button will
* lauch Settings Options
* */
public void showSettingsAlert() {
AlertDialog.Builder alertDialog = new AlertDialog.Builder(mContext);
// Setting DialogHelp Title
alertDialog.setTitle("GPS is settings");
// Setting DialogHelp Message
alertDialog
.setMessage("GPS is not enabled. Do you want to go to settings menu?");
// On pressing Settings button
alertDialog.setPositiveButton("Settings",
new DialogInterface.OnClickListener() {
public void onClick(DialogInterface dialog, int which) {
Intent intent = new Intent(
Settings.ACTION_LOCATION_SOURCE_SETTINGS);
mContext.startActivity(intent);
}
});
// on pressing cancel button
alertDialog.setNegativeButton("Cancel",
new DialogInterface.OnClickListener() {
public void onClick(DialogInterface dialog, int which) {
dialog.cancel();
}
});
// Showing Alert Message
alertDialog.show();
}
@Override
public void onLocationChanged(Location location) {
float bestAccuracy = -1f;
if (location.getAccuracy() != 0.0f
&& (location.getAccuracy() < bestAccuracy) || bestAccuracy == -1f) {
locationManager.removeUpdates(this);
}
bestAccuracy = location.getAccuracy();
}
@Override
public void onProviderDisabled(String provider) {
}
@Override
public void onProviderEnabled(String provider) {
}
@Override
public void onStatusChanged(String provider, int status, Bundle extras) {
}
@Override
public IBinder onBind(Intent arg0) {
return null;
}
public float getAccurecy()
{
return location.getAccuracy();
}
}
这篇关于在Android中使用GPS获取当前位置的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!