位置通过服务更新

时间:2014-04-06 10:33:34

标签: android service location

我正在尝试在我的应用关闭时在后台获取位置更新。我通过服务尝试这个。我的应用程序打开时工作正常,但当我关闭它时,服务似乎也会关闭。

这就是我使用的代码:

MainActivity:

public class MainActivity extends Activity {

@Override
protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.activity_main);
    Intent intent = new Intent(this, MyService.class);
    startService(intent);
}

为MyService:

public class MyService extends Service {

public static final String BROADCAST_ACTION = "Hello World";
private static final int TWO_MINUTES = 1000 * 60 * 2;
public LocationManager locationManager;
public MyLocationListener listener;
public Location previousBestLocation = null;
private String provider;


@Override
public void onCreate() {
super.onCreate();
intent = new Intent(BROADCAST_ACTION);      
}

@Override
public void onStart(Intent intent, int startId) {      
locationManager = (LocationManager) getSystemService(Context.LOCATION_SERVICE);
listener = new MyLocationListener();    
provider = locationManager.getBestProvider(new Criteria(), false);
locationManager.requestLocationUpdates(provider, 0, 0, listener);
}

@Override
public int onStartCommand(Intent intent, int flags, int startId)
{
super.onStartCommand(intent, flags, startId);       
return START_STICKY;
}

@Override
public IBinder onBind(Intent intent) {
return null;
}

protected boolean isBetterLocation(Location location, Location currentBestLocation) {
if (currentBestLocation == null) {
    // A new location is always better than no location
    return true;
}

// Check whether the new location fix is newer or older
long timeDelta = location.getTime() - currentBestLocation.getTime();
boolean isSignificantlyNewer = timeDelta > TWO_MINUTES;
boolean isSignificantlyOlder = timeDelta < -TWO_MINUTES;
boolean isNewer = timeDelta > 0;

// If it's been more than two minutes since the current location, use the new location
// because the user has likely moved
if (isSignificantlyNewer) {
    return true;
// If the new location is more than two minutes older, it must be worse
} else if (isSignificantlyOlder) {
    return false;
}

// Check whether the new location fix is more or less accurate
int accuracyDelta = (int) (location.getAccuracy() - currentBestLocation.getAccuracy());
boolean isLessAccurate = accuracyDelta > 0;
boolean isMoreAccurate = accuracyDelta < 0;
boolean isSignificantlyLessAccurate = accuracyDelta > 200;

// Check if the old and new location are from the same provider
boolean isFromSameProvider = isSameProvider(location.getProvider(),
        currentBestLocation.getProvider());

// Determine location quality using a combination of timeliness and accuracy
if (isMoreAccurate) {
    return true;
} else if (isNewer && !isLessAccurate) {
    return true;
} else if (isNewer && !isSignificantlyLessAccurate && isFromSameProvider) {
    return true;
}
return false;
}


@Override
public void onDestroy() {       
// handler.removeCallbacks(sendUpdatesToUI);     
super.onDestroy();
Log.v("STOP_SERVICE", "DONE");
locationManager.removeUpdates(listener);        
}   

public static Thread performOnBackgroundThread(final Runnable runnable) {
final Thread t = new Thread() {
    @Override
    public void run() {
        try {
            runnable.run();
        } finally {

        }
    }
};
t.start();
return t;
}


public class MyLocationListener implements LocationListener
{

public void onLocationChanged(final Location loc)
{
    Log.i("MyService", "Location changed");
    // do something  

    }                               
}

public void onProviderDisabled(String provider)
{
}


public void onProviderEnabled(String provider)
{
 }


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

}
}
}

1 个答案:

答案 0 :(得分:0)

尝试实施前台服务。 foreground service

前台服务会显示通知,并且在您需要之前永远不会停止。

在您的服务中实施此代码段

Notification notification = new Notification(R.drawable.icon, getText(R.string.ticker_text),
        System.currentTimeMillis());
Intent notificationIntent = new Intent(this, ExampleActivity.class);
PendingIntent pendingIntent = PendingIntent.getActivity(this, 0, notificationIntent, 0);
notification.setLatestEventInfo(this, getText(R.string.notification_title),
        getText(R.string.notification_message), pendingIntent);
startForeground(ONGOING_NOTIFICATION_ID, notification);