2016-11-11 32 views
7

我想使用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> 

編輯

我越來越PlaceLikelihoodBuffer {狀態=狀態{的StatusCode = ERROR,分辨率= NULL},歸因= NULL}在onResult()

回答

1

好吧,我終於得到了它的工作,如果有人發現了它有用

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) { 

       } 
      } 
     } 
+0

感謝上帝!你是一個拯救生命的人。像魅力一樣工作。 –

+0

很高興幫助你 – Pratik

1

它時,你和你的依賴使用不同版本的情況Google Play服務 - GPS。所以你需要將它們更新到相同的版本,或者只是在項目中更新到最新版本。首先,請檢查您的Build Gradle文件是否包含與Google Play Dependencies相關的錯誤警告。並嘗試更新它!

一個錯誤:

Execution failed for task ':app:processDebugGoogleServices'. Please fix the version conflict either by updating the version of the google-services plugin (information about the latest version is available here) or updating the version of com.google.android.gms to 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' 
+0

這是沒有幫助張貼。我的gradle編譯了'com.google.android.gms:play-services:9.6.1',我添加了這個以及編譯'com.google.android.gms:play-services-maps:9.6.1'但仍然不工作。 – Pratik

+0

@Pratik請嘗試爲應用程序使用MultiDex選項。 – GensaGames

+0

使用它編譯'com.android.support:multidex:1.0.0' – Pratik

1

實施googleapi連接聽衆&寄存器,並覆蓋onLocationChange回調以獲取位置更新