【问题标题】:How can I get my current location in Android using GPS?如何使用 GPS 获取我在 Android 中的当前位置?
【发布时间】:2020-01-11 18:44:18
【问题描述】:

我想通过 GPS 以地址的形式获取我的当前位置。我正在使用安卓工作室。 这是说我的应用程序停止工作。 它有什么错误? 有人可以帮我摆脱这个吗?

我在activity_main.xml 文件中的代码是

<?xml version="1.0" encoding="utf-8"?>
<android.support.constraint.ConstraintLayout 
xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:app="http://schemas.android.com/apk/res-auto"
xmlns:tools="http://schemas.android.com/tools"
android:layout_width="match_parent"
android:layout_height="match_parent"
tools:context=".MainActivity">

<TextView
    android:id="@+id/text_view"
    android:layout_width="wrap_content"
    android:layout_height="wrap_content"
    android:text="Hello World!"
    app:layout_constraintBottom_toBottomOf="parent"
    app:layout_constraintLeft_toLeftOf="parent"
    app:layout_constraintRight_toRightOf="parent"
    app:layout_constraintTop_toTopOf="parent" />

我在 MainActivity.java 中的代码是

package com.example.showlatlong;

import androidx.appcompat.app.AppCompatActivity;
import androidx.core.app.ActivityCompat;

import android.Manifest;
import android.content.Context;
import android.content.pm.PackageManager;
import android.location.Address;
import android.location.Geocoder;
import android.location.Location;
import android.location.LocationManager;
import android.os.Bundle;
import android.widget.TextView;

import java.util.List;
import java.util.Locale;

public class MainActivity extends AppCompatActivity {

Location gps_loc, network_loc, final_loc;
double longitude;
double latitude;
String userCountry, userAddress;


@Override
protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.activity_main);

    TextView tv = findViewById(R.id.text_view);

    LocationManager locationManager = (LocationManager) getSystemService(Context.LOCATION_SERVICE);


    if (ActivityCompat.checkSelfPermission(this, Manifest.permission.ACCESS_FINE_LOCATION) != PackageManager.PERMISSION_GRANTED
            && ActivityCompat.checkSelfPermission(this, Manifest.permission.ACCESS_COARSE_LOCATION) != PackageManager.PERMISSION_GRANTED
            && ActivityCompat.checkSelfPermission(this, Manifest.permission.ACCESS_NETWORK_STATE) != PackageManager.PERMISSION_GRANTED) {

        return;
    }

    try {
        gps_loc = locationManager.getLastKnownLocation(LocationManager.GPS_PROVIDER);
        network_loc = locationManager.getLastKnownLocation(LocationManager.NETWORK_PROVIDER);
    } catch (Exception e) {
        e.printStackTrace();
    }

    if (gps_loc != null) {
        final_loc = gps_loc;
        latitude = final_loc.getLatitude();
        longitude = final_loc.getLongitude();
    }
    else if (network_loc != null) {
        final_loc = network_loc;
        latitude = final_loc.getLatitude();
        longitude = final_loc.getLongitude();
    }
    else {
        latitude = 0.0;
        longitude = 0.0;
    }

     ActivityCompat.requestPermissions(this, new String[] {Manifest.permission.ACCESS_FINE_LOCATION, Manifest.permission.ACCESS_COARSE_LOCATION, Manifest.permission.ACCESS_NETWORK_STATE}, 1);



    try {

        Geocoder geocoder = new Geocoder(this, Locale.getDefault());
        List<Address> addresses = geocoder.getFromLocation(latitude, longitude, 1);
        if (addresses != null && addresses.size() > 0) {
            userCountry = addresses.get(0).getCountryName();
            userAddress = addresses.get(0).getAddressLine(0);
            tv.setText(userCountry + ", " + userAddress);
        }
        else {
            userCountry = "Unknown";
            tv.setText(userCountry);
        }

    } catch (Exception e) {
        e.printStackTrace();
    }

}

}

我在 manifest.xml 中的代码是

<?xml version="1.0" encoding="utf-8"?>

<uses-permission android:name="android.permission.INTERNET"/>
<uses-permission android:name="android.permission.ACCESS_FINE_LOCATION"/>
<uses-permission android:name="android.permission.ACCESS_COARSE_LOCATION"/>
<uses-permission android:name="android.permission.ACCESS_NETWORK_STATE"/>

<application
    android:allowBackup="true"
    android:icon="@mipmap/ic_launcher"
    android:label="@string/app_name"
    android:roundIcon="@mipmap/ic_launcher_round"
    android:supportsRtl="true"
    android:theme="@style/AppTheme">
    <activity android:name=".MainActivity">
        <intent-filter>
            <action android:name="android.intent.action.MAIN" />

            <category android:name="android.intent.category.LAUNCHER" />
        </intent-filter>
    </activity>
</application>

整个代码是这样的。它正在打开应用程序,在不到一秒钟的时间内,它通过在我的 android 应用程序上抛出“应用程序不断停止”的错误消息而关闭。 这是我在logcat中得到的

2019-09-11 12:58:45.344 15400-15400/com.example.showlatlong E/AndroidRuntime: FATAL EXCEPTION: main
Process: com.example.showlatlong, PID: 15400
java.lang.RuntimeException: Unable to start activity ComponentInfo{com.example.showlatlong/com.example.showlatlong.MainActivity}: android.view.InflateException: Binary XML file line #2: Binary XML file line #2: Error inflating class android.support.constraint.ConstraintLayout
    at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:2723)
    at android.app.ActivityThread.handleLaunchActivity(ActivityThread.java:2784)
    at android.app.ActivityThread.-wrap12(ActivityThread.java)
    at android.app.ActivityThread$H.handleMessage(ActivityThread.java:1523)
    at android.os.Handler.dispatchMessage(Handler.java:102)
    at android.os.Looper.loop(Looper.java:163)
    at android.app.ActivityThread.main(ActivityThread.java:6238)
    at java.lang.reflect.Method.invoke(Native Method)
    at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:933)
    at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:823)
 Caused by: android.view.InflateException: Binary XML file line #2: Binary XML file line #2: Error inflating class android.support.constraint.ConstraintLayout
 Caused by: android.view.InflateException: Binary XML file line #2: Error inflating class android.support.constraint.ConstraintLayout
 Caused by: java.lang.ClassNotFoundException: Didn't find class "android.support.constraint.ConstraintLayout" on path: DexPathList[[zip file "/data/app/com.example.showlatlong-1/base.apk", zip file "/data/app/com.example.showlatlong-1/split_lib_dependencies_apk.apk", zip file "/data/app/com.example.showlatlong-1/split_lib_slice_0_apk.apk", zip file "/data/app/com.example.showlatlong-1/split_lib_slice_1_apk.apk", zip file "/data/app/com.example.showlatlong-1/split_lib_slice_2_apk.apk", zip file "/data/app/com.example.showlatlong-1/split_lib_slice_3_apk.apk", zip file "/data/app/com.example.showlatlong-1/split_lib_slice_4_apk.apk", zip file "/data/app/com.example.showlatlong-1/split_lib_slice_5_apk.apk", zip file "/data/app/com.example.showlatlong-1/split_lib_slice_6_apk.apk", zip file "/data/app/com.example.showlatlong-1/split_lib_slice_7_apk.apk", zip file "/data/app/com.example.showlatlong-1/split_lib_slice_8_apk.apk", zip file "/data/app/com.example.showlatlong-1/split_lib_slice_9_apk.apk"],nativeLibraryDirectories=[/data/app/com.example.showlatlong-1/lib/arm64, /system/lib64, /vendor/lib64]]
    at dalvik.system.BaseDexClassLoader.findClass(BaseDexClassLoader.java:56)
    at java.lang.ClassLoader.loadClass(ClassLoader.java:380)
    at java.lang.ClassLoader.loadClass(ClassLoader.java:312)
    at android.view.LayoutInflater.createView(LayoutInflater.java:613)
    at android.view.LayoutInflater.createViewFromTag(LayoutInflater.java:812)
    at android.view.LayoutInflater.createViewFromTag(LayoutInflater.java:752)
    at android.view.LayoutInflater.inflate(LayoutInflater.java:499)
    at android.view.LayoutInflater.inflate(LayoutInflater.java:430)
    at android.view.LayoutInflater.inflate(LayoutInflater.java:377)
    at androidx.appcompat.app.AppCompatDelegateImpl.setContentView(AppCompatDelegateImpl.java:555)
    at androidx.appcompat.app.AppCompatActivity.setContentView(AppCompatActivity.java:161)
    at com.example.showlatlong.MainActivity.onCreate(MainActivity.java:29)
    at android.app.Activity.performCreate(Activity.java:6857)
    at android.app.Instrumentation.callActivityOnCreate(Instrumentation.java:1119)
    at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:2676)
    at android.app.ActivityThread.handleLaunchActivity(ActivityThread.java:2784)
    at android.app.ActivityThread.-wrap12(ActivityThread.java)
    at android.app.ActivityThread$H.handleMessage(ActivityThread.java:1523)
    at android.os.Handler.dispatchMessage(Handler.java:102)
    at android.os.Looper.loop(Looper.java:163)
    at android.app.ActivityThread.main(ActivityThread.java:6238)
    at java.lang.reflect.Method.invoke(Native Method)
    at 


 com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit. 
 java:933)
 2019-09-11 12:58:45.344 15400-15400/com.example.showlatlong  
 E/AndroidRuntime:     
 at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:823)

【问题讨论】:

  • 请显示一些代码,你到目前为止已经尝试过什么
  • 本机只能使用 gps 获取坐标。你想像谷歌地图一样获取地址吗?
  • @ArpitJ。我认为可以使用反向地理编码转换坐标以在谷歌地图中显示位置。
  • @CyrilleConMorales 我尝试过的所有代码都不是最新版本,它们是 3 年前发布的。所以,我没有发布代码。我仍然是一个初学者,这让我问你这个过程。谢谢你
  • 对于那些正在寻找简单实现以获取当前/最后已知位置的人,请查看:stackoverflow.com/a/62761897/3908895

标签: android android-location android-gps


【解决方案1】:

在您的 AndroidManifest.xml 中,您必须将其放在应用程序标记的上方或下方。

<uses-permission android:name="android.permission.INTERNET"/>
<uses-permission android:name="android.permission.ACCESS_FINE_LOCATION"/>
<uses-permission android:name="android.permission.ACCESS_COARSE_LOCATION"/>
<uses-permission android:name="android.permission.ACCESS_NETWORK_STATE"/>

因为你没有显示你的代码你一直在做什么,所以我不知道如何解决你的问题。但下面的代码是我用于我的应用程序获取当前用户国家/地区的代码。

activity_main.xml

    <?xml version="1.0" encoding="utf-8"?>
<android.support.constraint.ConstraintLayout xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:app="http://schemas.android.com/apk/res-auto"
    xmlns:tools="http://schemas.android.com/tools"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    tools:context=".MainActivity">

    <TextView
        android:id="@+id/text_view"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:text="Hello World!"
        app:layout_constraintBottom_toBottomOf="parent"
        app:layout_constraintLeft_toLeftOf="parent"
        app:layout_constraintRight_toRightOf="parent"
        app:layout_constraintTop_toTopOf="parent" />

</android.support.constraint.ConstraintLayout>

MainActivity.java

import android.Manifest;
import android.content.Context;
import android.content.pm.PackageManager;
import android.location.Address;
import android.location.Geocoder;
import android.location.Location;
import android.location.LocationManager;
import android.support.v4.app.ActivityCompat;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.widget.TextView;

import java.util.List;
import java.util.Locale;

public class MainActivity extends AppCompatActivity {

        Location gps_loc;
        Location network_loc;
        Location final_loc;
        double longitude;
        double latitude;
        String userCountry, userAddress;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);


        TextView tv = findViewById(R.id.text_view);

        LocationManager locationManager = (LocationManager) getSystemService(Context.LOCATION_SERVICE);


        if (ActivityCompat.checkSelfPermission(this, Manifest.permission.ACCESS_FINE_LOCATION) != PackageManager.PERMISSION_GRANTED
                && ActivityCompat.checkSelfPermission(this, Manifest.permission.ACCESS_COARSE_LOCATION) != PackageManager.PERMISSION_GRANTED
                && ActivityCompat.checkSelfPermission(this, Manifest.permission.ACCESS_NETWORK_STATE) != PackageManager.PERMISSION_GRANTED) {

            return;
        }

        try {

            gps_loc = locationManager.getLastKnownLocation(LocationManager.GPS_PROVIDER);
            network_loc = locationManager.getLastKnownLocation(LocationManager.NETWORK_PROVIDER);

        } catch (Exception e) {
            e.printStackTrace();
        }

        if (gps_loc != null) {
            final_loc = gps_loc;
            latitude = final_loc.getLatitude();
            longitude = final_loc.getLongitude();
        }
        else if (network_loc != null) {
            final_loc = network_loc;
            latitude = final_loc.getLatitude();
            longitude = final_loc.getLongitude();
        }
        else {
            latitude = 0.0;
            longitude = 0.0;
        }


        ActivityCompat.requestPermissions(this, new String[] {Manifest.permission.ACCESS_FINE_LOCATION, Manifest.permission.ACCESS_COARSE_LOCATION, Manifest.permission.ACCESS_NETWORK_STATE}, 1);

        try {

            Geocoder geocoder = new Geocoder(this, Locale.getDefault());
            List<Address> addresses = geocoder.getFromLocation(latitude, longitude, 1);
            if (addresses != null && addresses.size() > 0) {
                userCountry = addresses.get(0).getCountryName();
                userAddress = addresses.get(0).getAddressLine(0);
                tv.setText(userCountry + ", " + userAddress);
            }
            else {
                userCountry = "Unknown";
                tv.setText(userCountry);
            }

        } catch (Exception e) {
            e.printStackTrace();
        }
    }
}

您必须理解此代码。还有一件事,如果你在模拟器上运行你的应用程序,它会一直显示“美国”,或者更具体地说,是 Googleplex 的位置。只需在真实设备上运行它即可返回您当前的位置。

要返回您当前的位置而不仅仅是国家本身,您可以替换

addresses.get(0).getCountryName()

类似的东西

addresses.get(0).getPostalCode()

addresses.get(0).getAdminArea()

等等。

您也可以将这些值连接为字符串以详细显示您当前的位置。

请看this

【讨论】:

  • 非常感谢您的及时回复。错误:找不到符号变量 countryAdapter 错误:找不到符号变量 countryAdapter 错误:找不到符号变量 countryEdit 错误:找不到符号变量 countryEdit,我收到这些错误。请你帮帮我。
  • 看,我的 countryEdit 变量是一个微调器,而 countryAdapter 变量是 ArrayAdapter。您是否会使用微调器?请告诉我。
  • 不,我之前没用过。我刚刚尝试了您发送给我的代码。你能告诉我包括activity.xml文件的整个代码吗?这对我很有帮助。
  • 这是唯一相关的代码。我假设您正在使用文本视图来执行此操作,因此我将其更改为文本视图而不是微调器。如果有任何错误,请告诉我。
  • 错误:找不到符号变量 text_view。我现在得到这个。我也导入了 android.widget.textview。我现在该怎么办。
【解决方案2】:

您可以使用Google's Fused Location Profivider API library 来获取和访问您当前的位置(假设您的 GPS 服务已打开)

别忘了把这个添加到你的AndroidManifest.xml

 <uses-permission android:name="android.permission.ACCESS_FINE_LOCATION" />
 <uses-permission android:name="android.permission.ACCESS_COARSE_LOCATION" />

更详细的教程可以参考Medium GPS Tutorial

干杯

【讨论】:

  • 取决于设备,这可能不是最好的主意。我的工作管理着 600 台没有通过 play store 获取软件的平板电脑,并且融合的位置提供者依赖于 play 服务,google 强迫你经常更新。如果你不这样做,你就会失去播放服务,这会破坏保险丝位置提供者。我们不得不手动更新 600 台平板电脑。
  • 是的。但在大多数情况下,如果您正在制定规范,这是一个最佳计划。在您的情况下,您可以使用本机 LocationManager 访问 GPS 数据
  • 就像我说的,取决于设备。请注意,我还看到了一款平板电脑(特别是三星的新标签),我们不得不禁用除 gps 之外的所有位置源,因为它搞砸了。您的里程可能会有所不同。
  • @JohnLord,如果不使用Fused Location Profivider 并且很少(或从不)更新 Play 服务,LocationManager.getLastKnownLocation 会正常工作吗?
  • 我会这么认为。 google play 包装器所做的只是添加一些事件供您使用并自动切换到当前最佳位置。如果你在一个城市,这可能是 wifi。请注意,底层行为取决于操作系统版本。较新的仅在您移动时或当他们为您提供积分而不是您要求时触发新积分。它可以防止系统瘫痪。
【解决方案3】:

使用 Android 框架位置 API 中的 Geocoder 类,您可以将地址转换为相应的地理坐标。这个过程称为地理编码。或者,您可以将地理位置转换为地址。地址查找功能也称为反向地理编码。

使用getFromLocation() 方法将地理位置转换为地址。该方法返回对应于给定纬度和经度的估计街道地址。

public List<Address> getFromLocation (double latitude, double int maxResults)

这返回一个已知的地址数组,用于描述紧接给定纬度和经度周围的区域。返回的地址将针对提供给此类的构造函数的语言环境进行本地化。

也请看这里:https://developer.android.com/training/location/display-address

【讨论】:

    【解决方案4】:

    试试这个! (一年前做的)- 将在一定的时间间隔内更新您所有搬家的位置。

    在等级中添加依赖项

    implementation 'com.google.android.gms:play-services-location:16.0.0'
    

    在清单中添加权限

    <uses-permission android:name="android.permission.ACCESS_FINE_LOCATION" />
    <uses-permission android:name="android.permission.ACCESS_NETWORK_STATE" />
    <uses-permission android:name="android.permission.ACCESS_WIFI_STATE" />
    <uses-permission android:name="android.permission.INTERNET" />
    

    在你的活动中

    public class MainActivity extends AppCompatActivity implements GoogleApiClient.ConnectionCallbacks,
            GoogleApiClient.OnConnectionFailedListener, LocationListener {
    
        double longitude;
        double latitude;
        TextView tv;
        Context context;
    
        Location mLastLocation;
        private GoogleApiClient mGoogleApiClient;
        private LocationRequest mLocationRequest;
        public static final int MY_PERMISSIONS_REQUEST_LOCATION = 99;
        public static final int REQUEST_ID_MULTIPLE_PERMISSIONS = 1;
    
    
        @Override
        protected void onCreate(Bundle savedInstanceState) {
            super.onCreate(savedInstanceState);
            setContentView(R.layout.activity_main);
    
            context = this;
            tv = findViewById(R.id. text_view);
    
            mGoogleApiClient = new GoogleApiClient.Builder(this).addApi(LocationServices.API).addConnectionCallbacks(this).addOnConnectionFailedListener(this).build();
            initLocation();
    
        }
    
        @Override
        public void onConnected(@Nullable Bundle bundle) {
            if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.M) {
                checkLocationPermission();
            }
    
            mLocationRequest = LocationRequest.create();
            mLocationRequest.setPriority(LocationRequest.PRIORITY_HIGH_ACCURACY);
            mLocationRequest.setInterval(100000); // Update location every second
            if (ContextCompat.checkSelfPermission(this, Manifest.permission.ACCESS_FINE_LOCATION) == PackageManager.PERMISSION_GRANTED)
            {
                LocationServices.FusedLocationApi.requestLocationUpdates(mGoogleApiClient, mLocationRequest, this);
            }
    
            mLastLocation = LocationServices.FusedLocationApi.getLastLocation(mGoogleApiClient);
            if (mLastLocation != null) {
                latitude = mLastLocation.getLatitude();
                longitude = mLastLocation.getLongitude();
                setValue();
            }
        }
    
        private void setValue() {
            String strAddress =  getAddressFromLocation(this, latitude, longitude);
            tv.setText(strAddress);
        }
    
        @Override
        public void onConnectionSuspended(int i) {
    
        }
    
        @Override
        public void onConnectionFailed(@NonNull ConnectionResult connectionResult) {
    
        }
    
        @Override
        public void onLocationChanged(Location location) {
            if(location!=null){
                latitude = location.getLatitude();
                longitude = location.getLongitude();
            }
        }
    
        public boolean checkLocationPermission() {
            if (ContextCompat.checkSelfPermission(this, Manifest.permission.ACCESS_FINE_LOCATION) != PackageManager.PERMISSION_GRANTED)
            {
                // Asking user if explanation is needed
                if (ActivityCompat.shouldShowRequestPermissionRationale(this, Manifest.permission.ACCESS_FINE_LOCATION))
                {
                    // Show an explanation to the user *asynchronously* -- don't block
                    // this thread waiting for the user's response! After the user
                    // sees the explanation, try again to request the permission.
    
                    //Prompt the user once explanation has been shown
                    ActivityCompat.requestPermissions(this, new String[]{Manifest.permission.ACCESS_FINE_LOCATION}, MY_PERMISSIONS_REQUEST_LOCATION);
                }
                else
                {
                    // No explanation needed, we can request the permission.
                    ActivityCompat.requestPermissions(this, new String[]{Manifest.permission.ACCESS_FINE_LOCATION}, MY_PERMISSIONS_REQUEST_LOCATION);
                }
    
                return false;
            }
            else
            {
                return true;
            }
        }
    
        @Override
        protected void onStart() {
            super.onStart();
            mGoogleApiClient.connect();
        }
    
        @Override
        protected void onResume() {
            super.onResume();
            mGoogleApiClient.connect();
            initLocation();
        }
    
        @Override
        protected void onPause() {
            super.onPause();
            mGoogleApiClient.disconnect();
        }
    
        @Override
        protected void onDestroy() {
            mGoogleApiClient.disconnect();
            super.onDestroy();
        }
    
    
        private void initLocation() {
    
            if(checkAndRequestPermissions(context)) {
                Toast.makeText(context,"Permission Granded",Toast.LENGTH_SHORT).show();
            }
        }
    
        public static  boolean checkAndRequestPermissions(Context context) {
    
            int locationPermission = ContextCompat.checkSelfPermission(context,
                    Manifest.permission.ACCESS_FINE_LOCATION);
    
            List<String> listPermissionsNeeded = new ArrayList<>();
    
            if (locationPermission != PackageManager.PERMISSION_GRANTED) {
                listPermissionsNeeded.add(Manifest.permission.ACCESS_FINE_LOCATION);
            }
    
            if (!listPermissionsNeeded.isEmpty()) {
                ActivityCompat.requestPermissions((Activity) context, listPermissionsNeeded.toArray(new String[listPermissionsNeeded.size()]),REQUEST_ID_MULTIPLE_PERMISSIONS);
                return false;
            }
            return true;
        }
    
        public static String getAddressFromLocation(Context context, final double latitude, final double longitude) {
            String straddress = "";
            Geocoder geocoder = new Geocoder(context, Locale.getDefault());
    
            try {
                List<Address> addressList = geocoder.getFromLocation(
                        latitude, longitude, 1);
                if (addressList != null && addressList.size() > 0) {
                    Address address = addressList.get(0);
                    StringBuilder sb = new StringBuilder();
                    if(address.getAddressLine(0) !=null && address.getAddressLine(0).length()>0 && !address.getAddressLine(0).contentEquals("null"))
                    {
                        sb.append(address.getAddressLine(0)).append("\n");
                    }else {
    
                        sb.append(address.getLocality()).append("\n");
                        sb.append(address.getPostalCode()).append("\n");
                        sb.append(address.getCountryName());
                    }
                    straddress = sb.toString();
                    //Log.e("leaddress","@"+straddress);
                }
            } catch (IOException e) {
                //Log.e(TAG, "Unable connect to Geocoder", e);
            }
            return straddress;
        }
    }
    

    【讨论】:

      【解决方案5】:

      请尝试以下方式,您可以同时使用 gps 和网络获取位置

       public class LocationTracker {
      
          public static String TAG = LocationTracker.class.getName();
      
          boolean isGPSEnabled = false;
          boolean isNetworkEnabled = false;
          boolean canGetLocation = false;
          Location location = null;
          private static final long MIN_DISTANCE_CHANGE_FOR_UPDATES = 0;
          private static final long MIN_TIME_BW_UPDATES = 1000;
          protected LocationManager locationManager;
          static Context mcontext;
          private static LocationTracker instance;
      
      
          public static synchronized LocationTracker getInstance(Context ctx) {
              mcontext = ctx;
              if (instance == null) {
                  instance = new LocationTracker();
              }
              return instance;
          }
      
      
          public void connectToLocation() {
              stopLocationUpdates();
              displayLocation();
          }
      
          private void displayLocation() {
              try {
                  Logger.i(TAG,"displayLocation");
                  Location location = getLocation();
                  if (location != null) {
                      updateLattitudeLongitude(location.getLatitude(), location.getLongitude());
                  }
              } catch (SecurityException e) {
                  ExceptionHandler.printStackTrace(e);
              } catch (Exception e) {
                  ExceptionHandler.printStackTrace(e);
              }
          }
      
          public Location getLocation() {
              try {
                  locationManager = (LocationManager) mcontext
                          .getSystemService(Context.LOCATION_SERVICE);
      
                  isGPSEnabled = locationManager
                          .isProviderEnabled(LocationManager.GPS_PROVIDER);
      
                  isNetworkEnabled = locationManager
                          .isProviderEnabled(LocationManager.NETWORK_PROVIDER);
      
                  if (!isGPSEnabled && !isNetworkEnabled) {
                      this.canGetLocation = false;
      
                  } else {
      
                      this.canGetLocation = true;
      
                      if (isNetworkEnabled) {
      
                          Logger.d(TAG + "-->Network", "Network Enabled");
      
                          if (locationManager != null) {
      
                              location = locationManager
                                      .getLastKnownLocation(LocationManager.NETWORK_PROVIDER);
      
                              locationManager.requestLocationUpdates(
                                      LocationManager.NETWORK_PROVIDER,
                                      MIN_TIME_BW_UPDATES,
                                      MIN_DISTANCE_CHANGE_FOR_UPDATES, locationProviderListener);
                              return location;
                          }
      
                      } else if (isGPSEnabled) {
      
                          Logger.d(TAG + "-->GPS", "GPS Enabled");
      
                          if (locationManager != null) {
      
                              location = locationManager
                                      .getLastKnownLocation(LocationManager.GPS_PROVIDER);
      
                              locationManager.requestLocationUpdates(
                                      LocationManager.GPS_PROVIDER,
                                      MIN_TIME_BW_UPDATES,
                                      MIN_DISTANCE_CHANGE_FOR_UPDATES, locationProviderListener);
      
                              return location;
                          }
                      }
                  }
      
              } catch (SecurityException e) {
                  ExceptionHandler.printStackTrace(e);
              } catch (Exception e) {
                  ExceptionHandler.printStackTrace(e);
              }
              return location;
          }
      
          public void updateLattitudeLongitude(double latitude, double longitude) {
              Logger.i(TAG, "updated Lat == " + latitude + "  updated long == " + longitude);
              SharedPreferenceManager sharedPreferenceManager = SharedPreferenceManager.getInstance();
              sharedPreferenceManager.updateUserDeviceLatLong(latitude, longitude);
          }
      
          public void stopLocationUpdates(){
              try {
                  if (locationManager != null) {
                      Logger.i(TAG,"stopLocationUpdates");
                      locationManager.removeUpdates(locationProviderListener);
                      locationManager = null;
                  }
              }catch (Exception e){
                  e.printStackTrace();
              }
          }
      
          public LocationListener locationProviderListener = new LocationListener() {
      
              @Override
              public void onLocationChanged(Location location) {
                  try {
                      double latitude = location.getLatitude();
                      double longitude = location.getLongitude();
                      updateLattitudeLongitude(latitude, longitude);
      
                  } catch (Exception e) {
      
                      ExceptionHandler.printStackTrace(e);
                  }
              }
      
              @Override
              public void onStatusChanged(String s, int i, Bundle bundle) {
      
      
              }
      
              @Override
              public void onProviderEnabled(String s) {
      
      
              }
      
              @Override
              public void onProviderDisabled(String s) {
      
      
              }
          };
      }
      

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 1970-01-01
        • 2014-05-09
        • 2016-07-30
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        相关资源
        最近更新 更多