片段首次启动时未显示用户位置

时间:2018-10-11 15:09:48

标签: android android-fragments

在我的应用程序中,我有2个名为Home和account的片段。在Home片段中,我正在尝试使用Fused location api来获取用户的最后一个已知位置。问题是应用程序首次启动时不会获取用户位置以及我切换时在片段之间,返回到Home片段,它显示位置。 这是我的首页片段代码。

Home.java

public class Home extends Fragment implements GoogleApiClient.OnConnectionFailedListener,GoogleApiClient.ConnectionCallbacks,
                                            com.google.android.gms.location.LocationListener{

TextView fragText;
GoogleApiClient mGoogleApiClient;
LocationRequest mLocationRequest;
Location mLocation;

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

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

   fragText = view.findViewById(R.id.fragText);

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


       mGoogleApiClient = new GoogleApiClient.Builder(getActivity())
                .addConnectionCallbacks(this)
                .addOnConnectionFailedListener(this)
                .addApi(LocationServices.API)
                .build();

    return view;

     }

   @Override
   public void onStart() {
    super.onStart();

       mGoogleApiClient.connect();
     }



   @Override
   public void onStop() {
    super.onStop();

    if(mGoogleApiClient.isConnected()){

        mGoogleApiClient.disconnect();

    }

  }
@Override
public void onConnected(@Nullable Bundle bundle) {

        mLocation = LocationServices.FusedLocationApi.getLastLocation(mGoogleApiClient);

                if (mLocation != null) {

                   String str1 = hereLocation(mLocation.getLatitude(), mLocation.getLongitude());
                    fragText.setText(str1);



   }

}

  @Override
public void onConnectionSuspended(int i) {

}

@Override
public void onConnectionFailed(@NonNull ConnectionResult connectionResult) {

}

请让我知道我在上面的代码中做错了什么。

谢谢

0 个答案:

没有答案