根据片段中的位置获取数据

时间:2018-10-07 12:37:42

标签: android

我正在制作一个应用程序,其中根据用户位置获取数据。我使用底部导航栏,并具有三个名为Home,Notifications和Account的片段。在Home片段中,我实现了FusedLocation Api以获取用户位置,但是问题是应用首次启动时未获得位置信息。当我更改导航并返回到首页导航时,或在启动活动后,单击首页导航,即可轻松获取位置。 这里有什么问题?有人让我知道。

下面是我的代码。

MainActivity.java

BottomNavigationView bottomBar;

@Override
protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.activity_main);
    Toolbar toolbar = (Toolbar) findViewById(R.id.toolbar);
    setSupportActionBar(toolbar);

    bottomBar = findViewById(R.id.bottomBar);   

     Home fragment = new Home();
     FragmentTransaction fragmentTransaction = 
     getSupportFragmentManager().beginTransaction();
     fragmentTransaction.replace(R.id.frame,fragment);
     fragmentTransaction.commit();

    bottomBar.setOnNavigationItemSelectedListener(new 
    BottomNavigationView.OnNavigationItemSelectedListener() {

     @Override
     public boolean onNavigationItemSelected(@NonNull MenuItem menuItem) 
       {

            switch(menuItem.getItemId()){

                  case R.id.navigation_home:

                  Home fragment = new Home();
                  FragmentTransaction fragmentTransaction = 
                  getSupportFragmentManager().beginTransaction();
                  fragmentTransaction.replace(R.id.frame,fragment);
                  fragmentTransaction.commit();

                  return true;

                case R.id.navigation_notifications:

                Notification fragment_notif = new Notification();
                FragmentTransaction fragmentTransaction1 = 
                getSupportFragmentManager().beginTransaction();
                fragmentTransaction1.replace(R.id.frame,fragment_notif);
                fragmentTransaction1.commit();

                return true;

                case R.id.navigation_account:

                Account fragment_acc = new Account();
                FragmentTransaction fragmentTransaction2 = 
                getSupportFragmentManager().beginTransaction();
                fragmentTransaction2.replace(R.id.frame,fragment_acc);
                fragmentTransaction2.commit();

                return true;

            }

            return false;
        }
    });
 }

Home.java

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

TextView fragText;
GoogleApiClient mGoogleApiClient;
LocationRequest mLocationRequest;
String str1;
ProgressBar progressBar;

public Home() {

}

@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);
   progressBar = view.findViewById(R.id.progressBar);

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

    mLocationRequest = LocationRequest.create();
    mLocationRequest.setPriority(LocationRequest.PRIORITY_HIGH_ACCURACY);
    mLocationRequest.setInterval(1000);

    if(Build.VERSION.SDK_INT >= Build.VERSION_CODES.M) {

        if (ActivityCompat.checkSelfPermission(getActivity(), Manifest.permission.ACCESS_COARSE_LOCATION) != PackageManager.PERMISSION_GRANTED){

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

        } else {

            LocationServices.FusedLocationApi.requestLocationUpdates(mGoogleApiClient, mLocationRequest, this);
        }

    }
    else{

        LocationServices.FusedLocationApi.requestLocationUpdates(mGoogleApiClient, mLocationRequest, this);

    }
}

@Override
public void onConnectionSuspended(int i) {

}

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

}

@Override
public void onLocationChanged(Location location) {

    progressBar.setVisibility(View.INVISIBLE);

    str1 = hereLocation(location.getLatitude(),location.getLongitude());

    fragText.setText(str1);

}

@Override
public void onRequestPermissionsResult(int requestCode, @NonNull String[] permissions, @NonNull int[] grantResults) {
    super.onRequestPermissionsResult(requestCode, permissions, grantResults);

    if(grantResults.length>0 && grantResults[0] == PackageManager.PERMISSION_GRANTED){


        if(ContextCompat.checkSelfPermission(getActivity(),Manifest.permission.ACCESS_COARSE_LOCATION)
                == PackageManager.PERMISSION_GRANTED){

            LocationServices.FusedLocationApi.requestLocationUpdates(mGoogleApiClient, mLocationRequest, this);

        }
        else{

            progressBar.setVisibility(View.INVISIBLE);

            TastyToast.makeText(getActivity(),"Unable to get location",TastyToast.LENGTH_SHORT,TastyToast.ERROR).show();
        }

    }
}

private String hereLocation(double lat, double lon){

    String city = "";

    Geocoder geo = new Geocoder(getContext(), Locale.getDefault());
    List<Address> addresses;

    try {

        addresses = geo.getFromLocation(lat,lon,10);

        if(addresses.size()>0){

            for (Address adr: addresses){

                if(adr.getLocality()!=null && adr.getLocality().length()>0){

                    city = adr.getLocality();
                }
            }
        }
    }
    catch (IOException e) {
        e.printStackTrace();
    }

    return city;

}

请仔细阅读以上代码,让我现在为什么要面对这个问题。

谢谢

0 个答案:

没有答案