从后台服务android中查找当前位置

时间:2012-11-09 20:43:35

标签: android service geolocation location background-process

我想找到当前位置,并通过后台服务活动将其与我数据库中的某些数据进行比较......但不知道如何做到这一点......所以请给我一些建议......这是我目前的表现如何

    package com.example.alert;

    import android.app.Service;
    import android.content.Context;
    import android.content.Intent;
    import android.location.Location;
    import android.location.LocationListener;
    import android.location.LocationManager;
    import android.media.MediaPlayer;
    import android.os.Bundle;
    import android.os.IBinder;
    import android.widget.Toast;

    public class service extends Service{
LocationManager lm = (LocationManager)getSystemService(Context.LOCATION_SERVICE);

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

public void onCreate() {
    Toast.makeText(this, "Background Service Created", Toast.LENGTH_LONG).show();



}

public void onDestroy() {
    Toast.makeText(this, "My Service Stopped", Toast.LENGTH_LONG).show();


}

public void onStart(Intent intent, int startid) {

    Toast.makeText(this, "My Service Started", Toast.LENGTH_LONG).show();
    LocationListener ll = new MyLocationListener();
    //lm.requestLocationUpdates( LocationManager.GPS_PROVIDER, 5*60*10000, 0, ll);
    lm.requestLocationUpdates( LocationManager.GPS_PROVIDER, 0, 0, ll);



}


public class MyLocationListener implements LocationListener
{

    public void onLocationChanged(Location loc)
    {
        if(loc!=null)
        {
            double x;


            String Text = "My current location is: " +"Latitud = " + loc.getLatitude() +"Longitud = " + loc.getLongitude();
            Toast.makeText( getApplicationContext(),Text,Toast.LENGTH_SHORT).show();
        /*  cr.moveToFirst();
            while(!cr.isAfterLast()) {
                 al.add(cr.getString(cr.getColumnIndex(dbAdapter.KEY_NAME))); //add the item
                 cr.moveToNext();
            }*/
        //  lm.addProximityAlert(loc.getLatitude(), loc.getLongitude(), 10009,, intent)

            //for loop, alerters retrieving one by one
//      x= calcDistance(loc.getLatitude(),loc.getLongitude(),z,y);
    //      if(x<1){
        //        Intent myIntent = new Intent(ViewAlerters.this,CallMode.class);
          //        startActivity(myIntent);
            }

        }



    public void onProviderDisabled(String arg0) {
        // TODO Auto-generated method stub

    }

    public void onProviderEnabled(String provider) {
        // TODO Auto-generated method stub

    }

    public void onStatusChanged(String provider, int status, Bundle extras) {
        // TODO Auto-generated method stub

    }


    }
    }

1 个答案:

答案 0 :(得分:0)

Reto Meier(Android Developer Relations)在这方面做了大量工作,我建议你看一下。

博客http://android-developers.blogspot.com/2011/06/deep-dive-into-location.html

示例代码https://code.google.com/p/android-protips-location/