2017-11-20 4 views
0

나는 사용자의 마지막으로 알려진 위치를 얻으려고하지만, 앱을 열면 위도와 경도가 표시되어야하는 textViews에 빈 화면이 표시됩니다. 결함이나 오류를 찾을 수 없습니다. 그래서 도움이 필요해. 이 코드는 어제 실행했을 때 작동했지만 지금은 작동하지 않습니다. 다음은 내장치의 마지막 위치를 얻는 방법?

MainActivity.java입니다 :

public class MainActivity extends AppCompatActivity implements LocationListener { 
final String TAG = "GPS"; 
private final static int ALL_PERMISSIONS_RESULT = 101; 
private static final long MIN_DISTANCE_CHANGE_FOR_UPDATES = 10; 
private static final long MIN_TIME_BW_UPDATES = 1000 ; 

TextView tvLatitude, tvLongitude, tvTime; 
LocationManager locationManager; 
Location loc; 
ArrayList<String> permissions = new ArrayList<>(); 
ArrayList<String> permissionsToRequest; 
ArrayList<String> permissionsRejected = new ArrayList<>(); 
boolean isGPS = false; 
boolean isNetwork = false; 
boolean canGetLocation = true; 

@Override 
protected void onCreate(Bundle savedInstanceState) { 
    super.onCreate(savedInstanceState); 
    setContentView(R.layout.activity_main); 

    tvLatitude = (TextView) findViewById(R.id.tvLatitude); 
    tvLongitude = (TextView) findViewById(R.id.tvLongitude); 
    tvTime = (TextView) findViewById(R.id.tvTime); 

    locationManager = (LocationManager) getSystemService(Service.LOCATION_SERVICE); 
    isGPS = locationManager.isProviderEnabled(LocationManager.GPS_PROVIDER); 
    isNetwork = locationManager.isProviderEnabled(LocationManager.NETWORK_PROVIDER); 

    permissions.add(Manifest.permission.ACCESS_FINE_LOCATION); 
    permissions.add(Manifest.permission.ACCESS_COARSE_LOCATION); 
    permissionsToRequest = findUnAskedPermissions(permissions); 

    if (!isGPS && !isNetwork) { 
     Log.d(TAG, "Connection off"); 
     showSettingsAlert(); 
     getLastLocation(); 
    } else { 
     Log.d(TAG, "Connection on"); 
     // check permissions 
     if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.M) { 
      if (permissionsToRequest.size() > 0) { 
       requestPermissions(permissionsToRequest.toArray(new String[permissionsToRequest.size()]), 
         ALL_PERMISSIONS_RESULT); 
       Log.d(TAG, "Permission requests"); 
       canGetLocation = false; 
      } 
     } 

     // get location 
     getLocation(); 
    } 
} 

@Override 
public void onLocationChanged(Location location) { 
    Log.d(TAG, "onLocationChanged"); 
    updateUI(location); 
} 

@Override 
public void onStatusChanged(String s, int i, Bundle bundle) {} 

@Override 
public void onProviderEnabled(String s) { 
    getLocation(); 
} 

@Override 
public void onProviderDisabled(String s) { 
    if (locationManager != null) { 
     locationManager.removeUpdates(this); 
    } 
} 

private void getLocation() { 
    try { 
     if (canGetLocation) { 
      Log.d(TAG, "Can get location"); 
      if (isGPS) { 
       // from GPS 
       Log.d(TAG, "GPS on"); 
       locationManager.requestLocationUpdates(
         LocationManager.GPS_PROVIDER, 
         MIN_TIME_BW_UPDATES, 
         MIN_DISTANCE_CHANGE_FOR_UPDATES, this); 

       if (locationManager != null) { 
        loc = locationManager.getLastKnownLocation(LocationManager.GPS_PROVIDER); 
        if (loc != null) 
         updateUI(loc); 
       } 
      } else if (isNetwork) { 
       // from Network Provider 
       Log.d(TAG, "NETWORK_PROVIDER on"); 
       locationManager.requestLocationUpdates(
         LocationManager.NETWORK_PROVIDER, 
         MIN_TIME_BW_UPDATES, 
         MIN_DISTANCE_CHANGE_FOR_UPDATES, this); 

       if (locationManager != null) { 
        loc = locationManager.getLastKnownLocation(LocationManager.NETWORK_PROVIDER); 
        if (loc != null) 
         updateUI(loc); 
       } 
      } else { 
       loc.setLatitude(0); 
       loc.setLongitude(0); 
       updateUI(loc); 
      } 
     } else { 
      Log.d(TAG, "Can't get location"); 
     } 
    } catch (SecurityException e) { 
     e.printStackTrace(); 
    } 
} 

private void getLastLocation() { 
    try { 
     Criteria criteria = new Criteria(); 
     String provider = locationManager.getBestProvider(criteria, false); 
     Location location = locationManager.getLastKnownLocation(provider); 
     Log.d(TAG, provider); 
     Log.d(TAG, location == null ? "NO LastLocation" : location.toString()); 
    } catch (SecurityException e) { 
     e.printStackTrace(); 
    } 
} 

private ArrayList findUnAskedPermissions(ArrayList<String> wanted) { 
    ArrayList result = new ArrayList(); 

    for (String perm : wanted) { 
     if (!hasPermission(perm)) { 
      result.add(perm); 
     } 
    } 

    return result; 
} 

private boolean hasPermission(String permission) { 
    if (canAskPermission()) { 
     if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.M) { 
      return (checkSelfPermission(permission) == PackageManager.PERMISSION_GRANTED); 
     } 
    } 
    return true; 
} 

private boolean canAskPermission() { 
    return (Build.VERSION.SDK_INT > Build.VERSION_CODES.LOLLIPOP_MR1); 
} 

@TargetApi(Build.VERSION_CODES.M) 
@Override 
public void onRequestPermissionsResult(int requestCode, String[] permissions, int[] grantResults) { 
    switch (requestCode) { 
     case ALL_PERMISSIONS_RESULT: 
      Log.d(TAG, "onRequestPermissionsResult"); 
      for (String perms : permissionsToRequest) { 
       if (!hasPermission(perms)) { 
        permissionsRejected.add(perms); 
       } 
      } 

      if (permissionsRejected.size() > 0) { 
       if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.M) { 
        if (shouldShowRequestPermissionRationale(permissionsRejected.get(0))) { 
         showMessageOKCancel("These permissions are mandatory for the application. Please allow access.", 
           new DialogInterface.OnClickListener() { 
            @Override 
            public void onClick(DialogInterface dialog, int which) { 
             if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.M) { 
              requestPermissions(permissionsRejected.toArray(
                new String[permissionsRejected.size()]), ALL_PERMISSIONS_RESULT); 
             } 
            } 
           }); 
         return; 
        } 
       } 
      } else { 
       Log.d(TAG, "No rejected permissions."); 
       canGetLocation = true; 
       getLocation(); 
      } 
      break; 
    } 
} 

public void showSettingsAlert() { 
    AlertDialog.Builder alertDialog = new AlertDialog.Builder(this); 
    alertDialog.setTitle("GPS is not Enabled!"); 
    alertDialog.setMessage("Do you want to turn on GPS?"); 
    alertDialog.setPositiveButton("Yes", new DialogInterface.OnClickListener() { 
     public void onClick(DialogInterface dialog, int which) { 
      Intent intent = new Intent(Settings.ACTION_LOCATION_SOURCE_SETTINGS); 
      startActivity(intent); 
     } 
    }); 

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

    alertDialog.show(); 
} 

private void showMessageOKCancel(String message, DialogInterface.OnClickListener okListener) { 
    new AlertDialog.Builder(MainActivity.this) 
      .setMessage(message) 
      .setPositiveButton("OK", okListener) 
      .setNegativeButton("Cancel", null) 
      .create() 
      .show(); 
} 

private void updateUI(Location loc) { 
    Log.d(TAG, "updateUI"); 
    tvLatitude.setText(Double.toString(loc.getLatitude())); 
    tvLongitude.setText(Double.toString(loc.getLongitude())); 
    tvTime.setText(DateFormat.getTimeInstance().format(loc.getTime())); 
} 

@Override 
protected void onDestroy() { 
    super.onDestroy(); 
    if (locationManager != null) { 
     locationManager.removeUpdates(this); 
    } 
} 
} 

} 
+0

시도 - '파일 -> 무효화 캐시/Restart' –

+0

은'getLastLocation()'메소드는 장치가 알고 일이 마지막으로 알려진 위치를 가져옵니다. 때로는 장치가 위치를 "알 수없는"경우가 있으며 'null'이 반환됩니다. 또한 onLocationChanged()가 트리거되기 전에 시간이 걸릴 수도 있고, 장치가 위치를 결정할 수없는 경우 전혀 발생하지 않을 수도 있습니다. –

+0

@MarkusKauppinen 어떻게 해결할 수 있습니까? –

답변

0

융합 위치 제공자 클라이언트가 그것을 할 수있는 가장 좋은 방법입니다 매니페스트 파일에 다음 권한을 추가합니다. getLastLocation() 메소드에 대해이 코드를보십시오 :

FusedLocationProviderClient mLocationProvider = LocationServices.getFusedLocationProviderClient(activity); 
     mLocationProvider.getLastLocation().addOnSuccessListener(activity, location -> { 
      if (location != null) { 
       double latitude = location.getLatitude(); 
       double longitude = location.getLongitude();  
      } 
     }).addOnFailureListener(e -> { 
       //some log here 
     }); 
0

당신이 솔루션 아래 시도하고 나를 위해 잘 작동하고 있기 때문에, 알려 수 있습니다. 당신은 getLastLocation() 방법이 공급자를 언급 한

String provider = LocationManager.NETWORK_PROVIDER; 

는 공급자를 변경

.

또한

<uses-permission android:name="android.permission.INTERNET"/> 
    <uses-permission android:name="android.permission.ACCESS_COARSE_LOCATION"/> 
    <uses-permission android:name="android.permission.ACCESS_FINE_LOCATION"/> 
    <uses-permission android:name="android.permission.ACCESS_NETWORK_STATE"/> 
    <uses-permission android:name="android.permission.BIND_TELECOM_CONNECTION_SERVICE"/> 
    <uses-permission android:name="android.permission.ACCESS_WIFI_STATE"/> 
+0

이 솔루션을 사용해 보셨습니까? 제발 당신이 업데이 트됩니까? – androidOnHigh

+0

네, 고마워요. 괜찮 았어. 마지막 위치를 얻는 데 문제가있었습니다. –

관련 문제