2011-08-19 91 views
1

我應該每隔5秒更新一次偵聽器。但事實並非如此。我的代碼有什麼問題?每5秒更新一次GPS偵聽器

非常感謝您的幫助!

package com.example.android.lbs; 

import java.io.BufferedWriter; 
import java.io.File; 
import java.io.FileWriter; 
import java.sql.Date; 
import java.text.SimpleDateFormat; 

import android.app.Activity; 
import android.content.Context; 
import android.location.Location; 
import android.location.LocationListener; 
import android.location.LocationManager; 
import android.os.Bundle; 
import android.os.Environment; 
import android.util.Log; 
import android.view.View; 
import android.widget.Button; 
import android.widget.TextView; 
import android.widget.Toast; 

public class LbsGeocodingActivity extends Activity { 

    public static final String LOG_TAG = "<<< ------------ >>> GeocodingActivity <<< ------------ >>>"; 

    TextView tv; 
    int ScreenOutputCount; 
    String newTrip; 

    private static final long MINIMUM_DISTANCE_CHANGE_FOR_UPDATES = 0; // in Meters 
    private static final long MINIMUM_TIME_BETWEEN_UPDATES = 5000; // in Milliseconds, 5 secconds 

    protected LocationManager lm; 
    MyLocationListener locationL = new MyLocationListener(); 

    protected Button retrieveLocationButton; 
    //Log.e(LOG_TAG, e.toString()); 

    @Override 
    public void onCreate(Bundle savedInstanceState) { 

     super.onCreate(savedInstanceState); 
     setContentView(R.layout.main); 

     try { 
      View.OnClickListener handler = new View.OnClickListener(){ 
       public void onClick(View v) { 
        //we will use switch statement and just 
        //get thebutton's id to make things easier 
        switch (v.getId()) { 

         case R.id.trip_start: 
          tripStart(); 
          break; 
         case R.id.trip_end: 
          tripEnd(); 
         break; 
        } 
       } 
      }; 

      //we will set the listeners 
      findViewById(R.id.trip_start).setOnClickListener(handler); 
      findViewById(R.id.trip_end).setOnClickListener(handler); 

      }catch(Exception e){ 
       Log.e("Android Button Tutorial", e.toString()); 
      } 

    }  

    public void tripStart(){ 

     File originalDirectories = new File(Environment.getExternalStorageDirectory() + "/Android/GpsTracker/"); 
     if(!originalDirectories.exists()){ 
      originalDirectories.mkdirs(); 
     } 

     LbsGeocodingActivity.this.newTrip = getNewFileName(); 
     LbsGeocodingActivity.this.ScreenOutputCount = 1; 
     LbsGeocodingActivity.this.tv = (TextView) this.findViewById(R.id.thetext); 
     LbsGeocodingActivity.this.tv.setText("Location Updates: \n"); 

     LbsGeocodingActivity.this.lm = (LocationManager) getSystemService(Context.LOCATION_SERVICE); 

     LbsGeocodingActivity.this.lm.requestLocationUpdates(
       LocationManager.NETWORK_PROVIDER, 
       MINIMUM_TIME_BETWEEN_UPDATES, 
       MINIMUM_DISTANCE_CHANGE_FOR_UPDATES, 
       this.locationL 
     ); 

     Toast.makeText(getBaseContext(), "New Trip Started.", Toast.LENGTH_SHORT).show(); 

    } 

    public String getNewFileName(){ 
     SimpleDateFormat sdfDateTime = new SimpleDateFormat("yyyyMMddHHmmss"); 
     return sdfDateTime.format(new Date(System.currentTimeMillis()));  
    } 

    public void tripEnd(){ 
     LbsGeocodingActivity.this.lm.removeUpdates(this.locationL); 
     Toast.makeText(getBaseContext(), "Trip Ended.", Toast.LENGTH_SHORT).show(); 
    } 

    protected void showCurrentLocation() { 
     try{ 
      Location location = LbsGeocodingActivity.this.lm.getLastKnownLocation(LocationManager.NETWORK_PROVIDER); 

      if (location != null) { 
       String show_curent = "Longitude: " + location.getLongitude() 
             + " | Latitude: " + location.getLatitude(); 

       //LbsGeocodingActivity.this.tv.append(show_curent); 

       Toast.makeText(getBaseContext(), show_curent, Toast.LENGTH_SHORT).show(); 

       //LbsGeocodingActivity.this.ScreenOutputCount = LbsGeocodingActivity.this.ScreenOutputCount + 1; 
      }else{ 
       Toast.makeText(getBaseContext(), "Last Know Location Not Found.", Toast.LENGTH_SHORT).show(); 
      } 
     }catch(NullPointerException e){ 
      Log.e("Android Button Tutorial", e.toString()); 
     } 
    } 

    private class MyLocationListener implements LocationListener { 

     public void onLocationChanged(Location location) { 
      LbsGeocodingActivity.this.tv.append(LbsGeocodingActivity.this.ScreenOutputCount 
        + " | Longitude: " + location.getLongitude() 
        + " | Latitude: " + location.getLatitude() + "\n"); 

      LbsGeocodingActivity.this.ScreenOutputCount = LbsGeocodingActivity.this.ScreenOutputCount + 1; 

      logLocationUpdate(location.getLongitude(), location.getLatitude()); 
     } 

     public void logLocationUpdate(double longitude, double latitude){ 
      try { 

       SimpleDateFormat sdfDateTime = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss"); 
       String timestamp = sdfDateTime.format(new Date(System.currentTimeMillis())); 

       String logString = timestamp + "::" + 
            longitude + "::" + 
            latitude + "\n"; 

       String sdcard = Environment.getExternalStorageDirectory() + "/Android/GpsTracker/"; 

       //then write the file 
       final String TESTSTRING = new String(logString); 

       File gpxfile = new File(sdcard, LbsGeocodingActivity.this.newTrip + ".txt"); 
       FileWriter gpxwriter = new FileWriter(gpxfile, true); 
       BufferedWriter out = new BufferedWriter(gpxwriter); 
       out.write(TESTSTRING); 
       out.close(); 

      }catch(Exception e){ 
       Log.e("GPS Tracker", e.getMessage()); 
      } 
     } 
     public void onStatusChanged(String s, int i, Bundle b) { 
      /* 
      Toast.makeText(LbsGeocodingActivity.this, "Provider status changed", 
        Toast.LENGTH_LONG).show(); 
      */ 
     } 

     public void onProviderDisabled(String s) { 
      Toast.makeText(LbsGeocodingActivity.this, 
        "Provider disabled by the user. GPS turned off", 
        Toast.LENGTH_LONG).show(); 
     } 

     public void onProviderEnabled(String s) { 
      Toast.makeText(LbsGeocodingActivity.this, 
        "Provider enabled by the user. GPS turned on", 
        Toast.LENGTH_LONG).show(); 
     } 

    } 

} 

回答

3

通過將其設置爲5000毫秒,這並不一定意味着您將每隔5秒獲取一次位置。時間或多或少是最好的情況。

minTime接收通知的最小時間間隔,以毫秒爲單位。此字段僅用作節省電量的提示,位置更新之間的實際時間可能大於或小於此值。 http://developer.android.com/reference/android/location/LocationManager.html

您確定自己的活動正在運行?如果您想在活動休眠時接收位置,則需要喚醒鎖和服務。

例如,在GPS應用程序,我創建我把0毫秒儘快但是在調試和檢查logcat的時候我有時會收到的位置每分鐘左右,不是每一秒得到它。

3

如前所述大衛·奧爾森,MINIMUM_TIME_BETWEEN_UPDATES只是阻止請求聽衆過於頻繁。如果你想經常requestLocationUpdates,你應該使用TimerTimerTask並有requestLocationUpdates運行每5秒

schedule(TimerTask task, long delay, long period) 
Schedules the specified task for repeated fixed-delay execution, beginning after the specified delay. 
一次