Я хочу постоянно отслеживать местоположение пользователя даже после того, как он закроет приложение. Служба постоянно хранит местоположение в БД, и при пробуждении запускается временная задача, чтобы загрузить его на сервер. я использовал
LocationServices.FusedLocationApi.requestLocationUpdates(Utils.googleApiClient,
mlocationrequest, this);
на сервисе. Я объявил обслуживание в манифесте как
<service
android:name = "com.projest.services.BackgroundService"
android:enabled = "true"
android:process = ":Background">
</service>
и вызвал servicew для моей основной деятельности, используя
Intent service = new Intent(this, BackgroundService.class);
startService(service);
но сервис не работает. Я не видел журнала.
public class BackgroundService extends Service implements LocationListener{
public static final String TAG = "BackgroundService";
Context context;
LocationRequest mlocationrequest;
private static int UPDATE_INTERVAL = 10000; // 10 sec
private static int FATEST_INTERVAL = 5000; // 5 sec
public BackgroundService(Context context){
this.context = context;
}
public BackgroundService(){
}
public void onCreate(){
try{
super.onCreate();
if (Utils.DEBUG)Log.d(TAG,"inside onCreate");
}catch(Exception e){
if (Utils.DEBUG)Log.d(TAG,"problem oncreate");
}
}
public int onStartCommand(){
if (Utils.DEBUG)Log.d(TAG,"inside onStartCommand");
if (!Utils.startGpsTracker)
{
Utils.startGpsTracker=true;
toggleGPS(true);
}
buildGoogleApiClient();
Utils.googleApiClient.connect();
if (Utils.googleApiClient.isConnected()) {
startLocationUpdates();
}
return START_STICKY;
}
public void onConnected(Bundle connectionHint) {
Log.i(TAG, "Connected to GoogleApiClient");
if (Utils.latestLocation == null) {
Utils.latestLocation = LocationServices.FusedLocationApi.getLastLocation(Utils.googleApiClient);
if (Utils.DEBUG)Log.d(TAG,"inside onconnected");
try {
storeGpsinDb();
if (Utils.DEBUG)Log.d(TAG,"trouble opening storeGPS");
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
startLocationUpdates();
}
private void startLocationUpdates() {
// TODO Auto-generated method stub
try {
if (Utils.googleApiClient.isConnected()) {
LocationServices.FusedLocationApi.requestLocationUpdates(Utils.googleApiClient, mlocationrequest, this);
if (Utils.DEBUG)Log.d(TAG,"inside startlocationupdates");
}
} catch (SecurityException ex) {
}
}
@Override
public void onLocationChanged(Location location) {
Utils.latestLocation = location;
try {
storeGpsinDb();
if (Utils.DEBUG)Log.d(TAG,"inside onlocationchanged");
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
protected synchronized void buildGoogleApiClient() {
if (Utils.googleApiClient == null) {
Utils.googleApiClient = new GoogleApiClient.Builder(this.context).addApi(LocationServices.API).build();
if (Utils.DEBUG)Log.d(TAG,"googleAPIclient");
}
createLocationRequest();
}
private void createLocationRequest() {
// TODO Auto-generated method stub
mlocationrequest = new LocationRequest();
mlocationrequest.setInterval(UPDATE_INTERVAL);
mlocationrequest.setFastestInterval(FATEST_INTERVAL);
mlocationrequest.setPriority(LocationRequest.PRIORITY_HIGH_ACCURACY);
if (Utils.DEBUG)Log.d(TAG,"inside createlocationrequest");
}
public void onConnectionSuspended(int cause) {
Utils.googleApiClient.connect();
if (Utils.DEBUG)Log.d(TAG,"insise connectionsuspended");
}
@Override
public void onDestroy() {
if (Utils.DEBUG)Log.d(TAG,"inside onDestroy");
stopLocationUpdates();
Utils.googleApiClient.disconnect();
super.onDestroy();
}
protected void stopLocationUpdates() {
if (Utils.googleApiClient.isConnected()) {
LocationServices.FusedLocationApi.removeLocationUpdates(Utils.googleApiClient, this);
}
}
@Override
public IBinder onBind(Intent intent) {
// TODO Auto-generated method stub
return null;
}
private void toggleGPS(boolean enable) {
String provider = Settings.Secure.getString(context.getContentResolver(),Settings.Secure.LOCATION_PROVIDERS_ALLOWED);
if (Utils.DEBUG)System.out.println("toggleGPS:" + provider);
if (provider.contains("gps") == enable) {
if (Utils.DEBUG)System.out.println("toggleGPS:enable true");
return; // the GPS is already in the requested state
}
if (Utils.DEBUG)System.out.println("toggleGPS:enable false");
final Intent poke = new Intent();
poke.setClassName("com.android.settings",
"com.android.settings.widget.SettingsAppWidgetProvider");
poke.addCategory(Intent.CATEGORY_ALTERNATIVE);
poke.setData(Uri.parse("3"));
this.context.sendBroadcast(poke);
}
private void storeGpsinDb() throws IOException {
if (!(Utils.latestLocation==null)) {
}else{
}
// }
}
}
Какую ошибку я делаю Я работаю над этим две недели, пожалуйста, помогите мне.




вам нужно определить android: stopWithTask = "ложь" в манифесте.
процесс (потоки), запущенный из службы, перестанет работать, если ваше приложение будет удалено из последних приложений. Чтобы ваши процессы (потоки) всегда оставались в рабочем состоянии, вам необходимо переопределить метод onTaskRemoved () и добавить код для перезапуска задач, как показано ниже.
@Override
public void onTaskRemoved(Intent rootIntent){
Intent restartServiceTask = new Intent(getApplicationContext(),this.getClass());
restartServiceTask.setPackage(getPackageName());
PendingIntent restartPendingIntent =PendingIntent.getService(getApplicationContext(), 1,restartServiceTask, PendingIntent.FLAG_ONE_SHOT);
AlarmManager myAlarmService = (AlarmManager) getApplicationContext().getSystemService(Context.ALARM_SERVICE);
myAlarmService.set(
AlarmManager.ELAPSED_REALTIME,
SystemClock.elapsedRealtime() + 1000,
restartPendingIntent);
super.onTaskRemoved(rootIntent);
}