2016-08-23 11 views
-2

GPSClassを場所に使用しましたが、私は自分の活動から呼び出していますが、常に場所がnullになります。私はnull値を得るか、なぜ私がGPSTracker アンドロイド活動の現在の位置を取得していません

このような
@Override 
public void onCreate(Bundle savedInstanceState) { 
    super.onCreate(savedInstanceState); 
    setContentView(R.layout.petlist); 
GPSTracker gps; 
    gps = new GPSTracker(PetList.this); 

    // check if GPS enabled 
    if(gps.canGetLocation()){ 

     double latitude = gps.getLatitude(); 
     double longitude = gps.getLongitude(); 

     // \n is for new line 
     Toast.makeText(getApplicationContext(), "Your Location is - \nLat: " + latitude + "\nLong: " + longitude, Toast.LENGTH_LONG).show(); 
    }else{ 
     // can't get location 
     // GPS or Network is not enabled 
     // Ask user to enable GPS/network in settings 
     gps.showSettingsAlert(); 
    } 
} 

を呼んでいる?私の活動にGPSClass

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; 
      // First get location from Network Provider 
      if (isNetworkEnabled) { 
       if (ContextCompat.checkSelfPermission(mContext, Manifest.permission.ACCESS_FINE_LOCATION) != PackageManager.PERMISSION_GRANTED && ContextCompat.checkSelfPermission(mContext, Manifest.permission.ACCESS_COARSE_LOCATION) != PackageManager.PERMISSION_GRANTED) { 
        // TODO: Consider calling 
        // ActivityCompat#requestPermissions 
        // here to request the missing permissions, and then overriding 
        // public void onRequestPermissionsResult(int requestCode, String[] permissions, 
        //           int[] grantResults) 
        // to handle the case where the user grants the permission. See the documentation 
        // for ActivityCompat#requestPermissions for more details. 
        ActivityCompat.requestPermissions((Activity) getApplicationContext(), new String[]{android.Manifest.permission.ACCESS_FINE_LOCATION},1); 
        return location; 
       } 
       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) { 
     e.printStackTrace(); 
    } 

    return location; 
} 

/** 
* Stop using GPS listener 
* Calling this function will stop using GPS in your app 
* */ 
public void stopUsingGPS() { 
    if (locationManager != null) { 
     if (ActivityCompat.checkSelfPermission(this, Manifest.permission.ACCESS_FINE_LOCATION) != PackageManager.PERMISSION_GRANTED && ActivityCompat.checkSelfPermission(this, Manifest.permission.ACCESS_COARSE_LOCATION) != PackageManager.PERMISSION_GRANTED) { 
      // TODO: Consider calling 
      // ActivityCompat#requestPermissions 
      // here to request the missing permissions, and then overriding 
      // public void onRequestPermissionsResult(int requestCode, String[] permissions, 
      //           int[] grantResults) 
      // to handle the case where the user grants the permission. See the documentation 
      // for ActivityCompat#requestPermissions for more details. 
      return; 
     } 
     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 Dialog Title 
    alertDialog.setTitle("GPS is settings"); 

    // Setting Dialog 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) { 
     this.location = location; 
     getLatitude(); 
     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; 
} 
} 

を述べ下回っ

+0

あなたのアンドロイドOSのバージョン:このGPSClass参考

の代わりに、GoogleのAPIを使用しますか? –

+1

'GPSTracker extends Service'と' gps = new GPSTracker(PetList.this) '... ...私が推測させてください...非常に、非常に、**非常に悪い**のチュートリアルandroidhive - 悪いコードのソース練習 – Selvin

+0

私はマシュマロを使っています。私はまたそれの実行時許可を追加します。 @Sohail Zahid – Pratik

答えて

0

コールバックメソッドで 'myLatestFetchedLocation'コードを実装する必要があるためです。 ロケーションサービスは、ロケーションを取得するための非同期呼び出しを行います。したがって、現在の/最後の既知の場所がnullの場合、それはそれを返します。

+0

ここにコードを書いてください。 – Pratik

+0

私はinterval.whenアクティビティを初めて設定したくないのですが、その時間だけ私は場所が必要です。私は自分の場所を更新したくないので、どうすればこの問題を解決できますか教えてください。 – Pratik

+0

あなたのコードはonLocationChangedメソッドでなければなりません。これは、場所の更新があるときに呼び出されるものです。 複数の更新が必要ない場合は、requestSingleUpdateを使用してください Fusedライブラリは最新のものと同じように使用してください。 –

0

ロケーションエクスペリエンスを向上させる。 https://developer.android.com/training/location/receive-location-updates.html

+0

実際に私は複数のアクティビティからの場所を欲しがるので、複数のアクティビティで場所を取得するコードの書き換えを避けるために、アクティビティの場所を返す単一のクラスにコードを配置する方法はありますか? – Pratik

+0

私は間隔を設定したくありません。アクティビティが最初に始まるときはいつでも場所が必要ですが、間隔ごとに自分の位置を更新したくない場合は、どうすればこの問題を解決できるか教えてください。 mLocationRequest = new LocationRequest(); mLocationRequest.setPriority(LocationRequest.PRIORITY_HIGH_ACCURACY); mLocationRequest.setInterval(6000); mLocationRequest.setFastestInterval(1000); – Pratik

+0

Googleから場所を取得するクラスを1つ作成できます。そのクラスがgoogle fusedAPIから位置情報を取得すると、Interfaceを使用してロケーションが必要なアクティビティにロケーションコールが返されます。定期的にロケーションコールバックを送信するロケーションサービスを停止します。 –

関連する問題