Итак, меня попросили сделать Tracker Location. Отслеживание местоположения должно отслеживаться, даже если приложение настроено ... Моя идея - запустить мою собственную услугу (позвоните на нее TrackingService) из своей деятельности, вызвав startService (намерение); поэтому служба будет работать вечно (я думаю ..), а затем подключиться к службе определения местоположения из моего собственного созданного TrackingService. TrackingService должен прослушивать изменения местоположения после отключения приложения. Я пишу код, запускал TrackingService и запрашивал обновления местоположений в новом потоке. В любом случае, обновление местоположений останавливается после выхода из приложения, но служба все еще работает.сервис, который слушает для службы определения местоположения
EDIT: Итак, мне удалось немного улучшить код, поэтому теперь, когда мое приложение запущено, я получаю журнал, что мой поток (который работает в отдельной службе) запущен и получает обновления местоположения. Когда я закрываю приложение, я все равно получаю сообщение о том, что мой поток запущен, но он не получает обновлений местоположения ... Любой может указать мне причину, почему? P.S. Я знаю, что, вероятно, есть лучшие способы выполнить эту работу, но я действительно надеюсь исправить свой код. Здесь идет о классе услуги
public class TrackingService extends Service {
// DEBUG
public final static String TAG = "TrackingService";
public final static boolean D = true;
// Global constants
private static final long UPDATE_INTERVAL = 10000; // Update frequency in milliseconds
private static final long FASTEST_INTERVAL = 4000; // A fast frequency ceiling in milliseconds
//
int mStartMode; // indicates how to behave if the service is killed
private final IBinder mBinder = new LocalBinder(); // interface for clients that bind
boolean mAllowRebind; // indicates whether onRebind should be used
private int number; // testavimui
LocationThread mLocationThread;
@Override
public void onCreate() {
if (D) {Log.d(TAG, "service - onCreated started");};
mLocationThread = new LocationThread(this);
mLocationThread.start();
// mLocationThread.run();
}
@Override
public int onStartCommand(Intent intent, int flags, int startId) {
if (D) {Log.d(TAG, "service - onStartCommand started");};
// The service is starting, due to a call to startService()
return mStartMode;
}
@Override
public IBinder onBind(Intent intent) {
if (D) {Log.d(TAG, "service - onBind started");};
// A client is binding to the service with bindService()
return mBinder;
}
@Override
public boolean onUnbind(Intent intent) {
if (D) {Log.d(TAG, "service - onUnBind started");};
// All clients have unbound with unbindService()
return mAllowRebind;
}
@Override
public void onRebind(Intent intent) {
if (D) {Log.d(TAG, "service - onReBind started");};
// A client is binding to the service with bindService(),
// after onUnbind() has already been called
}
@Override
public void onDestroy() {
if (D) {Log.d(TAG, "service - onDestroy started");};
// The service is no longer used and is being destroyed
mLocationThread.cancel();
}
public class LocalBinder extends Binder {
TrackingService getService() {
// Return this instance of LocalService so clients can call public methods
return TrackingService.this;
}
}
public int number(){
number += 1;
return number;
}
private class LocationThread extends Thread implements
GooglePlayServicesClient.ConnectionCallbacks,
GooglePlayServicesClient.OnConnectionFailedListener,
LocationListener{
private boolean keepOn;
private Context mContext;
private LocationClient mLocationClient;
private LocationRequest mLocationRequest;
public LocationThread (Context context){
mContext = context;
keepOn = true;
}
public void cancel() {
keepOn = false;
if (D){Log.d(TAG, "thread was canceled");};
}
public void run(){
mLocationRequest = LocationRequest.create();
mLocationRequest.setPriority(LocationRequest.PRIORITY_HIGH_ACCURACY); // Use high accuracy
mLocationRequest.setInterval(UPDATE_INTERVAL); // Set the update interval to 5 seconds
mLocationRequest.setFastestInterval(FASTEST_INTERVAL); // Set the fastest update interval to 1 second
mLocationClient = new LocationClient(mContext, this, this);
mLocationClient.connect();
while (keepOn){
try {
Thread.sleep(10000);
if(D){Log.d(TAG, "thread running");};
} catch (Exception e){
}
}
}
@Override
public void onConnectionFailed(ConnectionResult result) {
if(D){Log.d(TAG, "connection failed");};
}
@Override
public void onConnected(Bundle connectionHint) {
if(D){Log.d(TAG, "connected to location service");};
mLocationClient.requestLocationUpdates(mLocationRequest, this);
}
@Override
public void onDisconnected() {
if(D){Log.d(TAG, "disconnected from location service");};
}
@Override
public void onLocationChanged(Location location) {
if(D){Log.d(TAG, "Location changed");};
}
}
}
Я не совсем понимаю, как вы ожидаете, что он будет себя вести? Вы имеете в виду, что он обновляется при первом запуске вашей работы, но не в последующие моменты? – Piovezan
Я планирую обновить местоположение и сохранить его в PolylineOptions и передать PolylineOptions обратно в действие, когда дело доходит до жизни. Но это будущая задача. прямо сейчас я просто нуждаюсь в доказательстве того, что местоположение обновляется, когда приложение уничтожено. Я считаю, что мой поток работает неправильно. – PauliusM