2017-03-06 14 views
0

GPSのみを使用してlatlongを取得しようとしています。 NetworkManagerを使用している場合は、latlongが表示されますが、GPSを使用している場合はGPS_PROVIDERになります。nullの位置にあります。GPSを使用して位置を取得できません

GPS_PROVIDERを使用してGPSの位置を取得する方法を教えてください。

コード。

public class GPSTracker extends Service implements LocationListener { 

    private final Context mContext; 

    // flag for GPS status 
    boolean isGPSEnabled = false; 

    // flag for network status 
    boolean isNetworkEnabled = false; 

    // flag for GPS status 
    boolean canGetLocation = false; 

    Location location; // location 
    double latitude; // latitude 
    double longitude; // longitude 

    // The minimum distance to change Updates in meters 
    private static final long MIN_DISTANCE_CHANGE_FOR_UPDATES = 10; // 10 meters 

    // The minimum time between updates in milliseconds 
    private static final long MIN_TIME_BW_UPDATES = 1000 * 60 * 1; // 1 minute 

    // Declaring a Location Manager 
    protected LocationManager locationManager; 

    public GPSTracker(Context context) { 
     this.mContext = context; 
     getLocation(); 
    } 

    public Location getLocation() { 
     try { 
      locationManager = (LocationManager) mContext 
        .getSystemService(LOCATION_SERVICE); 

      // getting GPS status 
      isGPSEnabled = locationManager 
        .isProviderEnabled(LocationManager.GPS_PROVIDER); 

      // getting network status 
      /*isNetworkEnabled = locationManager 
        .isProviderEnabled(LocationManager.NETWORK_PROVIDER); 

*/ 
      if (!isGPSEnabled && !isNetworkEnabled) { 
       // no network provider is enabled 
      } else { 
       this.canGetLocation = true; 
       /*if (isNetworkEnabled) { 
        locationManager.requestLocationUpdates(
          LocationManager.NETWORK_PROVIDER, 
          MIN_TIME_BW_UPDATES, 
          MIN_DISTANCE_CHANGE_FOR_UPDATES, this); 
        Log.d("Network", "Network"); 
        if (locationManager != null) { 
         location = locationManager.getLastKnownLocation(LocationManager.NETWORK_PROVIDER); 
         if (location != null) { 
          latitude = location.getLatitude(); 
          longitude = location.getLongitude(); 
         } 
        } 
       }*/ 
       // if GPS Enabled get lat/long using GPS Services 
       if (isGPSEnabled) { 
        if (location == null) { 
         locationManager.requestLocationUpdates(
           LocationManager.GPS_PROVIDER, 
           MIN_TIME_BW_UPDATES, 
           MIN_DISTANCE_CHANGE_FOR_UPDATES, this); 
         Log.d("GPS Enabled", "GPS Enabled"); 
         if (locationManager != null) { 
          location = locationManager 
            .getLastKnownLocation(LocationManager.GPS_PROVIDER); 
          if (location != null) { 
           latitude = location.getLatitude(); 
           longitude = location.getLongitude(); 
          } 
         } 
        } 
       } 
      } 

     } catch (Exception e) { 
     } 
     return location; 
    } 

    /** 
    * Stop using GPS listener Calling this function will stop using GPS in your 
    * app. 
    * */ 
    public void stopUsingGPS() { 
     if (locationManager != null) { 
      locationManager.removeUpdates(GPSTracker.this); 
     } 
    } 

    /** 
    * Function to get latitude 
    * */ 
    public double getLatitude() { 
     if (location != null) { 
      latitude = location.getLatitude(); 
     } 
     // return latitude 
     return latitude; 
    } 

    /** 
    * Function to get longitude 
    * */ 
    public double getLongitude() { 
     if (location != null) { 
      longitude = location.getLongitude(); 
     } 

     // return longitude 
     return longitude; 
    } 

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

    /** 
    * Function to show settings alert dialog On pressing Settings button will 
    * lauch Settings Options 
    * */ 
    public void showSettingsAlert() { 
     AlertDialog.Builder alertDialog = new AlertDialog.Builder(mContext); 

     // Setting DialogHelp Title 
     alertDialog.setTitle("GPS is settings"); 

     // Setting DialogHelp Message 
     alertDialog 
       .setMessage("GPS is not enabled. Do you want to go to settings menu?"); 

     // On pressing Settings button 
     alertDialog.setPositiveButton("Settings", 
       new DialogInterface.OnClickListener() { 
        public void onClick(DialogInterface dialog, int which) { 
         Intent intent = new Intent(
           Settings.ACTION_LOCATION_SOURCE_SETTINGS); 
         mContext.startActivity(intent); 
        } 
       }); 

     // on pressing cancel button 
     alertDialog.setNegativeButton("Cancel", 
       new DialogInterface.OnClickListener() { 
        public void onClick(DialogInterface dialog, int which) { 
         dialog.cancel(); 
        } 
       }); 

     // Showing Alert Message 
     alertDialog.show(); 
    } 

    @Override 
    public void onLocationChanged(Location location) { 
     Log.d("location",location.getLatitude()+" "+location.getLongitude()); 

     float bestAccuracy = -1f; 
     if (location.getAccuracy() != 0.0f 
       && (location.getAccuracy() < bestAccuracy) || bestAccuracy == -1f) { 
      locationManager.removeUpdates(this); 
     } 
     bestAccuracy = location.getAccuracy(); 
     Log.d("location",location.getLatitude()+" "+location.getLongitude()); 
    } 

    @Override 
    public void onProviderDisabled(String provider) { 
    } 

    @Override 
    public void onProviderEnabled(String provider) { 
    } 

    @Override 
    public void onStatusChanged(String provider, int status, Bundle extras) { 
    } 

    @Override 
    public IBinder onBind(Intent arg0) { 
     return null; 
    } 

    public float getAccurecy() 
    { 
     return location.getAccuracy(); 
    } 

} 
+0

時にはそれが上...承認するonLocationChanged方法場所ショートーストを取得するための時間がかかるのを待ちます。場所の取得または不在 –

答えて

0
**FusedLocationProviderApi** 

    public class LocationActivity extends Activity implements 
      LocationListener,GoogleApiClient.ConnectionCallbacks,GoogleApiClient.OnConnectionFailedListener { 

private static final String TAG = "LocationActivity"; 
private static final long INTERVAL = 1000 * 10; 
private static final long FASTEST_INTERVAL = 1000 * 5; 
Button btnFusedLocation; 
TextView tvLocation; 
LocationRequest mLocationRequest; 
GoogleApiClient mGoogleApiClient; 
Location mCurrentLocation; 
String mLastUpdateTime; 

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

@Override 
protected void onCreate(Bundle savedInstanceState) { 
    super.onCreate(savedInstanceState); 
    Log.d(TAG, "onCreate ..............................."); 
    //show error dialog if GoolglePlayServices not available 
    if (!isGooglePlayServicesAvailable()) { 
     finish(); 
    } 
    createLocationRequest(); 
    mGoogleApiClient = new GoogleApiClient.Builder(this) 
      .addApi(LocationServices.API) 
      .addConnectionCallbacks(this) 
      .addOnConnectionFailedListener(this) 
      .build(); 

    setContentView(R.layout.activity_main); 
    tvLocation = (TextView) findViewById(R.id.tvLocation); 

    btnFusedLocation = (Button) findViewById(R.id.btnShowLocation); 
    btnFusedLocation.setOnClickListener(new View.OnClickListener() { 
     @Override 
     public void onClick(View arg0) { 
      updateUI(); 
     } 
    }); 

} 

@Override 
public void onStart() { 
    super.onStart(); 
    Log.d(TAG, "onStart fired .............."); 
    mGoogleApiClient.connect(); 
} 

@Override 
public void onStop() { 
    super.onStop(); 
    Log.d(TAG, "onStop fired .............."); 
    mGoogleApiClient.disconnect(); 
    Log.d(TAG, "isConnected ...............: " + mGoogleApiClient.isConnected()); 
} 

private boolean isGooglePlayServicesAvailable() { 
    int status = GooglePlayServicesUtil.isGooglePlayServicesAvailable(this); 
    if (ConnectionResult.SUCCESS == status) { 
     return true; 
    } else { 
     GooglePlayServicesUtil.getErrorDialog(status, this, 0).show(); 
     return false; 
    } 
} 

@Override 
public void onConnected(Bundle bundle) { 
    Log.d(TAG, "onConnected - isConnected ...............: " + mGoogleApiClient.isConnected()); 
    startLocationUpdates(); 
} 

protected void startLocationUpdates() { 
    PendingResult<Status> pendingResult = LocationServices.FusedLocationApi.requestLocationUpdates(
      mGoogleApiClient, mLocationRequest, this); 
    Log.d(TAG, "Location update started ..............: "); 
} 

@Override 
public void onConnectionSuspended(int i) { 

} 

@Override 
public void onConnectionFailed(ConnectionResult connectionResult) { 
    Log.d(TAG, "Connection failed: " + connectionResult.toString()); 
} 

@Override 
public void onLocationChanged(Location location) { 
    Log.d(TAG, "Firing onLocationChanged.............................................."); 
    mCurrentLocation = location; 
    mLastUpdateTime = DateFormat.getTimeInstance().format(new Date()); 
    updateUI(); 
} 

private void updateUI() { 
    Log.d(TAG, "UI update initiated ............."); 
    if (null != mCurrentLocation) { 
     String lat = String.valueOf(mCurrentLocation.getLatitude()); 
     String lng = String.valueOf(mCurrentLocation.getLongitude()); 
     tvLocation.setText("At Time: " + mLastUpdateTime + "\n" + 
       "Latitude: " + lat + "\n" + 
       "Longitude: " + lng + "\n" + 
       "Accuracy: " + mCurrentLocation.getAccuracy() + "\n" + 
       "Provider: " + mCurrentLocation.getProvider()); 
    } else { 
     Log.d(TAG, "location is null ..............."); 
    } 
} 

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

protected void stopLocationUpdates() { 
    LocationServices.FusedLocationApi.removeLocationUpdates(
      mGoogleApiClient, this); 
    Log.d(TAG, "Location update stopped ......................."); 
} 

@Override 
public void onResume() { 
    super.onResume(); 
    if (mGoogleApiClient.isConnected()) { 
     startLocationUpdates(); 
     Log.d(TAG, "Location update resumed ....................."); 
     } 
    } 
    } 








    <RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android" 
    xmlns:tools="http://schemas.android.com/tools" 
    android:layout_width="match_parent" 
    android:layout_height="match_parent" 
    android:paddingLeft="@dimen/activity_horizontal_margin" 
    android:paddingRight="@dimen/activity_horizontal_margin" 
    android:paddingTop="@dimen/activity_vertical_margin" 
    android:paddingBottom="@dimen/activity_vertical_margin" 
    tools:context=".LocationActivity" 
android:background="#ffffa6c7"> 

<TextView 
    android:text="@string/locationTxt" 
    android:layout_width="wrap_content" 
    android:layout_height="wrap_content" 
    android:id="@+id/textView" 
    android:layout_centerHorizontal="true" /> 

<Button 
    style="?android:attr/buttonStyleSmall" 
    android:layout_width="fill_parent" 
    android:layout_height="wrap_content" 
    android:text="Show Location" 
    android:id="@+id/btnShowLocation" 
    android:layout_toEndOf="@+id/textView" 
    android:layout_marginTop="53dp" 
    android:layout_below="@+id/textView" 
    android:layout_alignParentStart="true" 
    android:layout_centerHorizontal="true" 
    android:background="#ffff1a7c" 
    android:textColor="#ffffffff" /> 

    <TextView 
     android:layout_width="fill_parent" 
     android:layout_height="wrap_content" 
     android:id="@+id/tvLocation" 
     android:layout_alignParentBottom="true" 
     android:layout_marginBottom="134dp" 
     android:layout_alignParentEnd="true" /> 

    </RelativeLayout> 
関連する問題