1

融合されたロケーション APIを介してロケーションを取得しようとしています。アプリ全体で使用できるように、ヘルパー クラスを構築しようとしました。

コード:

import com.google.android.gms.common.ConnectionResult;
import com.google.android.gms.common.GooglePlayServicesUtil;
import com.google.android.gms.common.api.GoogleApiClient;
import com.google.android.gms.common.api.GoogleApiClient.ConnectionCallbacks;
import com.google.android.gms.common.api.GoogleApiClient.OnConnectionFailedListener;
import com.google.android.gms.location.LocationListener;
import com.google.android.gms.location.LocationRequest;
import com.google.android.gms.location.LocationServices;

import android.app.Activity;
import android.content.Context;
import android.location.Location;
import android.os.Bundle;
import android.util.Log;
import android.widget.Toast;

public class GPSTracker2  implements ConnectionCallbacks,
        OnConnectionFailedListener,LocationListener {
    // LogCat tag
    private static final String TAG = GPSTracker2.class.getSimpleName();

    private final static int PLAY_SERVICES_RESOLUTION_REQUEST = 1000;

    private Location mLastLocation;

    // Google client to interact with Google API
    private GoogleApiClient mGoogleApiClient;

    // boolean flag to toggle periodic location updates
    private boolean mRequestingLocationUpdates = false;

    private LocationRequest mLocationRequest;

    // Location updates intervals in sec
    private static int UPDATE_INTERVAL = 1000; // 10 sec
    private static int FATEST_INTERVAL = 500; // 5 sec
    private static int DISPLACEMENT = 10; // 10 meters

   Context context;
// flag for GPS status
    boolean canGetLocation = true;

    double latitude,longitude;

        public GPSTracker2(Context context) {
            // TODO Auto-generated constructor stub
              // First we need to check availability of play services
            this.context=context;
             createLocationRequest();
            if (checkPlayServices()) {

                // Building the GoogleApi client
                buildGoogleApiClient();
            }

            if (mGoogleApiClient != null) {
                mGoogleApiClient.connect();
            }
            // Show location button click listener
        }





    /**
     * Method to display the location on UI
     * */
    /*private void displayLocation() {

        mLastLocation = LocationServices.FusedLocationApi
                .getLastLocation(mGoogleApiClient);

        if (mLastLocation != null) {
            double latitude = mLastLocation.getLatitude();
            double longitude = mLastLocation.getLongitude();

        } else {


        }
    }*/

        /**
         * Method to display the location on UI
         * */
        private void displayLocation() {

            mLastLocation = LocationServices.FusedLocationApi
                    .getLastLocation(mGoogleApiClient);

            if (mLastLocation != null) {
                double latitude = mLastLocation.getLatitude();
                double longitude = mLastLocation.getLongitude();

            Toast.makeText(context,latitude+" "+longitude,Toast.LENGTH_LONG).show();

            } else {


            }
        }
    /**
     * Function to get latitude
     * */
    public double getLatitude(){


         mLastLocation = LocationServices.FusedLocationApi
                    .getLastLocation(mGoogleApiClient);

            if (mLastLocation != null) {
                this.canGetLocation = true;
               double latitude = mLastLocation.getLatitude();
               System.out.println("In GetLat==>"+latitude);
               return latitude;
            }else{
                System.out.println("last known null");
                return 0.0;
            }

    }

    /**
     * Function to get longitude
     * */
    public double getLongitude(){

         mLastLocation = LocationServices.FusedLocationApi
                    .getLastLocation(mGoogleApiClient);

            if (mLastLocation != null) {
                this.canGetLocation = true;
               longitude = mLastLocation.getLongitude();
               System.out.println("In Getlong==>"+longitude);
            }
            return longitude;
    }

    /**
     * Creating google api client object
     * */
    protected synchronized void buildGoogleApiClient() {
        mGoogleApiClient = new GoogleApiClient.Builder(context)
                .addConnectionCallbacks(this)
                .addOnConnectionFailedListener(this)
                .addApi(LocationServices.API).build();
    }

    /**
     * Method to verify google play services on the device
     * */
    private boolean checkPlayServices() {
        int resultCode = GooglePlayServicesUtil
                .isGooglePlayServicesAvailable(context);
        if (resultCode != ConnectionResult.SUCCESS) {
            if (GooglePlayServicesUtil.isUserRecoverableError(resultCode)) {
                GooglePlayServicesUtil.getErrorDialog(resultCode, (Activity) context,
                        PLAY_SERVICES_RESOLUTION_REQUEST).show();
            } else {
                Toast.makeText(context,
                        "context device is not supported.", Toast.LENGTH_LONG)
                        .show();
                //finish();
            }
            return false;
        }
        return true;
    }

    /**
     * Creating location request object
     * */
    protected void createLocationRequest() {
        mLocationRequest = new LocationRequest();
        mLocationRequest.setInterval(UPDATE_INTERVAL);
        mLocationRequest.setFastestInterval(FATEST_INTERVAL);
        mLocationRequest.setPriority(LocationRequest.PRIORITY_HIGH_ACCURACY);
        mLocationRequest.setSmallestDisplacement(DISPLACEMENT);
    }

    /**
     * Starting the location updates
     * */
    protected void startLocationUpdates() {

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

    }

    /**
     * Stopping location updates
     */
    protected void stopLocationUpdates() {
        LocationServices.FusedLocationApi.removeLocationUpdates(
                mGoogleApiClient, this);
    }

    /**
     * Google api callback methods
     */
    @Override
    public void onConnectionFailed(ConnectionResult result) {
        Log.i(TAG, "Connection failed: ConnectionResult.getErrorCode() = "
                + result.getErrorCode());
    }

    @Override
    public void onConnected(Bundle arg0) {

        // Once connected with google api, get the location
      //  displayLocation();
        //getLatitude();
        //getLongitude();
        displayLocation();
 System.out.println("On Connected");
        if (mRequestingLocationUpdates) {
            startLocationUpdates();
        }
    }

    @Override
    public void onConnectionSuspended(int arg0) {
        mGoogleApiClient.connect();
    }

    @Override
    public void onLocationChanged(Location location) {
        // Assign the new location
        mLastLocation = location;

        Toast.makeText(context, "Location changed!",
                Toast.LENGTH_SHORT).show();
        displayLocation();
        // Displaying the new location on UI
       // displayLocation();
       // getLatitude();
     //   getLongitude();
    }

    /**
     * Function to check GPS/wifi enabled
     * @return boolean
     * */
    public boolean canGetLocation() {
        return this.canGetLocation;
    }
}

私はこれを次のように使用しようとしています:

CallingClass.java _

GPSTracker2 gps=new GPSTracker2(SettingsActivity.this);
        if(gps.canGetLocation())
        {
            System.out.println("lat-->"+gps.getLatitude()+" long===>"+gps.getLongitude());
        }else{
            showSettingsAlert(true);
        }

問題: メソッドgps.getLatitude()およびgps.getLongitude()0.0を返します。ただし、トースト メッセージ ( displayLocation(); メソッド内) では、緯度と経度が完全に取得されます。

したがって、アプリケーションをデバッグしたところ、GpsTracker2 クラスのコンストラクターを呼び出した後、制御が呼び出し元のクラスに戻り、呼び出し元のクラスの onCreate を終了した後、GoogleApiclient が接続されていることがわかりました。呼び出しクラスのonCreate() 、したがって結果。

どうすればこの問題を克服できますか??

4

2 に答える 2