无法在Fragment中找到当前位置

时间:2016-11-11 05:19:22

标签: android location google-places-api

我正在尝试使用Places API获取当前位置。 请找到以下代码

 public class PlaceFragment extends Fragment implements View.OnClickListener {

private Button currentLocation;

private View myFragmentView;

private GoogleApiClient mGoogleApiClient;

private static final int MY_PERMISSIONS_REQUEST_LOCATION = 101;


public PlaceFragment() {
    // Required empty public constructor
}


@Override
public void onCreate(Bundle savedInstanceState) {

    super.onCreate(savedInstanceState);
    mGoogleApiClient = new GoogleApiClient
            .Builder(getActivity())
            .addApi(Places.GEO_DATA_API)
            .addApi(Places.PLACE_DETECTION_API)
            .build();

}

@Override
public void onStart() {

    super.onStart();
    if (mGoogleApiClient != null)
        mGoogleApiClient.connect();

}

@Override
public void onStop() {

    if (mGoogleApiClient != null && mGoogleApiClient.isConnected()) {
        mGoogleApiClient.disconnect();
    }
    super.onStop();

}

@Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
                         Bundle savedInstanceState) {
    // Inflate the layout for this fragment
    myFragmentView = inflater.inflate(R.layout.fragment_place, container, false);

    currentLocation = (Button) myFragmentView.findViewById(R.id.currentLocation);
    currentLocation.setOnClickListener(this);

    return myFragmentView;
}

@Override
public void onClick(View v) {

    if (v.getId() == R.id.currentLocation) {

        int permissionCheck = ContextCompat.checkSelfPermission(getActivity(),
                Manifest.permission.ACCESS_FINE_LOCATION);

        if (permissionCheck != PackageManager.PERMISSION_GRANTED) {
            requestPermissions(new String[]{Manifest.permission.ACCESS_FINE_LOCATION}, MY_PERMISSIONS_REQUEST_LOCATION);
        } else {
            getCurrentLocation();
        }
    }
}


@Override
public void onRequestPermissionsResult(int requestCode,
                                       String permissions[], int[] grantResults) {
    switch (requestCode) {
        case MY_PERMISSIONS_REQUEST_LOCATION: {
            // If request is cancelled, the result arrays are empty.
            if (grantResults.length > 0
                    && grantResults[0] == PackageManager.PERMISSION_GRANTED) {

                // permission was granted, yay! Do the
                // contacts-related task you need to do.
                getCurrentLocation();

            } else {

                // permission denied, boo! Disable the
                // functionality that depends on this permission.
            }
            return;
        }

        // other 'case' lines to check for other
        // permissions this app might request
    }
}


private void getCurrentLocation() {

    PendingResult<PlaceLikelihoodBuffer> result = Places.PlaceDetectionApi.getCurrentPlace(mGoogleApiClient, null);
    result.setResultCallback(new ResultCallback<PlaceLikelihoodBuffer>() {
        @Override
        public void onResult(PlaceLikelihoodBuffer likelyPlaces) {

            PlaceLikelihood placeLikelihood = likelyPlaces.get(0);
            String content = "";
            if (placeLikelihood != null && placeLikelihood.getPlace() != null && !TextUtils.isEmpty(placeLikelihood.getPlace().getName()))
                content = "Most likely place: " + placeLikelihood.getPlace().getName() + "\n";
            if (placeLikelihood != null)
                content += "Percent change of being there: " + (int) (placeLikelihood.getLikelihood() * 100) + "%";
            System.out.println(content);

            likelyPlaces.release();
        }
    });
}
}

但我既没有得到权限对话也没有任何有效的当前位置,我尝试通过删除访问来提供访问权限。 这是我在监视器中得到的错误

 E/Places: Timed out waiting for a location for getCurrentPlace
 11-11 10:41:46.417 2591-2591/com.kumarpratik.WhatsAround E/UncaughtException: java.lang.IllegalStateException
                                                                              at com.google.android.gms.common.internal.zzac.zzbr(Unknown Source)
                                                                              at com.google.android.gms.common.data.zzc.zzfz(Unknown Source)
                                                                              at com.google.android.gms.common.data.zzc.<init>(Unknown Source)
                                                                              at com.google.android.gms.location.places.internal.zzt.<init>(Unknown Source)
                                                                              at com.google.android.gms.location.places.internal.zzn.<init>(Unknown Source)
                                                                              at com.google.android.gms.location.places.PlaceLikelihoodBuffer.get(Unknown Source)
                                                                              at com.kumarpratik.WhatsAround.fragment.PlaceFragment$1.onResult(PlaceFragment.java:147)
                                                                              at com.kumarpratik.WhatsAround.fragment.PlaceFragment$1.onResult(PlaceFragment.java:143)
                                                                              at com.google.android.gms.internal.zzqe$zza.zzb(Unknown Source)
                                                                              at com.google.android.gms.internal.zzqe$zza.handleMessage(Unknown Source)
                                                                              at android.os.Handler.dispatchMessage(Handler.java:102)
                                                                              at android.os.Looper.loop(Looper.java:135)
                                                                              at android.app.ActivityThread.main(ActivityThread.java:5292)
                                                                              at java.lang.reflect.Method.invoke(Native Method)
                                                                              at java.lang.reflect.Method.invoke(Method.java:372)
                                                                              at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:904)
                                                                              at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:699)
11-11 10:41:46.664 2591-2591/com.kumarpratik.WhatsAround E/AndroidRuntime: FATAL EXCEPTION: main
                                                                       Process: com.kumarpratik.WhatsAround, PID: 2591
                                                                       java.lang.IllegalStateException
                                                                           at com.google.android.gms.common.internal.zzac.zzbr(Unknown Source)
                                                                           at com.google.android.gms.common.data.zzc.zzfz(Unknown Source)
                                                                           at com.google.android.gms.common.data.zzc.<init>(Unknown Source)
                                                                           at com.google.android.gms.location.places.internal.zzt.<init>(Unknown Source)
                                                                           at com.google.android.gms.location.places.internal.zzn.<init>(Unknown Source)
                                                                           at com.google.android.gms.location.places.PlaceLikelihoodBuffer.get(Unknown Source)
                                                                           at com.kumarpratik.WhatsAround.fragment.PlaceFragment$1.onResult(PlaceFragment.java:147)
                                                                           at com.kumarpratik.WhatsAround.fragment.PlaceFragment$1.onResult(PlaceFragment.java:143)
                                                                           at com.google.android.gms.internal.zzqe$zza.zzb(Unknown Source)
                                                                           at com.google.android.gms.internal.zzqe$zza.handleMessage(Unknown Source)
                                                                           at android.os.Handler.dispatchMessage(Handler.java:102)
                                                                           at android.os.Looper.loop(Looper.java:135)
                                                                           at android.app.ActivityThread.main(ActivityThread.java:5292)
                                                                           at java.lang.reflect.Method.invoke(Native Method)
                                                                           at java.lang.reflect.Method.invoke(Method.java:372)
                                                                           at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:904)
                                                                           at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:699)
11-11 10:42:33.120 18739-3697/? E/GeofenceHelper: Failed: remove geofences by PendingIntent

这是我的清单文件

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

<uses-permission android:name="android.permission.ACCESS_FINE_LOCATION" />
<uses-permission android:name="com.google.android.providers.gsf.permission.READ_GSERVICES" />
<uses-permission android:name="android.permission.INTERNET" />

<uses-feature
    android:glEsVersion="0x00020000"
    android:required="true"/>

<application android:name=".common.AppController" android:allowBackup="true" android:debuggable="true"
android:icon="@mipmap/ic_launcher" android:label="@string/app_name" android:supportsRtl="true"
android:theme="@style/MyMaterialTheme">
<meta-data android:name="com.google.android.gms.version" android:value="@integer/google_play_services_version" />
<meta-data android:name="com.google.android.geo.API_KEY" android:value="@string/googlekey" />

<activity android:name=".activity.MainActivity" android:label="@string/title_activity_welcome"
    android:launchMode="standard" android:theme="@style/MyMaterialTheme" />
<activity android:name=".activity.IntroActivity" android:theme="@style/MyMaterialTheme">
    <intent-filter>
        <action android:name="android.intent.action.MAIN" />

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

    <!-- Parent activity meta-data to support 4.0 and lower -->
    <meta-data android:name="android.support.PARENT_ACTIVITY" android:value="com.kumarpratik.WhatsAround.activity.MainActivity" />
</activity>

修改

我在onResult()

中获得PlaceLikelihoodBuffer {status = Status {statusCode = ERROR,resolution = null},attributions = null}

4 个答案:

答案 0 :(得分:2)

好的,我终于得到了它的工作,如果有人觉得有用的话就贴出来

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

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

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

        if (!checkGPS && !checkNetwork) {
            Toast.makeText(mContext, "No Service Provider Available", Toast.LENGTH_SHORT).show();
        } else {
            this.canGetLocation = true;
            // First get location from Network Provider
            if (checkNetwork) {
                Toast.makeText(mContext, "Network", Toast.LENGTH_SHORT).show();

                try {
                    locationManager.requestLocationUpdates(
                            LocationManager.NETWORK_PROVIDER,
                            MIN_TIME_BW_UPDATES,
                            MIN_DISTANCE_CHANGE_FOR_UPDATES, this);
                    Log.d("Network", "Network");
                    if (locationManager != null) {
                        loc = locationManager
                                .getLastKnownLocation(LocationManager.NETWORK_PROVIDER);

                    }

                    if (loc != null) {
                        latitude = loc.getLatitude();
                        longitude = loc.getLongitude();
                    }
                } catch (SecurityException e) {

                }
            }
        }
        // if GPS Enabled get lat/long using GPS Services
        if (checkGPS) {
            Toast.makeText(mContext, "GPS", Toast.LENGTH_SHORT).show();
            if (loc == null) {
                try {
                    locationManager.requestLocationUpdates(
                            LocationManager.GPS_PROVIDER,
                            MIN_TIME_BW_UPDATES,
                            MIN_DISTANCE_CHANGE_FOR_UPDATES, this);
                    Log.d("GPS Enabled", "GPS Enabled");
                    if (locationManager != null) {
                        loc = locationManager
                                .getLastKnownLocation(LocationManager.GPS_PROVIDER);
                        if (loc != null) {
                            latitude = loc.getLatitude();
                            longitude = loc.getLongitude();
                        }
                    }
                } catch (SecurityException e) {

                }
            }
        }

答案 1 :(得分:1)

当您和您的相关人员使用不同版本的Google Play服务 - GPS时,就会发生这种情况。因此,您需要将它们更新为相同版本,或者只是将项目更新为最新版本。首先,检查Build Gradle文件以包含与Google Play依赖关系相关的错误警告。并尝试更新它!

其中一个错误:

  

任务执行失败':app:processDebugGoogleServices'。请   通过更新版本来修复版本冲突   google-services插件(有关最新版本的信息是   可在此处获得)或将com.google.android.gms的版本更新为   8.3.0。

    /*
     * Update GPA regarding to issue with
     * conflict google services dependencies!
     */
    compile 'com.google.android.gms:play-services-base:9.6.1'
    // Google Play Services Maps
    compile 'com.google.android.gms:play-services-maps:9.6.1'

答案 2 :(得分:1)

实施&amp;注册googleapi连接侦听器并覆盖onLocationChange回调以获取位置更新

答案 3 :(得分:1)

您无法在清单文件中提供相同的权限。还可以在启用/禁用选项中检查GCM项目。检查以下链接以提供有关地图的信息。

http://wptrafficanalyzer.in/blog/showing-current-location-in-google-maps-using-api-v2-with-supportmapfragment/