使用服务记录位置坐标

时间:2015-03-13 23:27:50

标签: android service location

伙计我正在尝试创建一个记录您的位置的应用程序'使用位置类和服务类进行坐标,但它不起作用!

我不知道如何开始!!!

这是我的服务文件:

public class LocationService extends Service {


private static final long ONE_MIN = 1000 * 60;
private static final long TWO_MIN = ONE_MIN * 2;
private static final long FIVE_MIN = ONE_MIN * 5;
private static final long MEASURE_TIME = 1000 * 30;
private static final long POLLING_FREQ = 1000 * 10;
private static final float MIN_ACCURACY = 25.0f;
private static final float MIN_LAST_READ_ACCURACY = 500.0f;
private static final float MIN_DISTANCE = 10.0f;
private static final int NOTIFICATION_ID = 1;
// Current best location estimate
    private Location mBestReading;


    WIWDb db;
    // Reference to the LocationManager and LocationListener
    private LocationManager mLocationManager;
    private LocationListener mLocationListener;

    private final String TAG = "LocationGetLocationActivity";

    private boolean mFirstUpdate = true;
@SuppressLint("NewApi") @Override
public void onCreate() {
    super.onCreate();
    Log.i(TAG,"here");
        db=new WIWDb(this);

    // Acquire reference to the LocationManager
    if (null == (mLocationManager = (LocationManager) getSystemService(Context.LOCATION_SERVICE)))
        Toast.makeText(getBaseContext(), "Error", Toast.LENGTH_LONG).show();

    // Get best last location measurement
    mBestReading = bestLastKnownLocation(MIN_LAST_READ_ACCURACY, FIVE_MIN);

    // Display last reading information
    if (null != mBestReading) {

        updateDisplay(mBestReading);

    } else {

        Toast.makeText(getBaseContext(),"No Initial Reading Available",Toast.LENGTH_LONG).show();
        //mAccuracyView.setText("No Initial Reading Available");

    }

    mLocationListener = new LocationListener() {

        // Called back when location changes

        public void onLocationChanged(Location location) {


            // Determine whether new location is better than current best
            // estimate

            if (null == mBestReading
                    || location.getAccuracy() < mBestReading.getAccuracy()) {

                // Update best estimate
                mBestReading = location;

                // Update display
                updateDisplay(location);

                if (mBestReading.getAccuracy() < MIN_ACCURACY)
                    mLocationManager.removeUpdates(mLocationListener);

            }
        }

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

        public void onProviderEnabled(String provider) {
            // NA
        }

        public void onProviderDisabled(String provider) {
            // NA
        }
    };


    // Create a notification area notification so the user 
            // can get back to the MusicServiceClient

            final Intent notificationIntent = new Intent(getApplicationContext(),
                    MainActivity.class);
            final PendingIntent pendingIntent = PendingIntent.getActivity(this, 0,
                    notificationIntent, 0);

            final Notification notification = new Notification.Builder(
                    getApplicationContext())
                    .setSmallIcon(android.R.drawable.ic_menu_compass)
                    .setOngoing(true).setContentTitle("Location tracking...")
                    .setContentText("Back to WIW")
                    .setContentIntent(pendingIntent).build();

            // Put this Service in a foreground state, so it won't 
            // readily be killed by the system  
            startForeground(NOTIFICATION_ID, notification);


}

private Location bestLastKnownLocation(float minAccuracy, long maxAge) {

    Location bestResult = null;
    float bestAccuracy = Float.MAX_VALUE;
    long bestAge = Long.MIN_VALUE;

    List<String> matchingProviders = mLocationManager.getAllProviders();

    for (String provider : matchingProviders) {

        Location location = mLocationManager.getLastKnownLocation(provider);

        if (location != null) {

            float accuracy = location.getAccuracy();
            long time = location.getTime();

            if (accuracy < bestAccuracy) {

                bestResult = location;
                bestAccuracy = accuracy;
                bestAge = time;

            }
        }
    }

    // Return best reading or null
    if (bestAccuracy > minAccuracy
            || (System.currentTimeMillis() - bestAge) > maxAge) {
        return null;
    } else {
        return bestResult;
    }
}

@SuppressWarnings("deprecation")
private void updateDisplay(Location location) {

    StringBuilder sb=new StringBuilder();
    sb.append("Accuracy:" + location.getAccuracy());
    //mAccuracyView.setText("Accuracy:" + location.getAccuracy());
    sb.append("Time:"+ new SimpleDateFormat("MM/dd/yyyy HH:mm:ss", Locale.getDefault()).format(new Date(location.getTime())));
    //mTimeView.setText("Time:"+ new SimpleDateFormat("MM/dd/yyyy HH:mm:ss", Locale.getDefault()).format(new Date(location.getTime())));
    sb.append("Longitude:" + location.getLongitude());
    //mLatView.setText("Longitude:" + location.getLongitude());
sb.append("Latitude:" + location.getLatitude());
    //mLngView.setText("Latitude:" + location.getLatitude());

  //db.insertCordsToDb(String.valueOf(location.getLongitude())+","+String.valueOf(    location.getLatitude()),String.valueOf(new Date().getDate())     ,String.valueOf(location.getTime()));
db.insertCordsToDb(String.valueOf(location.getLongitude())+","+String.valueOf(lo     cation.getLatitude()),new SimpleDateFormat("MM/dd/yyyy",     Locale.getDefault()).format(new Date(location.getTime())) ,new   SimpleDateFormat("HH:mm:ss", Locale.getDefault()).format(new   Date(location.getTime())));
}



protected void onResume() {


    // Determine whether initial reading is
    // "good enough". If not, register for
    // further location updates

    if (null == mBestReading
            || mBestReading.getAccuracy() > MIN_LAST_READ_ACCURACY
            || mBestReading.getTime() < System.currentTimeMillis()
                    - TWO_MIN) {

        // Register for network location updates
        if (null != mLocationManager
                .getProvider(LocationManager.NETWORK_PROVIDER)) {
            mLocationManager.requestLocationUpdates(
                    LocationManager.NETWORK_PROVIDER, POLLING_FREQ,
                    MIN_DISTANCE, mLocationListener);
        }

        // Register for GPS location updates
        if (null != mLocationManager
                .getProvider(LocationManager.GPS_PROVIDER)) {
            mLocationManager.requestLocationUpdates(
                    LocationManager.GPS_PROVIDER, POLLING_FREQ,
                    MIN_DISTANCE, mLocationListener);
        }

        // Schedule a runnable to unregister location listeners
        Executors.newScheduledThreadPool(1).schedule(new Runnable() {

            @Override
            public void run() {

                Log.i(TAG, "location updates cancelled");

                mLocationManager.removeUpdates(mLocationListener);

            }
        }, MEASURE_TIME, TimeUnit.MILLISECONDS);
    }
}

// Unregister location listeners



@Override
public IBinder onBind(Intent intent) {
    // TODO Auto-generated method stub
    return null;
}


}

请指导完成此申请

0 个答案:

没有答案
相关问题