在Android中获取位置更新

在Android中获取位置更新,android,location,updates,Android,Location,Updates,您好,我使用的代码如下: 这里我使用TextView显示一次位置坐标。 现在,如果位置不断更改,我如何在TextView中不断更新位置 我现在使用的代码:这是我的主要活动 package com.example.locationtests; import android.os.Bundle; import android.app.Activity; import android.view.Menu; import android.widget.TextView; public class M

您好,我使用的代码如下: 这里我使用TextView显示一次位置坐标。 现在,如果位置不断更改,我如何在TextView中不断更新位置

我现在使用的代码:这是我的主要活动

package com.example.locationtests;

import android.os.Bundle;
import android.app.Activity;
import android.view.Menu;
import android.widget.TextView;

public class MainActivity extends Activity {

@Override
protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.activity_main);
    GPSTracker mGPS = new GPSTracker(this);

    TextView text = (TextView) findViewById(R.id.texts);
    if(mGPS.canGetLocation ){
    mGPS.getLocation();
    text.setText("Lat"+mGPS.getLatitude()+"Lon"+mGPS.getLongitude());
    }else{
        text.setText("Unabletofind");
        System.out.println("Unable");
    }
}

@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;
}
}

This is the class im using for Tracking:

package com.example.locationtests;

import android.app.AlertDialog;
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.provider.Settings;
import android.util.Log;

public final class GPSTracker implements LocationListener {

    private final Context mContext;

    // flag for GPS status
    public 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 = 1; // 10 meters

    // The minimum time between updates in milliseconds
    private static final long MIN_TIME_BW_UPDATES = 1; // 1 minute

    // Declaring a Location Manager
    protected LocationManager locationManager;

    public GPSTracker(Context context) {
        this.mContext = context;
        getLocation();
    }

    /**
     * Function to get the user's current location
     * 
     * @return
     */
    public Location getLocation() {
        try {
            locationManager = (LocationManager) mContext
                    .getSystemService(Context.LOCATION_SERVICE);

            // getting GPS status
            isGPSEnabled = locationManager
                    .isProviderEnabled(LocationManager.GPS_PROVIDER);

            Log.v("isGPSEnabled", "=" + isGPSEnabled);

            // getting network status
            isNetworkEnabled = locationManager
                    .isProviderEnabled(LocationManager.NETWORK_PROVIDER);

            Log.v("isNetworkEnabled", "=" + isNetworkEnabled);

            if (isGPSEnabled == false && isNetworkEnabled == false) {
                // no network provider is enabled
            } else {
                this.canGetLocation = true;
                if (isNetworkEnabled) {
                    location=null;
                    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) {
                    location=null;
                    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) {
            e.printStackTrace();
        }

        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 Dialog Title
        alertDialog.setTitle("GPS is settings");

        // Setting Dialog 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) {
    }

    @Override
    public void onProviderDisabled(String provider) {
    }

    @Override
    public void onProviderEnabled(String provider) {
    }

    @Override
    public void onStatusChanged(String provider, int status, Bundle extras) {
    }

}
This is my AndroidManifest.xml

<?xml version="1.0" encoding="utf-8"?>
<manifest xmlns:android="http://schemas.android.com/apk/res/android"
    package="com.example.locationtests"
    android:versionCode="1"
    android:versionName="1.0" >
    <uses-permission android:name="android.permission.CAMERA" />
    <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"></uses-permission>
    <uses-permission android:name="android.permission.ACCESS_WIFI_STATE" /> 
    <uses-permission android:name="android.permission.ACCESS_NETWORK_STATE" />
    <uses-permission android:name="android.permission.VIBRATE" />
    <uses-feature android:name="android.hardware.camera" />
    <uses-feature android:name="android.hardware.location" android:required="true" />
    <uses-feature android:name="android.hardware.location.gps" android:required="false" />

    <uses-sdk
        android:minSdkVersion="8"
        android:targetSdkVersion="17" />

    <application
        android:allowBackup="true"
        android:icon="@drawable/ic_launcher"
        android:label="@string/app_name"
        android:theme="@style/AppTheme" >
        <activity
            android:name="com.example.locationtests.MainActivity"
            android:label="@string/app_name" >
            <intent-filter>
                <action android:name="android.intent.action.MAIN" />

                <category android:name="android.intent.category.LAUNCHER" />
            </intent-filter>
        </activity>
package com.example.locationtests;
导入android.os.Bundle;
导入android.app.Activity;
导入android.view.Menu;
导入android.widget.TextView;
公共类MainActivity扩展了活动{
@凌驾
创建时受保护的void(Bundle savedInstanceState){
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
GPSTracker mGPS=新的GPSTracker(本);
TextView text=(TextView)findViewById(R.id.text);
if(mGPS.canGetLocation){
mGPS.getLocation();
text.setText(“Lat”+mGPS.getLatitude()+“Lon”+mGPS.getLatitude());
}否则{
text.setText(“无法查找”);
System.out.println(“无法”);
}
}
@凌驾
公共布尔onCreateOptions菜单(菜单){
//为菜单充气;这会将项目添加到操作栏(如果存在)。
getMenuInflater().充气(R.menu.main,menu);
返回true;
}
}
这是im用于跟踪的类:
包com.example.locationtests;
导入android.app.AlertDialog;
导入android.content.Context;
导入android.content.DialogInterface;
导入android.content.Intent;
导入android.location.location;
导入android.location.LocationListener;
导入android.location.LocationManager;
导入android.os.Bundle;
导入android.provider.Settings;
导入android.util.Log;
公共最终类GPSTracker实现LocationListener{
私有最终上下文mContext;
//GPS状态标志
公共布尔值isGPSEnabled=false;
//网络状态标志
布尔值isNetworkEnabled=false;
//GPS状态标志
布尔值canGetLocation=false;
位置;//位置
双纬度;//纬度
双经度;//经度
//更改更新的最小距离(以米为单位)
私有静态最终长距离最小距离更改更新=1;//10米
//更新之间的最短时间(以毫秒为单位)
私有静态最终长MIN\u时间\u BW\u更新=1;//1分钟
//声明位置管理器
受保护的LocationManager LocationManager;
公共GPSTracker(上下文){
this.mContext=上下文;
getLocation();
}
/**
*函数获取用户的当前位置
* 
*@返回
*/
公共位置getLocation(){
试一试{
locationManager=(locationManager)mContext
.getSystemService(Context.LOCATION\u服务);
//获取GPS状态
isGPSEnabled=位置管理器
.isprovidenabled(LocationManager.GPS\U提供商);
Log.v(“isGPSEnabled”,“=”+isGPSEnabled);
//获取网络状态
isNetworkEnabled=locationManager
.isProviderEnabled(LocationManager.NETWORK_提供商);
Log.v(“isNetworkEnabled”,“=”+isNetworkEnabled);
if(isGPSEnabled==false&&isNetworkEnabled==false){
//未启用任何网络提供程序
}否则{
this.canGetLocation=true;
if(可联网){
位置=空;
locationManager.RequestLocationUpdate(
LocationManager.NETWORK\u提供程序,
最短时间更新,
最小距离\u更改\u用于更新,此);
Log.d(“网络”、“网络”);
如果(locationManager!=null){
位置=位置管理器
.getLastKnownLocation(LocationManager.网络提供商);
如果(位置!=null){
纬度=位置。getLatitude();
longitude=location.getLongitude();
}
}
}
//如果启用GPS,则使用GPS服务获取横向/纵向
如果(isGPSEnabled){
位置=空;
if(位置==null){
locationManager.RequestLocationUpdate(
LocationManager.GPS\u提供程序,
最短时间更新,
最小距离\u更改\u用于更新,此);
Log.d(“GPS启用”、“GPS启用”);
如果(locationManager!=null){
位置=位置管理器
.getLastKnownLocation(LocationManager.GPS\U提供商);
如果(位置!=null){
纬度=位置。getLatitude();
longitude=location.getLongitude();
}
}
}
}
}
}捕获(例外e){
e、 printStackTrace();
}
返回位置;
}
/**
*停止使用GPS侦听器调用此函数将停止在您的系统中使用GPS
*应用程序
* */
使用GPS()的公共无效停止{
如果(locationManager!=null){
locationManager.RemoveUpdate(GPSTracker.this);
}
}
/**
*获取纬度的函数
* */
公共双纬度(){
如果(位置!=null){
纬度=位置。getLatitude();
}
//返回纬度
返回纬度;
}
/**
*函数获取经度
* */
公共双getLongitude(){
如果(位置!=null){
longitude=location.getLongitude();
}
//返回经度
返回经度;
}
/**
*用于检查已启用GPS/wifi的功能
* 
*@返回布尔值
* */
locationManager.requestLocationUpdates(..., ..., ..., this);
@Override
public void onLocationChanged(Location location) {
}
GPSTracker mGPS = new GPSTracker(this);
public GPSTracker(Context context) {
    this.mContext = context;
@Override
public void onLocationChanged(Location location)
{
    TextView text = (TextView) ((Activity)mContext).findViewById(R.id.texts);
    text.setText("Lat"+location.getLatitude()+"Lon"+location.getLongitude());
}
@Override
public void onLocationChanged(Location location) {
Log.d(TAG, "GPS LocationChanged");
double lat = location.getLatitude();
double lng = location.getLongitude();
Log.d(TAG, "Received GPS request for " + String.valueOf(lat) + "," + String.valueOf(lng)       + " , ready to rumble!");

// Do clever stuff here
}