如何在谷歌地图android API v2的后台访问位置变化



在我的应用程序中,我使用谷歌地图android API v2,我必须获得当前位置坐标在位置的变化,即使我的应用程序在后台,做一定的任务。我该怎么做呢?

编辑:

这是我的代码跟踪位置

LocationService.java

public class LocationService extends Service {
String TAG = "LocationService";
LocationManager mylocManager;
LocationTracker mylocListener;  
String myprovider;
database obj = new database(this);
@Override
public IBinder onBind(Intent arg0) 
{
    return null;
}
@Override
public void onDestroy() 
{    
    super.onDestroy();
    if(mylocManager!=null)
    {
        mylocManager.removeUpdates(mylocListener);
    }
}
@Override
public int onStartCommand(Intent intent, int flags, int startId) 
{
    mylocManager   = (LocationManager)getSystemService(Context.LOCATION_SERVICE);
    mylocListener  = new LocationTracker();
    Location loc = null;
    for(String myprovider:mylocManager.getAllProviders())
    {
       loc = mylocManager.getLastKnownLocation(myprovider);
       if(loc!=null)
       {
           Log.d(TAG,"Updating with last known location");
           updateLocation(loc);
           break;
       }   
    }
    if(Build.FINGERPRINT.contains("generic"))
    {
        Log.d(TAG,"App running on emulator");
        mylocManager.requestLocationUpdates( LocationManager.GPS_PROVIDER, 0, 0, mylocListener);            
    }
    else if(mylocManager.isProviderEnabled(LocationManager.NETWORK_PROVIDER))
    {
        Log.d(TAG,"GPS Provider available");
        mylocManager.requestLocationUpdates(LocationManager.GPS_PROVIDER, 0, 0, mylocListener);
    }
    else if(mylocManager.isProviderEnabled(LocationManager.GPS_PROVIDER))
    {
         Log.d(TAG,"NETWORK Provider available");
        mylocManager.requestLocationUpdates(LocationManager.NETWORK_PROVIDER, 0, 0, mylocListener);
    }
    else
    {
        Log.w(TAG,"No provider found. Stopping service");
        stopSelf();
    }  
    return super.onStartCommand(intent, flags, startId);
}


public class LocationTracker  implements LocationListener
{
    @Override
    public void onLocationChanged(Location loc)
    {
        Log.d(TAG,"Updating exact coordinates");
        Toast.makeText(getApplicationContext(), "Location changed", Toast.LENGTH_SHORT).show();
        updateLocation(loc);
        stopSelf();
    }
    @Override
    public void onProviderDisabled(String arg0) 
    {
        stopSelf();
    }
    @Override
    public void onProviderEnabled(String arg0)
    {
    }
    @Override
    public void onStatusChanged(String arg0, int arg1, Bundle arg2)
    {
    }
}
}

您必须创建一个即使应用程序在后台也能运行的Service。这个Service必须实现或拥有一个LocationListener对象。

onLocationChanged被触发时,您可以执行您的任务,因为这表明您已经收到了一个新的位置更新。

相关内容

  • 没有找到相关文章

最新更新