2012-11-12 3 views
0

나는 내 입장에 착수 중이며 사용자 위치 정보를지도에 표시하는 앱을 개발 중입니다. 우리는 매 x 변수 (x는 사용자가 5, 10, 15, 30, 60 분 중에서 선택하여 입력 한 설정)를 가져와 나중에 공유 할 수 있도록 최상의 위치를 ​​데이터베이스에 보냅니다. 앱의 기본 흐름은 사용자가 앱을 열 때마다지도가 표시되며 최대한 빨리 현재 위치를 표시한다는 것입니다. 그 위치는 다른 사람들과 공유하기 위해 데이터베이스로 전송됩니다. 그들이 위치를 얻은 후 타이머가 시작되어 위치가 매번 다시 시작되고 30 분이 필요하다고 말한 다음 해당 위치를 DB로 보내고 타이머를 다시 시작합니다. 사용자가 앱을 시작할 때 즉시 위치를 알 수 있기 때문에 사용자가 애플리케이션에 액세스 할 때마다 타이머를 재설정해야합니다. 내가 겪고있는 문제는 백그라운드에서 자신의 위치를 ​​얻을 수있는 응용 프로그램에 DB를 보낼 타이머를 만드는 것입니다. 또한 위치를 얻은 후 짧은 시간 동안 업데이트 수신을 중지한다는 논리를 구현하려고합니다.Android : 타이머를 사용하여 1 분 간격으로 30 분마다 위치 정보 가져 오기

현재 requestLocationUpdates() 메소드를 이해하고 사용자가 앱에 액세스 할 때 GPS와 NETWORK에서 위치 정보를 가져오고 최소 시간은 60 초, 거리는 100 피트 또는 30.48 미터입니다. . 또한 사용자가 앱을 일시 중지하고 사용자가 앱을 다시 탐색 할 때 시작됩니다. 나는 우리가 이미 업데이트를 받았음에도 불구하고 우리가 계속 업데이트를 요청하고 있음을 알 수 있습니다. 이로 인해 requestLocationUpdates는 업데이트 변경 사항을 수신 할 때 배터리 수명을 계속 사용하고 있다고 생각합니다.

위치를받은 후에 업데이트를 중지하고 특정 시간이 지나면 위치 청취를 시작하려면 어떻게해야합니까? requestLocationUpdates의 현재 안드로이드 메소드를 읽는 minTime과 minDistance는 단지 "힌트"일 뿐이지 만, 그것들을 따르지는 않습니다. 설정 매개 변수를 따르려면 locationUpdater가 필요합니다. 당신이 필요

@Override 
public void onCreate(Bundle savedInstanceState) { 
    super.onCreate(savedInstanceState); 
    /** Session Creation and Checker */ 
    session = new SessionManagement(getApplicationContext()); 
    // Check if the user is logged in 
    session.checkLogin(); 

    /** Setup basic session and content view */ 
    // Set the Content View 
    setContentView(R.layout.activity_main); 
    /** Start of the MapView Elements */ 
    // extract MapView from layout 
    mapView = (MapView) findViewById(R.id.mapview); 
    // Set a mapController 
    mapController = mapView.getController(); 
    // set the map to have built in zoom controls 
    mapView.setBuiltInZoomControls(true); 

    /** Getting the device location */ 
    locationManager = (LocationManager) getSystemService(LOCATION_SERVICE); 
    geoCoder = new Geocoder(this); 

    isEnabled = locationManager 
      .isProviderEnabled(LocationManager.GPS_PROVIDER); 
    // Check if the GPS is enabled 
    if (!isEnabled) { 
     alert.showAlertDialog(MainActivity.this, 12); 
    } 

    // Retrieve a list of location providers that have fine accuracy, no 
    // monetary cost, etc 
    Criteria criteria = new Criteria(); 
    criteria.setAccuracy(Criteria.ACCURACY_HIGH); 
    criteria.setAltitudeRequired(false); 
    criteria.setBearingRequired(false); 
    criteria.setCostAllowed(true); 
    criteria.setPowerRequirement(Criteria.POWER_LOW); 
    provider = locationManager.getBestProvider(criteria, true); 

    // If no suitable provider is found, null is returned. 
    if (provider != null) { 
     provider = locationManager.getBestProvider(criteria, false); 
     BCT = (session.getBCT() * 60000); 
     // Initialize with last known location 
     locationManager.requestLocationUpdates(provider, BCT, 31, 
       locationListener); 

     // Check the map settings 
     if (session.isSatellite()) { 
      SatelliteChecked = true; 
      mapView.setSatellite(true); 
     } 
     if (session.isTraffic()) { 
      TrafficChecked = true; 
      mapView.setTraffic(true); 
     } 
    } else { 
     alert.showAlertDialog(getApplicationContext(), 15); 
     locationManager.removeUpdates(locationListener); 
    } 

} 

// 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. 

      Toast.makeText(getApplicationContext(), location.toString(), 
        Toast.LENGTH_LONG).show(); 

    } 

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

    } 

    public void onProviderEnabled(String provider) { 
     Toast.makeText(getApplicationContext(), provider.toUpperCase() + " enabled.", Toast.LENGTH_SHORT).show(); 
    } 

    public void onProviderDisabled(String provider) { 
     Toast.makeText(getApplicationContext(), provider.toUpperCase() + " disabled.", Toast.LENGTH_SHORT).show(); 
    } 
}; 
@Override 
protected void onResume() { 
    super.onResume(); 
    BCT = (session.getBCT() * 60000); 
    // when our activity resumes, we want to register for location updates 
    locationManager.requestLocationUpdates(
      provider, BCT, 31, locationListener); 
} 

@Override 
protected void onPause() { 
    super.onPause(); 
    // when our activity pauses, we want to remove listening for location 
    // updates 
    locationManager.removeUpdates(locationListener); 
} 

답변

0

은 타이머에 대한 배경 스레드입니다.

당신은 시도 할 수 :

  1. 모든 X 분을 예약 알람 관리자를 사용하여. 이것이 당신의 캡 스톤 프로젝트이기 때문에 내가 너무 많은 코드를주고 싶지 않았다, 긴 http://developer.android.com/reference/android/os/Handler.html#postDelayed(java.lang.Runnable 같이 Android: How to use AlarmManager
  2. 사용 X 분에 의해 postDelayed과 AsyncTask를 또는 처리기,,)

:이 질문의 답변을 참조 . 하지만 배경 스레드를 자세히 설명 할 수 있습니다 :

타이밍이 지금은 포 그라운드에서 수행됩니다. 즉, 앱이 열리지 않으면 타이머가 똑딱 거리지 않습니다. 타이머가 백그라운드 스레드에 있어야합니다. 이 스레드는 운영 체제에서 관리하며 응용 프로그램이 실행 중이 지 않아도 계속 실행되는 스레드입니다. 프로젝트와 상업용 프로젝트가 아닌이 작업을 수행하고 있기 때문에 Handler 접근 방식을 사용하는 것이 좋습니다. 같은 :

//make instance variable of the time the user chose, say... delayInMinutes 
int delayInMinutes; 
... 
//then whenever you want to start the timer... 
final Runnable updateLocation = new Runnable() { 
    public void run() { 
     // 
     ... do your update location here 
     // 
    } 
}; 

handler.postDelayed(updateLocation, delayInMinutes * 60 * 1000); 

및 그

0

를 작동해야이 alarmsIntentService 사용을위한 완벽한 상황이다. 사용자가 원하는 간격으로 설정된 반복 알람으로 IntentService를 시작하고 IntentService가 위치 업데이트를 처리하도록합니다.

모두 백그라운드에서 완료되었으며 필요하지 않을 때 실행중인 항목이 없습니다.

관련 문제