2016-11-17 28 views
1

私はアプリケーションを構築しており、ユーザーの現在地を取得する必要があります。このプロセスでは、ユーザーのAndroidバージョンのSDKバージョンが23 - Marshmallowであるかどうか最初に確認したい場合は、それが許可されていればそれが必要です。許可を得てユーザーの現在地を取得する

ユーザーが許可する場合は、その場所を有効にするかオンにします。ユーザーが拒否すると、再度要求します。

しかしユーザのAndroidバージョンが23未満である場合、それは処理に進む。

アプリケーションが位置を取得し、二重可変に緯度と経度を格納し、他のメソッドにアクセスすることができます。

この機能を正しく実装する方法を教えてください。ステップバイステップのように。以下のおかげ

答えて

1
public class MainActivity extends ActionBarActivity implements 
    ConnectionCallbacks, OnConnectionFailedListener { 
... 
@Override 
public void onConnected(Bundle connectionHint) { 
    mLastLocation = LocationServices.FusedLocationApi.getLastLocation(
      mGoogleApiClient); 
    if (mLastLocation != null) { 
     mLatitudeText.setText(String.valueOf(mLastLocation.getLatitude())); 
     mLongitudeText.setText(String.valueOf(mLastLocation.getLongitude())); 
    } 
}} 

を助けるonConnectedあなたはGoogleApiClientCallbackメソッドを実装した後、あなたが得るコールバックです。上記のメソッドは、最後の既知の場所の緯度と経度のみを取得します。前提条件について@jitesh mohiteの回答を参照してください

1

は= 1

プライベート静的最終int型のPERMISSION_REQUEST_CODEあなたの問題を解決することになるだろう。取得するためのコード

@Override 
    public void onRequestPermissionsResult(int requestCode, String permissions[], int[] grantResults) { 
     switch (requestCode) { 
      case PERMISSION_REQUEST_CODE: 
       if (grantResults.length > 0 && grantResults[0] == PackageManager.PERMISSION_GRANTED) { 
        Util.showToast(getBaseContext(), getBaseContext().getString(R.string 
          .loc_permission_granted)); 
        Util.startActivityAndLocationTracking(getApplicationContext()); 
       } else { 
        Util.showToast(getBaseContext(), getBaseContext().getString(R.string 
          .loc_permission_denied)); 
       } 
       break; 
      default: 
       break; 
     } 
    } 
+0

どのように私はユーザーの場所を取得しますか?私はそれを格納する必要があり、あなたのコメントは許可要求のみを表示します。場所は指定されていません。 –

+0

下記のリンク先の参考用に使用できますhttps://developer.android.com/training/location/receive-location-updates.html –

0

使用次のクラス以下のオーバーライドをチェックし、marshmellowの要求ランタイム権限とユーザーがmarshmellowデバイスにおけるロケーション要求を受け入れる場合、場所の追跡

private void requestRunTimePermissionAndStartTracking() { 
     if (Build.VERSION.SDK_INT >= 23) { 
      // Marshmallow+ 
      if (!checkPermission(getBaseContext())) { 
       requestPermission(mActivity, PERMISSION_REQUEST_CODE); 
      } else { 
        // get location here 
      } 
     } else { 
      // get location here 
     } 
    } 


// check whether we are having location permission for marshmellow 
    public static boolean checkPermission(Context context) { 
     int result = ContextCompat.checkSelfPermission(context, Manifest.permission 
       .ACCESS_FINE_LOCATION); 
     if (result == PackageManager.PERMISSION_GRANTED) { 
      return true; 
     } else { 
      return false; 

     } 
    } 

// used to request for location permission. 
    public static void requestPermission(Activity activity , int code) { 
     if (ActivityCompat.shouldShowRequestPermissionRationale(activity, Manifest.permission 
       .ACCESS_FINE_LOCATION)) { 
      Toast.makeText(activity, "GPS permission allows us to access location data. Please allow " + 
        "in App Settings for additional functionality.", Toast.LENGTH_LONG).show(); 
     } else { 
      ActivityCompat.requestPermissions(activity, new String[]{Manifest.permission 
        .ACCESS_FINE_LOCATION, Manifest.permission 
        .ACCESS_COARSE_LOCATION}, code); 
     } 
    } 

開始するために使用

//現在地:

public class GPSTracker extends Service implements LocationListener { 

    // 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 = 3000; // 3 seconds 
    private final Context mContext; 
    // Declaring a Location Manager 
    protected LocationManager locationManager; 
    // flag for GPS status 
    boolean isGPSEnabled = false; 
    // flag for network status 
    boolean isNetworkEnabled = false; 
    boolean canGetLocation = false; 
    Location location; // location 
    double latitude; // latitude 
    double longitude; // longitude 
    Fragment frag; 

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

    @SuppressWarnings("ResourceType") 
    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) { 
       // 
//    Toast.makeText(mContext,"no network provider is enabled",Toast.LENGTH_SHORT).show(); 
      } else { 
       this.canGetLocation = true; 
       // First get location from Network Provider 
       if (isNetworkEnabled) { 

        locationManager.requestLocationUpdates(
          LocationManager.NETWORK_PROVIDER, 
          MIN_TIME_BW_UPDATES, 
          MIN_DISTANCE_CHANGE_FOR_UPDATES, this); 
        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); 
         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; 
    } 

    @Override 
    public void onLocationChanged(Location location) { 
     this.location = location; 
    } 

    @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 double getLatitude() { 
     if (location != null) { 
      latitude = location.getLatitude(); 
     } 

     return latitude; 
    } 

    public double getLongitude() { 
     if (location != null) { 
      longitude = location.getLongitude(); 
     } 

     return longitude; 
    } 

    public boolean canGetLocation() { 
     return this.canGetLocation; 
    } 

    public void showSettingsAlert() { 
     if (mContext != null) { 
      AlertDialog.Builder alertDialog = new AlertDialog.Builder(mContext); 

      alertDialog.setTitle("GPS Setting"); 

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

      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); 
         } 
        }); 

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

      alertDialog.show(); 
     } 
    } 

    public void stopUsingGPS() { 
     if (locationManager != null) { 
      if (ActivityCompat.checkSelfPermission(Application.getAppContext(), 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. 
       ActivityCompat.requestPermissions((Activity)mContext, new String[]{Manifest.permission.ACCESS_COARSE_LOCATION, Manifest.permission.ACCESS_FINE_LOCATION}, 789); 

      } 
      locationManager.removeUpdates(GPSTracker.this); 
     } 
    } 

} 

実行時のアクセス許可

private void getGpsLink() { 
      if (ActivityCompat.checkSelfPermission(getActivity(), Manifest.permission.ACCESS_FINE_LOCATION) != PackageManager.PERMISSION_GRANTED && ActivityCompat.checkSelfPermission(getActivity(), Manifest.permission.ACCESS_COARSE_LOCATION) != PackageManager.PERMISSION_GRANTED) { 
if (ActivityCompat.shouldShowRequestPermissionRationale(getActivity(), Manifest.permission.ACCESS_FINE_LOCATION)) { 
Toast.makeText(getActivity(), "Location permission needed. Please allow in App Settings for additional functionality.", Toast.LENGTH_LONG).show(); 
Intent intent = new Intent(Settings.ACTION_APPLICATION_DETAILS_SETTINGS, Uri.fromParts("package", getActivity().getPackageName(), null)); 
intent.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK); 
intent.setFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP); 
startActivityForResult(intent, 789); 
}else{ 
       ActivityCompat.requestPermissions(getActivity(), new String[]{Manifest.permission.ACCESS_COARSE_LOCATION, Manifest.permission.ACCESS_FINE_LOCATION}, REQUEST_CODE_LOCATION); 
    } 


      } else { 
       GPSTracker gps = new GPSTracker(getActivity(), null); 


       if (gps.canGetLocation()) { 
        String latitude = String.valueOf(gps.getLatitude()); 
        String longitude= String.valueOf(gps.getLongitude()); 

        CallSearchApi(); 
       } else { 
        showSettingsAlert(); 
       } 
      } 
     } 

であなたのアクティビティ/フラグメントで使用するのプロセスがうまくいけば、それはあなたの

+0

Android用フレームワークAPIを使用しない場合は、Googleサービスの場所apisを使用してください(https:///developer.android.com/training/location/index.html –

+0

ありがとうSaurabh Srivastava、私は彼が正しいと思いますが、あなたのこのコードを試してみます。 Googleサービスの場所のapiはより一貫しています。しかしAbhinav Puri、あなたは私にどのように表示できますか? –

関連する問題