【问题标题】:ANDROID: GetLocation nullANDROID:获取位置空
【发布时间】:2016-02-20 09:58:30
【问题描述】:

我正在开发一个基于 gmaps 和地理位置的小应用程序。

这是计算long和lat得到我的位置的方法:

public List<Object> getLocation(Activity act) {

        List<Object> parameters = new ArrayList();

        //controllo se il GPS è attivo
        isGPSEnable = locationManager.isProviderEnabled(LocationManager.GPS_PROVIDER);

        //verifico lo stato della connessione
        isNetworkrEnable = locationManager.isProviderEnabled(LocationManager.NETWORK_PROVIDER);

        if (!isGPSEnable && !isNetworkrEnable) {
            return null;
        } else {
            if (isNetworkrEnable) {
                if (ActivityCompat.checkSelfPermission(act, Manifest.permission.ACCESS_FINE_LOCATION) != PackageManager.PERMISSION_GRANTED &&
                        ActivityCompat.checkSelfPermission(act, Manifest.permission.ACCESS_COARSE_LOCATION) != PackageManager.PERMISSION_GRANTED) {
                    // TODO: Consider calling
                    //    ActivityCompat#requestPermissions
                    // here to request the missing permissions, and then overriding
                    //   public void onRequestPermissionsResult(int requestCode, String[] permissions,
                    //                                          int[] grantResults)
                    // to handle the case where the user grants the permission. See the documentation
                    // for ActivityCompat#requestPermissions for more details.
                    return null;
                }
                locationManager.requestLocationUpdates(LocationManager.NETWORK_PROVIDER, 0, 0, this);
                Log.d("NETWORK CHECK", "NETWORK ATTIVO!");
                if(locationManager != null){
                    location = locationManager.getLastKnownLocation(LocationManager.NETWORK_PROVIDER);
                    if(location != null){
                        latitudine = location.getLatitude();
                        longitudine = location.getLongitude();
                        parameters.add(location);
                        parameters.add(latitudine);
                        parameters.add(longitudine);
                    }
                }
            }

            if(isGPSEnable){
                if(isGPSEnable){
                    if(location == null){
                        locationManager.requestLocationUpdates(LocationManager.GPS_PROVIDER, 0, 0, this);
                        Log.d("GPS CHECK", "GPS ATTIVO!");
                        if(locationManager != null){
                            location = locationManager.getLastKnownLocation(LocationManager.GPS_PROVIDER);
                            if(location != null){
                                latitudine = location.getLatitude();
                                longitudine = location.getLongitude();
                                parameters.add(location);
                                parameters.add(latitudine);
                                parameters.add(longitudine);
                            }
                        }
                    }
                }
            }
        }

        return parameters;
    }

这是我的清单:

<?xml version="1.0" encoding="utf-8"?>
<manifest xmlns:android="http://schemas.android.com/apk/res/android"
    package="francescoperfetti.mamba.it.futureselfdrive_gmaps">

    <!--
         The ACCESS_COARSE/FINE_LOCATION permissions are not required to use
         Google Maps Android API v2, but you must specify either coarse or fine
         location permissions for the 'MyLocation' functionality. 
    -->
    <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" />

    <application
        android:allowBackup="true"
        android:icon="@mipmap/ic_launcher"
        android:label="@string/app_name"
        android:supportsRtl="true"
        android:theme="@style/AppTheme">

        <!--
             The API key for Google Maps-based APIs is defined as a string resource.
             (See the file "res/values/google_maps_api.xml").
             Note that the API key is linked to the encryption key used to sign the APK.
             You need a different API key for each encryption key, including the release key that is used to
             sign the APK for publishing.
             You can define the keys for the debug and release targets in src/debug/ and src/release/. 
        -->
        <meta-data
            android:name="com.google.android.geo.API_KEY"
            android:value="@string/google_maps_key" />

        <activity
            android:name=".MainMapsActivity"
            android:label="@string/title_activity_main_maps">
            <intent-filter>
                <action android:name="android.intent.action.MAIN" />

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

</manifest>

位置始终为空,我在模拟器上检查了一些东西或有什么问题?

谢谢,祝你有美好的一天。

弗朗切斯科。

【问题讨论】:

  • 使用 Google Play 服务 fues location api。它很容易处理,并且会减少位置管理器的障碍

标签: android google-maps geolocation


【解决方案1】:

以下是返回用户当前位置的我的代码:

以下是服务类:

   package com.anonymous.attendancemange.servicess;

    import android.Manifest;
    import android.app.Service;
    import android.content.Intent;
    import android.location.Location;
    import android.location.LocationListener;

    import android.os.AsyncTask;
    import android.os.Bundle;
    import android.os.IBinder;
    import android.support.v4.app.ActivityCompat;
    import android.support.v4.content.ContextCompat;
    import android.util.Log;

    import com.anonymous.attendancemange.util.Util;
    import com.google.android.gms.common.ConnectionResult;
    import com.google.android.gms.common.api.GoogleApiClient;
    import com.google.android.gms.location.LocationRequest;
    import com.google.android.gms.location.LocationServices;


    /**
     * Created by bitcode on 24/8/15.
     */

    //GoogleApiClient.ConnectionCallbacks ,GoogleApiClient.OnConnectionFailedListener,LocationListener
    public class MyService extends Service implements LocationListener, GoogleApiClient.ConnectionCallbacks, GoogleApiClient.OnConnectionFailedListener {

        private GoogleApiClient googleApiClient;
        private LocationRequest mLocationRequest;
        private static String TAG = "test";
        private GetLocationRef mGetLocationRef;


        @Override
        public IBinder onBind(Intent intent) {

            return null;
        }

        @Override
        public void onCreate() {
            super.onCreate();
            Log.d(TAG, "onCreate");

            buildGoogleApiClient();
            createLocationRequest();

        }


        @Override
        public synchronized void onDestroy() {
            super.onDestroy();


            Log.d(TAG, "onDestroy");
            if (googleApiClient != null)
                stopLocationUpdates();
        }

        @Override
        public int onStartCommand(Intent intent, int flags, int startId) {

            Log.d(TAG, "onStart");

            if (googleApiClient != null) {
                googleApiClient.connect();
            }

            return super.onStartCommand(intent, flags, startId);
        }


        @Override
        public void onLocationChanged(Location location) {


            Log.d("test", "location changes main .");
            if (location != null) {

                Util.currntLocation = location;

            }
        }

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

            Log.d(TAG, "State Changed.");
        }

        @Override
        public void onProviderEnabled(String provider) {

        }

        @Override
        public void onProviderDisabled(String provider) {

        }


        protected void createLocationRequest() {
            mLocationRequest = new LocationRequest();
            mLocationRequest.setInterval(30000);
            mLocationRequest.setFastestInterval(30000);
            mLocationRequest.setPriority(LocationRequest.PRIORITY_HIGH_ACCURACY);
        }

        protected void startLocationUpdates() {

            Log.d(TAG, "StartLocationUpdates");

            mGetLocationRef = new GetLocationRef();

            int permissionCheck = ContextCompat.checkSelfPermission(this, Manifest.permission.ACCESS_FINE_LOCATION);
            if (permissionCheck == android.content.pm.PackageManager.PERMISSION_GRANTED) {
                LocationServices.FusedLocationApi.requestLocationUpdates(googleApiClient, mLocationRequest, mGetLocationRef);
            }


        }

        protected void stopLocationUpdates() {

            Log.d(TAG, "StopUpdate");

            if (mGetLocationRef != null)
                LocationServices.FusedLocationApi.removeLocationUpdates(googleApiClient, mGetLocationRef);
        }


        @Override
        public void onConnected(Bundle bundle) {

            Log.d("test", "connected");
            int permissionCheck = ContextCompat.checkSelfPermission(this, Manifest.permission.ACCESS_FINE_LOCATION);

            if (permissionCheck == android.content.pm.PackageManager.PERMISSION_GRANTED) {

                Location mLastLocation = LocationServices.FusedLocationApi.getLastLocation(googleApiClient);
                if (mLastLocation != null) {

                    Util.currntLocation = mLastLocation;
                }
                if (googleApiClient != null)
                    startLocationUpdates();

            }
        }

        @Override
        public void onConnectionSuspended(int i) {

        }


        protected synchronized void buildGoogleApiClient() {
            googleApiClient = new GoogleApiClient.Builder(this)
                    .addConnectionCallbacks(this)
                    .addOnConnectionFailedListener(this)
                    .addApi(LocationServices.API)
                    .build();


        }


        @Override
        public void onConnectionFailed(ConnectionResult connectionResult) {

            Log.d(TAG, "failed.....");
        }


        public class GetLocationRef implements com.google.android.gms.location.LocationListener {
            @Override
            public void onLocationChanged(Location location) {

                // Log.d("test","location changes.");
                if (location != null) {
                    Util.currntLocation = location;
                }
            }


        }


    }

这是我存储当前位置的 Util 类:

package com.anonymous.attendancemange.util;

import android.location.Location;

/**
 * Created by sos on 1/10/2016.
 */
public class Util {

    public static Location currntLocation;
}

只需在主要活动中添加以下行即可启动服务:

Intent intent = new Intent(MainActivity.this, MyService.class);
startService(intent);

以下是主文件:

<?xml version="1.0" encoding="utf-8"?>
<manifest xmlns:android="http://schemas.android.com/apk/res/android"
    package="com.anonymous.attendancemange" >

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

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



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

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


        <activity android:name="com.anonymous.attendancemange.ActivityLogin"
            android:screenOrientation="portrait"
            ></activity>


        <activity android:name="com.anonymous.attendancemange.MainActivity"
            android:screenOrientation="portrait"
            ></activity>

        <activity android:name=".ActivityOfficessCheckin"
            android:screenOrientation="portrait"
            ></activity>

        <service android:name=".servicess.MyService"></service>
    </application>

</manifest>

以及您希望在哪里使用所需的当前位置:

if(Util.currntLocation!=null){

   Log.d("test", "lat:" + Util.currntLocation.getLatitude() + "Long:" +       Util.currntLocation.getLongitude());

}

【讨论】:

  • 非常感谢:),我正在尝试实现它,但我正在寻找一种等待服务结束以使用 currentLocation 的方法。我正在通过 util 类调用服务,它由 Activity 调用。实际上 currentLocation 之前使用它来表示赞赏。有什么建议吗?再次感谢。
  • 位置 mLastLocation = LocationServices.FusedLocationApi.getLastLocation(googleApiClient);总是为空..
猜你喜欢
  • 1970-01-01
  • 2011-07-15
  • 2015-03-26
  • 2018-02-08
  • 1970-01-01
  • 2015-05-14
  • 2015-05-17
  • 2012-08-19
  • 2021-01-17
相关资源
最近更新 更多