2014-01-22 7 views
1

가능한 경우 네트워크 제공 업체를 선택하는 코드 작성자 또는 네트워크를 사용할 수없는 경우 GPS 제공 업체를 선택하는 방법을 모르겠습니다. 어떻게 코드를 변경할 수 있습니까? 이것은 내 첫 번째 안드로이드 응용 프로그램이며 나는 그것을 시도했지만 성공하지 못했습니다.LocationManager Provider

package com.example.googlemapslbs; 

import java.util.List; 
import com.google.android.gms.maps.GoogleMap; 
import com.google.android.gms.maps.MapFragment; 
import com.google.android.gms.maps.model.LatLng; 
import com.google.android.gms.maps.model.MarkerOptions; 
import android.app.Activity; 
import android.content.Context; 
import android.os.Bundle; 
import android.widget.Toast; 
import android.location.Location; 
import android.location.LocationListener; 
import android.location.LocationManager; 
import com.google.android.gms.maps.CameraUpdateFactory; 
import android.location.Criteria; 
import android.util.Log; 

public class MainActivity extends Activity { 
    GoogleMap Map; 

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

     try { 
      // Load map 
      initilizeMap(); 
      } 
     catch (Exception e) { 
      e.printStackTrace(); 
     } 

    } 


    private void initilizeMap() { 
     if (Map == null) { 
      Map = ((MapFragment) getFragmentManager().findFragmentById(R.id.map)).getMap(); 

      // map type normal (other possible choices: hybrid, terrain, satellite) 
      Map.setMapType(GoogleMap.MAP_TYPE_NORMAL); 

      // enable my-location 
      Map.setMyLocationEnabled(true); 
      LocationManager locationManager = (LocationManager) getSystemService(LOCATION_SERVICE); 

      // 
      Criteria criteria = new Criteria(); 
      String provider = locationManager.getBestProvider(criteria, true); 

      //getting Current Location 
      Location location = locationManager.getLastKnownLocation(provider); 

      if(location == null){ 
       LocationListener locationListener = new LocationListener() { 

       @Override 
       public void onLocationChanged(Location location) { 
        double lat= location.getLatitude(); 
        double lng = location.getLongitude(); 
        LatLng ll = new LatLng(lat, lng); 
        Map.moveCamera(CameraUpdateFactory.newLatLngZoom(ll, 18));      
       } 
       @Override 
       public void onProviderDisabled(String provider) {} 
       @Override 
       public void onProviderEnabled(String provider) {} 
       @Override 
       public void onStatusChanged(String provider, int status, 
         Bundle extras) {} 
       }; 
      //Log.d("APpln", "well hello there >>"+location); 

       //location updates - requestLocationUpdates(provider, minTime, minDistance, listener) 
       locationManager.requestLocationUpdates(provider, 20000, 0, locationListener); 

      }else{ 
       double lat= location.getLatitude(); 
       double lng = location.getLongitude(); 

       LatLng ll = new LatLng(lat, lng); 

       //modify the map's camera - zoom 18 
       Map.moveCamera(CameraUpdateFactory.newLatLngZoom(ll, 18)); 
      } 


     // Define a listener that responds to location updates 
      LocationListener locationListener = new LocationListener() { 

       public void onLocationChanged(Location location) { 

       // Called when a new location is found by the network location provider. 
       makeUseOfNewLocation(location); 
       } 

       private void makeUseOfNewLocation(Location location) { 
        double lat = location.getLatitude(); 
      double lng = location.getLongitude(); 
       LatLng ll = new LatLng(lat, lng); 
       Toast.makeText(getApplicationContext(), "Your Current Location \nLat: " + lat + "\nLng: " + lng, Toast.LENGTH_LONG).show(); 

      } 

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

       public void onProviderEnabled(String provider) {} 

       public void onProviderDisabled(String provider) {} 
      }; 

      locationManager.requestLocationUpdates(locationManager.getBestProvider(criteria, true), 0, 0, locationListener); 

      // check if map is created successfully or not 
      if (Map == null) { 
       Toast.makeText(getApplicationContext(), 
         "ups... can not create map", Toast.LENGTH_SHORT) 
         .show(); 
      } 
     } 
    } 

    @Override 
    protected void onResume() { 
     super.onResume(); 
     initilizeMap(); 
    } 

    } 
+0

여기의 예를 참조하십시오. http://www.androidhive.info/2012/07/android-gps-location-manager-tutorial/ GPS 만 사용하지만 무선을 유사하게 사용할 수도 있습니다. –

+0

이 대답은 당신에게 가장 어울립니다. http://stackoverflow.com/a/6280851/1979347 –

+0

@Rohan Kandwal이 당신의 도움에 감사 드리며 조언 된 대답은 upvoted – bucek

답변

1

Location Services의 사용법을 이해하기위한 샘플 프로젝트를 만들었습니다. 나는 코드를 게시하는 중이고, Location Services의 작업에 대한 필요와 이해를 위해 자유롭게 사용하십시오. 이 코드는 사용 가능한 최상의 위치 서비스 공급자를 확인하고 사용하지 않을 경우 설정에서 전환합니다.

public class DSLVFragmentClicks extends Activity implements LocationListener { 
private final int BESTAVAILABLEPROVIDERCODE = 1; 
private final int BESTPROVIDERCODE = 2; 
LocationManager locationManager; 
String bestProvider; 
String bestAvailableProvider; 

@Override 
public void onActivityResult(int requestCode, int resultCode, Intent data) { 
    if (requestCode == BESTPROVIDERCODE) { 
     if (requestCode != Activity.RESULT_OK || locationManager.isProviderEnabled(bestProvider)) { 
      Toast.makeText(getActivity(), "Error! Location Service " + bestProvider + " not Enabled", Toast.LENGTH_LONG).show(); 

     } else { 
      getLocation(bestProvider); 
     } 
    } else { 
     if (requestCode != Activity.RESULT_OK || locationManager.isProviderEnabled(bestAvailableProvider)) { 
      Toast.makeText(getActivity(), "Error! Location Service " + bestAvailableProvider + " not Enabled", Toast.LENGTH_LONG).show(); 

     } else { 
      getLocation(bestAvailableProvider); 
     } 
    } 
} 

public void getLocation(String usedLocationService) { 
    Toast.makeText(getActivity(), "getting Location", Toast.LENGTH_SHORT).show(); 
    long updateTime = 0; 
    float updateDistance = 0; 
    // finding the current location 
    locationManager.requestLocationUpdates(usedLocationService, updateTime, updateDistance, this); 

} 


@Override 
public void onCreate(Bundle savedState) { 
    super.onCreate(savedState); 
    setContentView(R.layout.main); 
    // set a Criteria specifying things you want from a particular Location Service 
      Criteria criteria = new Criteria(); 
      criteria.setSpeedRequired(false); 
      criteria.setAccuracy(Criteria.ACCURACY_FINE); 
      criteria.setCostAllowed(true); 
      criteria.setBearingAccuracy(Criteria.ACCURACY_HIGH); 
      criteria.setAltitudeRequired(false); 

      locationManager = (LocationManager) getActivity().getSystemService(Context.LOCATION_SERVICE); 
      // finding best provider without fulfilling the criteria 
      bestProvider = locationManager.getBestProvider(criteria, false); 
      // finding best provider which fulfills the criteria 
      bestAvailableProvider = locationManager.getBestProvider(criteria, true); 
      String toastMessage = null; 
      if (bestProvider == null) { 
       toastMessage = "NO best Provider Found"; 
      } else if (bestAvailableProvider != null && bestAvailableProvider.equals(bestAvailableProvider)) { 
       boolean enabled = locationManager.isProviderEnabled(bestAvailableProvider); 
       if (!enabled) { 
        Toast.makeText(getActivity(), " Please enable " + bestAvailableProvider + " to find your location", Toast.LENGTH_LONG).show(); 
        Intent mainIntent = new Intent(Settings.ACTION_LOCATION_SOURCE_SETTINGS); 
        startActivityForResult(mainIntent, BESTAVAILABLEPROVIDERCODE); 
       } else { 
        getLocation(bestAvailableProvider); 
       } 
       toastMessage = bestAvailableProvider + " used for getting your current location"; 
      } else { 
       boolean enabled = locationManager.isProviderEnabled(bestProvider); 
       if (!enabled) { 
        Toast.makeText(getActivity(), " Please enable " + bestProvider + " to find your location", Toast.LENGTH_LONG).show(); 
        Intent mainIntent = new Intent(Settings.ACTION_LOCATION_SOURCE_SETTINGS); 
        startActivityForResult(mainIntent, BESTPROVIDERCODE); 
       } else { 
        getLocation(bestProvider); 
       } 
       toastMessage = bestProvider + " is used to get your current location"; 

      } 
      Toast.makeText(getActivity(), toastMessage, Toast.LENGTH_LONG).show(); 
      return true; 
     } 
    }); 
} 

@Override 
public void onLocationChanged(Location location) { 
    Log.d("Location Found", location.getLatitude() + " " + location.getLongitude()); 
    // getting the street address from longitute and latitude 
    Geocoder geocoder = new Geocoder(getActivity(), Locale.getDefault()); 
    String addressString = "not found !!"; 
    try { 
     List<Address> addressList = geocoder.getFromLocation(location.getLatitude(), location.getLongitude(), 1); 
     StringBuilder stringBuilder = new StringBuilder(); 
     if (addressList.size() > 0) { 
      Address address = addressList.get(0); 
      for (int i = 0; i < address.getMaxAddressLineIndex(); i++) { 
       stringBuilder.append(address.getAddressLine(i)).append("\n"); 
       stringBuilder.append(address.getLocality()).append("\n"); 
       stringBuilder.append(address.getPostalCode()).append("\n"); 
       stringBuilder.append(address.getCountryName()).append("\n"); 
      } 

      addressString = stringBuilder.toString(); 
      locationManager.removeUpdates(this); 
     } 
    } catch (IOException e) { 
     e.printStackTrace(); //To change body of catch statement use File | Settings | File Templates. 
    } 
    Toast.makeText(getActivity(), " Your Location is " + addressString, Toast.LENGTH_LONG).show(); 
} 

@Override 
public void onStatusChanged(String s, int i, Bundle bundle) { 
    //To change body of implemented methods use File | Settings | File Templates. 
} 

@Override 
public void onProviderEnabled(String s) { 
    //To change body of implemented methods use File | Settings | File Templates. 
} 

@Override 
public void onProviderDisabled(String s) { 
    //To change body of implemented methods use File | Settings | File Templates. 
} 
} 

당신이 그 중 일부를 이해하지 못했다면 언제든지 물어보십시오.

관련 문제