私のアプリでは、Google Maps 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)
{
}
}
}