【问题标题】:Getting location Updates in Android在 Android 中获取位置更新
【发布时间】:2014-01-05 20:17:55
【问题描述】:

您好 AM,使用以下代码:How to get current location in Android 这里我使用 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>

【问题讨论】:

    标签: android location updates


    【解决方案1】:

    当您在 locationManger 上调用 requestLocationUpdates 方法时,您将 'this' 指定为 LocationListener:

    locationManager.requestLocationUpdates(..., ..., ..., this);
    

    这很好,因为该类实现了 LocationListener。位置更改时进行的回调是方法“onLocationChanged”。你的类中有这个方法,但它没有代码,所以什么都不做:

    @Override
    public void onLocationChanged(Location location) {
    }
    

    添加适当的代码以从“位置”参数中获取新的纬度和经度,并在您的 Activity 中更新 TextView。有很多方法可以做到这一点。想到的两个:

    1) 在 GPSTracker 类构造函数中传递对 TextView 的引用,以便您可以从类中访问它。 2) 在 GPSTracker 类构造函数中传递对 Activity 的引用,以便您可以在 Activity 中调用一个方法(接受要显示的值),然后更新 TextView。

    编辑:

    您已经有了我在上面第 2 点中提到的参考资料。当您在 Activity 中实例化 GPSTracker 实例时,您已经传递了“this”:

    GPSTracker mGPS = new GPSTracker(this);
    

    在这种情况下,'this' 是 MainActivity 类的实例,而 Activity 类也恰好是 Context。在 GPSTracker 的构造函数中,您将此上下文存储在一个变量中:

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

    因此,您可以使用它来访问 TextView。将您拥有的上下文投射到一个 Activity 上,然后您可以在其上使用 findViewById 方法:

    @Override
    public void onLocationChanged(Location location)
    {
        TextView text = (TextView) ((Activity)mContext).findViewById(R.id.texts);
        text.setText("Lat"+location.getLatitude()+"Lon"+location.getLongitude());
    }
    

    【讨论】:

    • 嗨 Nigel,您能否详细说明该方法,正如您根据我的代码所建议的那样。我是 Android 新手,发展缓慢。您的帮助将不胜感激。问候山姆
    • NigelK,Superrrrrrrrrb 是我可以告诉你的......它的工作方式和它的工作方式非常好......他的位置在不到 1 或 2 m 的距离内不断更新。 ...太棒了 ty 非常....我的问题解决了....问候,Sam
    • Nigelk....添加到这个....现在我已经在文件中获得了位置的更新坐标....正在将文件传输到我的笔记本电脑并使用它进一步......我无法在流程中的任何地方使用互联网服务..总结是我有一个文件存储在我的安卓手机的内部存储器中,我必须通过一些无线网络技术将它发送到我的基于 Windows 的笔记本电脑而不使用互联网服务..我也不能使用 USB,因为感觉需要用坐标更新......
    • Sam - 我想蓝牙是要走的路。不是我处理过的事情,所以请提出一个新问题,你会从其他人那里得到很多帮助。谢谢。
    • Thx nigel 我已经发布了问题...我遇到的另一个问题是我必须在正在执行的文件中添加更改的位置坐标,但它会覆盖前一个...这里是强制声明位置内的文件创建和文件编写器模块已更改,如果我在其外部声明给我一些令牌错误...我需要的输出是查看正在使用的代码
    【解决方案2】:

    做这样的事情:

    示例代码:

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

    【讨论】:

    • 对此我不熟悉..请参阅我已将其添加到我的代码中,但不明白接下来要做什么...您能详细说明一下...我必须做的聪明的事情是什么。 ..你能看到我的代码,并给我确切的步骤我必须做什么..
    猜你喜欢
    • 2014-12-31
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2023-04-08
    • 1970-01-01
    相关资源
    最近更新 更多