如何在另一个活动中获取谷歌地图实时位置

时间:2016-06-17 14:26:25

标签: android google-maps google-api-client

假设我可以在一个片段中实时获取我的位置,现在我有另一个活动,我需要从这个mapTabFragment获取实时位置,我该怎么做。因为我已经在这个片段中有我的实时位置所以我想做的就是在我的另一个活动中使用这个结果。我只需要latlng ......

public class MapTabFragment extends Fragment implements
        GoogleApiClient.ConnectionCallbacks,
        GoogleApiClient.OnConnectionFailedListener, LocationListener{

    GoogleMap mGoogleMap;
    LocationRequest mLocationRequest;
    GoogleApiClient mGoogleApiClient;
    Location mLastLocation;
    List<ParseObject> parseObjectsList;
    ArrayList<Post> postsList;
    private static int REQUEST_CODE_RECOVER_PLAY_SERVICES = 200;


    @Override
    public View onCreateView(LayoutInflater inflater, ViewGroup container,
                             Bundle savedInstanceState) {
        View v = inflater.inflate(R.layout.fragment_map_tab, container, false);

        if (android.os.Build.VERSION.SDK_INT >= Build.VERSION_CODES.M) {
            checkLocationPermission();
        }
        FragmentManager fm = getChildFragmentManager();
        SupportMapFragment mapFragment =
                (SupportMapFragment) fm.findFragmentById(R.id.mapView);
     //   mapFragment.getMapAsync(this);
        return v;
    }


    @Override
    public void onCreate(@Nullable Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        postsList = new ArrayList<>();

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

        //connect here or at onStart()?
        mGoogleApiClient.connect();

       // buildGoogleApiClient();
        if(checkGooglePlayServices()){
            buildGoogleApiClient();
        }
        createLocationRequest();
    }

    protected synchronized void buildGoogleApiClient() {
        mGoogleApiClient = new GoogleApiClient.Builder(getContext())
                .addConnectionCallbacks(this)
                .addOnConnectionFailedListener(this)
                .addApi(LocationServices.API)
                .build();
        //  mGoogleApiClient.connect();
    }


    private boolean checkGooglePlayServices() {
        int checkGooglePlayServices = GooglePlayServicesUtil
                .isGooglePlayServicesAvailable(getContext());
        if (checkGooglePlayServices != ConnectionResult.SUCCESS) {
            /*
            * google play services is missing or update is required
            *  return code could be
            * SUCCESS,
            * SERVICE_MISSING, SERVICE_VERSION_UPDATE_REQUIRED,
            * SERVICE_DISABLED, SERVICE_INVALID.
            */
            GooglePlayServicesUtil.getErrorDialog(checkGooglePlayServices,
                    getActivity(), REQUEST_CODE_RECOVER_PLAY_SERVICES).show();

            return false;
        }

        return true;

    }

    @Override
    public void onActivityResult(int requestCode, int resultCode, Intent data) {
        if (requestCode == REQUEST_CODE_RECOVER_PLAY_SERVICES) {

            if (resultCode == Activity.RESULT_OK) {
                // Make sure the app is not already connected or attempting to connect
                if (!mGoogleApiClient.isConnecting() &&
                        !mGoogleApiClient.isConnected()) {
                    mGoogleApiClient.connect();
                }
            } else if (resultCode == Activity.RESULT_CANCELED) {
                Toast.makeText(getContext(), "Google Play Services must be installed.",
                        Toast.LENGTH_SHORT).show();
                //finish();

            }
        }
    }



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

        if(mGoogleApiClient.isConnected()){
            Log.d("map","Google_Api_Client: It was connected on (onConnected) function, working as it should.");
        }
        else{
            Log.d("map failed","Google_Api_Client: It was NOT connected on (onConnected) function, It is definetly bugged.");
        }

        if (ActivityCompat.checkSelfPermission(getContext(),
                Manifest.permission.ACCESS_FINE_LOCATION)
                == PackageManager.PERMISSION_GRANTED) {
            startLocationUpdates();
        }

//        mLastLocation = LocationServices.FusedLocationApi.getLastLocation(
//                mGoogleApiClient);
        if (mLastLocation != null) {
            Toast.makeText(getContext(), "Latitude:" + mLastLocation.getLatitude()+", Longitude:"+mLastLocation.getLongitude(),Toast.LENGTH_LONG).show();
        }

    }

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

    protected void startLocationUpdates(){
        LocationServices.FusedLocationApi.requestLocationUpdates(
                mGoogleApiClient, mLocationRequest, this);
    }

    @Override
    public void onConnectionSuspended(int i) {

    }

    @Override
    public void onLocationChanged(Location location) {
        mLastLocation = location;
        Toast.makeText(getContext(), "Latitude:" + mLastLocation.getLatitude()+", Longitude:"+mLastLocation.getLongitude(),Toast.LENGTH_LONG).show();
    }




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

    protected void stopLocationUpdates(){
        if (mGoogleApiClient != null) {
            LocationServices.FusedLocationApi.removeLocationUpdates(
                    mGoogleApiClient, this);
        }
    }

    @Override
    public void onStop() {
        super.onStop();
        if (mGoogleApiClient != null) {
            mGoogleApiClient.disconnect();
        }
    }

//    @Override
//    public void onMapReady(GoogleMap googleMap) {
//        mGoogleMap = googleMap;
//        mGoogleMap.setMyLocationEnabled(true);
//        mGoogleMap.setMapType(GoogleMap.MAP_TYPE_NORMAL);
//        mGoogleMap.getUiSettings().setZoomControlsEnabled(true);
//
//        LocationManager locationManager = (LocationManager) getActivity().
//                getSystemService(getContext().LOCATION_SERVICE);
//        Criteria criteria = new Criteria();
//        Location location = locationManager.getLastKnownLocation(locationManager.getBestProvider(criteria, false));
//        if (location != null) {
//            mGoogleMap.animateCamera(CameraUpdateFactory.newLatLngZoom(
//                    new LatLng(location.getLatitude(), location.getLongitude()), 15.0f));
//            //     mGoogleMap.addMarker(new MarkerOptions().position(new LatLng(location.getLatitude(),location.getLongitude())).title("hoodmark"));
//
//            //Initialize Google Play Services
//            if (android.os.Build.VERSION.SDK_INT >= Build.VERSION_CODES.M) {
//                if (ContextCompat.checkSelfPermission(getActivity(),
//                        Manifest.permission.ACCESS_FINE_LOCATION)
//                        == PackageManager.PERMISSION_GRANTED) {
//                    buildGoogleApiClient();
//                    mGoogleMap.setMyLocationEnabled(true);
//                }
//            } else {
//                buildGoogleApiClient();
//                mGoogleMap.setMyLocationEnabled(true);
//            }
//
//        }
//        new GetPostsDataTask().execute();
//    }

    @Override
    public void onStart() {
        super.onStart();
  //      mGoogleApiClient.connect();
    }


    @Override
    public void onPause() {
        super.onPause();
        stopLocationUpdates();
    }

    public static final int MY_PERMISSIONS_REQUEST_LOCATION = 99;

    public boolean checkLocationPermission() {
        if (ContextCompat.checkSelfPermission(getActivity(),
                Manifest.permission.ACCESS_FINE_LOCATION)
                != PackageManager.PERMISSION_GRANTED) {

            // Should we show an explanation?
            if (ActivityCompat.shouldShowRequestPermissionRationale(getActivity(),
                    Manifest.permission.ACCESS_FINE_LOCATION)) {
                // Show an expanation to the user *asynchronously* -- don't block
                // this thread waiting for the user's response! After the user
                // sees the explanation, try again to request the permission.

                //Prompt the user once explanation has been shown
                ActivityCompat.requestPermissions(getActivity(),
                        new String[]{Manifest.permission.ACCESS_FINE_LOCATION},
                        MY_PERMISSIONS_REQUEST_LOCATION);

            } else {
                // No explanation needed, we can request the permission.
                ActivityCompat.requestPermissions(getActivity(),
                        new String[]{Manifest.permission.ACCESS_FINE_LOCATION},
                        MY_PERMISSIONS_REQUEST_LOCATION);
            }
            return false;
        } else {
            return true;
        }
    }

    @Override
    public void onRequestPermissionsResult(int requestCode, @NonNull String[] permissions, @NonNull 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.
                    if (ContextCompat.checkSelfPermission(getActivity(),
                            Manifest.permission.ACCESS_FINE_LOCATION)
                            == PackageManager.PERMISSION_GRANTED) {

                        if (mGoogleApiClient == null) {
                            buildGoogleApiClient();
                        }
                        mGoogleMap.setMyLocationEnabled(true);
                    }

                } else {
                    // permission denied, boo! Disable the
                    // functionality that depends on this permission.
                    Toast.makeText(getContext(), "permission denied", Toast.LENGTH_LONG).show();
                }
                return;
            }

        }
    }

    /***
     * Mango code to handle getting posts Top1000 in area based on likes
     * as well as getting users location and
     */
    /**
     * TODO: query parse for the top 100 posts
     * @param longitude
     * @param latitude
     * @return
     */

    public ArrayList<ParseObject> getTop100PostsForLocation(double longitude, double latitude) {
        ArrayList<ParseObject> top100Posts = new ArrayList<>();

        return top100Posts;
    }

logcat的:

java.lang.IllegalStateException: GoogleApiClient is not connected yet.
at com.google.android.gms.common.api.internal.zzj.zzb(Unknown Source)
at com.google.android.gms.location.internal.zzd.requestLocationUpdates(Unknown Source)
at com.mangoconcepts.hoodmarkandroid.fragments.MapTabFragment.startLocationUpdates(MapTabFragment.java:203)
at com.mangoconcepts.hoodmarkandroid.fragments.MapTabFragment.onConnected(MapTabFragment.java:184)
at com.google.android.gms.common.internal.zzk.zzk(Unknown Source)
at com.google.android.gms.common.api.internal.zzj.zzi(Unknown Source)
at com.google.android.gms.common.api.internal.zzh.zzpx(Unknown Source)
at com.google.android.gms.common.api.internal.zzh.onConnected(Unknown Source)
at com.google.android.gms.common.api.internal.zzl.onConnected(Unknown Source)
at com.google.android.gms.common.api.internal.zzc.onConnected(Unknown Source)
at com.google.android.gms.common.internal.zzj$zzg.zzqL(Unknown Source)
at com.google.android.gms.common.internal.zzj$zza.zzc(Unknown Source)
at com.google.android.gms.common.internal.zzj$zza.zzw(Unknown Source)
at com.google.android.gms.common.internal.zzj$zzc.zzqN(Unknown Source)
at com.google.android.gms.common.internal.zzj$zzb.handleMessage(Unknown Source)
at android.os.Handler.dispatchMessage(Handler.java:102)
at android.os.Looper.loop(Looper.java:145)
at android.app.ActivityThread.main(ActivityThread.java:5835)
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:1399)
at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:1194)

1 个答案:

答案 0 :(得分:0)

如果启用了,则必须检查您的Google客户端API。请查看此信息以获取更多信息:https://developers.google.com/api-client-library/java/google-api-java-client/android

相关问题