2011-10-12 8 views
8

10 분마다 새로운 GPS 위치를 기록하는 앱을 작성 중입니다.주기적으로 안드로이드에서 GPS 위치를 찾는 방법

위치 폴러를 시도해 보았습니다. 서비스에 위치 수신기를 넣고 위치 수신기를 활동에 넣었지만 이러한 방법 중 아무 것도 작동하지 않습니다.

위치 데이터를 기록하기 시작하기 2 분 전에 gps 위치 수신기를 켜는 방법이 필요합니다 (GPS를 통해 위치를 찾거나 신호가 없음을 확인하는 데 충분한 시간을줍니다). 나는 나의 updatelocation 클래스를 호출하기 전에 2 분 전에 gpsActivity를 호출하는 알람을 사용하여이 작업을 수행했습니다. 그런 다음 내 updatelocation 클래스는 gpsActivity의 locationManager를 가져 와서 위치를 추출합니다.

이론적으로이 작업을해야하지만 내 휴대 전화에 넣어 때 항상 잘못된 데이터를 (정확도가 너무 낮거나 아무런 신호도 모두가) 누군가가 나를 도울 수 있다면

나는 매우 감사 없을 것이다 얻을.

감사

알람 업데이트 위치하기 전에이 클래스 2 분을 호출

public class GPSActivity extends Activity { 

    public static LocationListener loc_listener = null; 
    public static LocationManager locationManager = null; 

    @Override 
    protected void onCreate(Bundle savedInstanceState) { 
     super.onCreate(savedInstanceState); 
     locationManager = (LocationManager) getSystemService(LOCATION_SERVICE); 
     getGPS(); 
    } 

    public static void getGPS() { 
     if (loc_listener == null) { 
      loc_listener = new LocationListener() { 

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

       @Override 
       public void onProviderEnabled(String provider) {} 

       @Override 
       public void onProviderDisabled(String provider) {} 

       @Override 
       public void onLocationChanged(Location location) {} 
      }; 
     } 
     locationManager.requestLocationUpdates(
       LocationManager.GPS_PROVIDER, 0, 0, loc_listener); 
    } 

    public static void killGPS() { 
     if (locationManager != null && loc_listener != null) { 
      locationManager.removeUpdates(loc_listener); 
     } 
    } 
} 

다음 두 분 후에이 서비스가 함께

public class UpdateLocation extends IntentService { 

    public static final String id = ""; 
    public static int retryCount = 0; 
    int notificationID = 1; 
    // gets the location manager from the GPSActivity 
    LocationManager locationManager = GPSActivity.locationManager; 

    @Override 
    public void onDestroy() { 
     super.onDestroy(); 
    } 

    public UpdateLocation() { 
     super("UpdateLocation"); 
    } 

    @Override 
    protected void onHandleIntent(Intent intent) { 
     locationManager = GPSActivity.locationManager; 
     SharedPreferences prefs = getSharedPreferences("Settings", 0); 
     final String id = prefs.getString("ID", ""); 
     HttpParams httpParams = new BasicHttpParams(); 
     // 30seconds and it stops 
     HttpConnectionParams.setConnectionTimeout(httpParams, 30000); 
     HttpConnectionParams.setSoTimeout(httpParams, 30000); 
     DefaultHttpClient httpclient = new DefaultHttpClient(httpParams); 
     HttpPost httpost = new HttpPost(
       "http://iphone-radar.com/gps/gps_locations"); 
     JSONObject holder = new JSONObject(); 
     try { 
      holder.put("id", id); 
      Location location = getLocation(); 
      if (location != null && (location.getAccuracy() < 25)) { 
       retryCount = 0; 
       Calendar c = Calendar.getInstance(); 
       SimpleDateFormat sdf = new SimpleDateFormat(
         "hh:mmaa MM/dd/yyyy"); 
       holder.put("time", sdf.format(c.getTime())); 
       holder.put("time_since_epoch", 
         System.currentTimeMillis()/1000); 
       holder.put("lat", location.getLatitude()); 
       holder.put("lon", location.getLongitude()); 
       StringEntity se = new StringEntity(holder.toString()); 
       httpost.setEntity(se); 
       httpost.setHeader("Accept", "application/json"); 
       httpost.setHeader("Content-type", "application/json"); 
       ResponseHandler responseHandler = new BasicResponseHandler(); 
       String response = httpclient.execute(httpost, 
         responseHandler); 
       org.json.JSONObject obj; 
       obj = new org.json.JSONObject(response); 
       SimpleDateFormat sdf2 = new SimpleDateFormat(
         "yyyy-MM-dd hh:mm:ssaa"); 
       addHistory(
         sdf2.format(c.getTime()), 
         "Background GPS", 
         "Latitude: " 
          + String.format("%.6g%n", 
            location.getLatitude()) 
          + "\n" 
          + "Longitude: " 
          + String.format("%.6g%n", 
            location.getLongitude())); 
       SharedPreferences.Editor editor = prefs.edit(); 
       editor.putString("LastUpdatedTime", sdf.format(c.getTime())); 
       editor.commit(); 
       Intent setAlarm = new Intent(UpdateLocation.this, 
         UpdateLocation.class); 
       PendingIntent pendingIntent = PendingIntent.getService(
         UpdateLocation.this, 0, setAlarm, 0); 
       AlarmManager alarmManager = (AlarmManager) getSystemService(ALARM_SERVICE); 
       Calendar calendar = Calendar.getInstance(); 
       calendar.setTimeInMillis(System.currentTimeMillis()); 
       int UPDATE_TIME = prefs.getInt("Update_time", 10); 
       calendar.add(Calendar.MINUTE, UPDATE_TIME); 
       alarmManager.set(AlarmManager.RTC_WAKEUP, 
         calendar.getTimeInMillis(), pendingIntent); 
       // sets an alarm for the next time we need to record a 
       // location 
       GPSActivity.killGPS(); 
       // turns off the gps location listener 
       Intent setAlarm2 = new Intent(UpdateLocation.this, 
         GPSActivity.class); 
       PendingIntent pendingIntent2 = PendingIntent.getService(
         UpdateLocation.this, 0, setAlarm2, 0); 
       Calendar calendar2 = Calendar.getInstance(); 
       calendar2.add(Calendar.MINUTE, UPDATE_TIME - 2); 
       alarmManager.set(AlarmManager.RTC_WAKEUP, 
         calendar2.getTimeInMillis(), pendingIntent2); 
       // sets an alarm to turn on the gpsActivity 2mins before the 
       // next time updatelocation needs to record some data 
      } 
     } finally { 
     } 
    } 
} 
+0

http://tinyurl.com/942lhyf이 작업 데모를 사용해보십시오. –

답변

4

를 사용하여 수신기 및 서비스라고합니다. 이를 위해 this link에서 전체 샘플을 찾을 수 있습니다. 거기에 청취자가 있습니다. 청취자는 귀하의 활동에 새로운 위치가 준비되었음을 알리는 데 사용될 수 있습니다.

+0

http://stackoverflow.com/questions/2775628/android-how-to-periodically-send-location-to-a-server 동의하지 않는다. 알람 관리자를 권장합니다. – Mawg

관련 문제