как создать сервис для обновления местоположения в фоновом режиме

public class MainActivity extends AppCompatActivity {
private static String lat_long_time="";
private static final String TAG = MainActivity.class.getSimpleName();

private static final int PERMISSION_REQUEST_CODE = 1;

private static final int REQUEST_PERMISSIONS_REQUEST_CODE = 34;


private static final int REQUEST_CHECK_SETTINGS = 0x1;


private static final long UPDATE_INTERVAL_IN_MILLISECONDS = 5000;

private static final long FASTEST_UPDATE_INTERVAL_IN_MILLISECONDS =
        UPDATE_INTERVAL_IN_MILLISECONDS / 2;

private final static String KEY_REQUESTING_LOCATION_UPDATES = "requesting-location-updates";
private final static String KEY_LOCATION = "location";
private final static String KEY_LAST_UPDATED_TIME_STRING = "last-updated-time-string";

private FusedLocationProviderClient mFusedLocationClient;

private SettingsClient mSettingsClient;

private LocationRequest mLocationRequest;

private LocationSettingsRequest mLocationSettingsRequest;

private LocationCallback mLocationCallback;

private Location mCurrentLocation;

private Button mStartUpdatesButton;
private TextView mLastUpdateTimeTextView;
private TextView mLatitudeTextView;
private TextView mLongitudeTextView;

private String mLatitudeLabel;
private String mLongitudeLabel;
private String mLastUpdateTimeLabel;

private Boolean mRequestingLocationUpdates;
private String mLastUpdateTime;

@Override
public void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.main_activity);
    Toolbar toolbar = (Toolbar) findViewById(R.id.toolbar);
    setSupportActionBar(toolbar);

    if(!checkPermissionForStorage()){
        requestPermissionForStorage();
    }

    mStartUpdatesButton = (Button) 
    findViewById(R.id.start_updates_button);
    findViewById(R.id.stop_updates_button);
    mLatitudeTextView = (TextView) findViewById(R.id.latitude_text);
    mLongitudeTextView = (TextView) findViewById(R.id.longitude_text);
    mLastUpdateTimeTextView = (TextView) 
    findViewById(R.id.last_update_time_text);
    mLatitudeLabel = 
    getResources().getString(R.string.latitude_label);
    mLongitudeLabel = 
    getResources().getString(R.string.longitude_label);
    mLastUpdateTimeLabel = 
    getResources().getString(R.string.last_update_time_label);

    mRequestingLocationUpdates = false;
    mLastUpdateTime = "";
    updateValuesFromBundle(savedInstanceState);

    mFusedLocationClient = 
    LocationServices.getFusedLocationProviderClient(this);
    mSettingsClient = LocationServices.getSettingsClient(this);
    LocationRequest, and
    createLocationCallback();
    createLocationRequest();
    buildLocationSettingsRequest();
    }
    private void updateValuesFromBundle(Bundle savedInstanceState) {
    if (savedInstanceState != null) {
    if (savedInstanceState.keySet().contains(KEY_REQUESTING_LOCATION_UPDATES)) {
            mRequestingLocationUpdates = savedInstanceState.getBoolean(
                    KEY_REQUESTING_LOCATION_UPDATES);
        }

        if (savedInstanceState.keySet().contains(KEY_LOCATION)) {

убедитесь, что mCurrentLocation mCurrentLocation = saveInstanceState.getParcelable(KEY_LOCATION); } if (savedInstanceState.keySet().contains(KEY_LAST_UPDATED_TIME_STRING)) { mLastUpdateTime = saveInstanceState.getString(KEY_LAST_UPDATED_TIME_STRING); } обновитьUI(); } }

private void createLocationRequest() {
    mLocationRequest = new LocationRequest();

    mLocationRequest.setInterval(UPDATE_INTERVAL_IN_MILLISECONDS);
    mLocationRequest.setFastestInterval(FASTEST_UPDATE_INTERVAL_IN_MILLISECONDS);

    mLocationRequest.setPriority(LocationRequest.PRIORITY_HIGH_ACCURACY);
}

private void createLocationCallback() {
    mLocationCallback = new LocationCallback() {
        @Override
        public void onLocationResult(LocationResult locationResult) {
            super.onLocationResult(locationResult);

            mCurrentLocation = locationResult.getLastLocation();
            mLastUpdateTime = DateFormat.getTimeInstance().format(new Date());
            updateLocationUI();
        }
    };
}
private void buildLocationSettingsRequest() {
    LocationSettingsRequest.Builder builder = new LocationSettingsRequest.Builder();
    builder.addLocationRequest(mLocationRequest);
    mLocationSettingsRequest = builder.build();
}

@Override
protected void onActivityResult(int requestCode, int resultCode, Intent data) {
    switch (requestCode) {

startResolutionForResult(). case REQUEST_CHECK_SETTINGS: switch (resultCode) { case Activity.RESULT_OK: Log.i(TAG, «Пользователь согласился внести необходимые изменения в настройки местоположения»); ломать; case Activity.RESULT_CANCELED: Log.i(TAG, "Пользователь решил не вносить необходимые изменения в настройки местоположения."); mRequestingLocationUpdates = ложь; обновитьUI(); ломать; } ломать; } }

public void startUpdatesButtonHandler(View view) {
    if (!mRequestingLocationUpdates) {
        mRequestingLocationUpdates = true;
        setButtonsEnabledState();
        startLocationUpdates();
    }
}



private void startLocationUpdates() {
    mSettingsClient.checkLocationSettings(mLocationSettingsRequest)
            .addOnSuccessListener(this, new OnSuccessListener<LocationSettingsResponse>() {
                @Override
                public void onSuccess(LocationSettingsResponse locationSettingsResponse) {
                    Log.i(TAG, "All location settings are satisfied.");

                    //noinspection MissingPermission
                    mFusedLocationClient.requestLocationUpdates(mLocationRequest,
                            mLocationCallback, Looper.myLooper());

                    updateUI();
                }
            })
            .addOnFailureListener(this, new OnFailureListener() {
                @Override
                public void onFailure(@NonNull Exception e) {
                    int statusCode = ((ApiException) e).getStatusCode();
                    switch (statusCode) {
                        case LocationSettingsStatusCodes.RESOLUTION_REQUIRED:
                            Log.i(TAG, "Location settings are not satisfied. Attempting to upgrade " +
                                    "location settings ");
                            try {
                                // Show the dialog by calling startResolutionForResult(), and check the
                                // result in onActivityResult().
                                ResolvableApiException rae = (ResolvableApiException) e;
                                rae.startResolutionForResult(MainActivity.this, REQUEST_CHECK_SETTINGS);
                            } catch (IntentSender.SendIntentException sie) {
                                Log.i(TAG, "PendingIntent unable to execute request.");
                            }
                            break;
                        case LocationSettingsStatusCodes.SETTINGS_CHANGE_UNAVAILABLE:
                            String errorMessage = "Location settings are inadequate, and cannot be " +
                                    "fixed here. Fix in Settings.";
                            Log.e(TAG, errorMessage);
                            Toast.makeText(MainActivity.this, errorMessage, Toast.LENGTH_LONG).show();
                            mRequestingLocationUpdates = false;
                    }

                    updateUI();
                }
            });
}


private void updateUI() {
    setButtonsEnabledState();
    updateLocationUI();
}


private void setButtonsEnabledState() {
    if (mRequestingLocationUpdates) {
        mStartUpdatesButton.setEnabled(false);
        //mStopUpdatesButton.setEnabled(true);
    } else {
        mStartUpdatesButton.setEnabled(true);
        //mStopUpdatesButton.setEnabled(false);
    }
}

private void updateLocationUI() {
    if (mCurrentLocation != null) {
        mLatitudeTextView.setText(String.format(Locale.ENGLISH, "%s: %f", mLatitudeLabel,
                mCurrentLocation.getLatitude()));
        mLongitudeTextView.setText(String.format(Locale.ENGLISH, "%s: %f", mLongitudeLabel,
                mCurrentLocation.getLongitude()));
        mLastUpdateTimeTextView.setText(String.format(Locale.ENGLISH, "%s: %s",
                mLastUpdateTimeLabel, mLastUpdateTime));
        Toast.makeText(MainActivity.this, "latitude="+mCurrentLocation.getLatitude()
                +" longitude="+mCurrentLocation.getLongitude()+
                " last update="+mLastUpdateTime, LENGTH_SHORT).show();

        lat_long_time=mCurrentLocation.getLatitude()+" "+mCurrentLocation.getLongitude();

        Map<String, String> source = readFromSdMap("GettingLocation/sources.dat");

        source.put(mLastUpdateTime, lat_long_time);
        saveToSDMap(source, "GettingLocation/sources.dat");



       Toast.makeText(MainActivity.this,lat_long_time,Toast.LENGTH_SHORT).show();
    }
}


@Override
public void onResume() {
    super.onResume();

    if (mRequestingLocationUpdates && checkPermissions()) {
        startLocationUpdates();
    } else if (!checkPermissions()) {
        requestPermissions();
    }

    updateUI();
}

@Override
protected void onPause() {
    super.onPause();

        }

@Override
public void onStop(){
    super.onStop();
}

public void onSaveInstanceState(Bundle savedInstanceState) {
    savedInstanceState.putBoolean(KEY_REQUESTING_LOCATION_UPDATES, mRequestingLocationUpdates);
    savedInstanceState.putParcelable(KEY_LOCATION, mCurrentLocation);
    savedInstanceState.putString(KEY_LAST_UPDATED_TIME_STRING, mLastUpdateTime);
    super.onSaveInstanceState(savedInstanceState);
}


private void showSnackbar(final int mainTextStringId, final int actionStringId,
                          View.OnClickListener listener) {
    Snackbar.make(
            findViewById(android.R.id.content),
            getString(mainTextStringId),
            Snackbar.LENGTH_INDEFINITE)
            .setAction(getString(actionStringId), listener).show();
}


private boolean checkPermissions() {
    int permissionState = ActivityCompat.checkSelfPermission(this,
            Manifest.permission.ACCESS_FINE_LOCATION);
    return permissionState == PackageManager.PERMISSION_GRANTED;
}

private boolean checkPermissionForStorage() {
    int result = ContextCompat.checkSelfPermission(MainActivity.this, Manifest.permission.WRITE_EXTERNAL_STORAGE);
    if (result == PackageManager.PERMISSION_GRANTED) {
        return true;
    } else {
        return false;
    }
}

private void requestPermissionForStorage() {

    ActivityCompat.requestPermissions(this, new String[]{Manifest.permission.WRITE_EXTERNAL_STORAGE}, PERMISSION_REQUEST_CODE);

}

private void requestPermissions() {
    boolean shouldProvideRationale =
            ActivityCompat.shouldShowRequestPermissionRationale(this,
                    Manifest.permission.ACCESS_FINE_LOCATION);

    if (shouldProvideRationale) {
        Log.i(TAG, "Displaying permission rationale to provide additional context.");
        showSnackbar(R.string.permission_rationale,
                android.R.string.ok, new View.OnClickListener() {
                    @Override
                    public void onClick(View view) {
                        // Request permission
                        ActivityCompat.requestPermissions(MainActivity.this,
                                new String[]{Manifest.permission.ACCESS_FINE_LOCATION},
                                REQUEST_PERMISSIONS_REQUEST_CODE);
                    }
                });
    } else {
        Log.i(TAG, "Requesting permission");
        // Request permission. It's possible this can be auto answered if device policy
        // sets the permission in a given state or the user denied the permission
        // previously and checked "Never ask again".
        ActivityCompat.requestPermissions(MainActivity.this,
                new String[]{Manifest.permission.ACCESS_FINE_LOCATION},
                REQUEST_PERMISSIONS_REQUEST_CODE);
    }
}

public static boolean isExternalStorageWritable() {
    String state = Environment.getExternalStorageState();
    if (Environment.MEDIA_MOUNTED.equals(state)) {
        return true;
    }
    return false;
}

void saveToSDMap(Map<String, String> source, String dest) {

    if (isExternalStorageWritable()) {
        File path = Environment.getExternalStorageDirectory();
        try {
            File dir = new File(valueOf(path) + "/GettingLocation");
            if (!dir.exists()) {
                dir.mkdir();
            }
            FileOutputStream fos =
                    new FileOutputStream(
                            new File(path, dest)
                    );
            ObjectOutputStream os = new ObjectOutputStream(fos);
            os.writeObject(source);
            os.close();

        } catch (Exception ex) {
            ex.printStackTrace();
            System.out.println(ex.getMessage());

        }
    }
}

public static Map<String, String> readFromSdMap(String dest) {

    Map<String, String> source = new HashMap<String, String>();
    if (isExternalStorageWritable()) {
        File path = Environment.getExternalStorageDirectory();

        try {
            File dir = new File(valueOf(path) + "/GettingLocation");
            if (!dir.exists()) {
                dir.mkdir();
            }
            FileInputStream fis =
                    new FileInputStream(
                            new File(path, dest)
                    );
            ObjectInputStream is = new ObjectInputStream(fis);
            source = (Map<String, String>) is.readObject();
            is.close();
            fis.close();

        } catch (IOException | ClassNotFoundException e) {
            e.printStackTrace();
        }

        return source;

    } else {
        return source;
    }
}



@Override
public void onRequestPermissionsResult(int requestCode, @NonNull String[] permissions,
                                       @NonNull int[] grantResults) {
    Log.i(TAG, "onRequestPermissionResult");
    if (requestCode == REQUEST_PERMISSIONS_REQUEST_CODE) {
        if (grantResults.length <= 0) {
            // If user interaction was interrupted, the permission request is cancelled and you
            // receive empty arrays.
            Log.i(TAG, "User interaction was cancelled.");
        } else if (grantResults[0] == PackageManager.PERMISSION_GRANTED) {
            if (mRequestingLocationUpdates) {
                Log.i(TAG, "Permission granted, updates requested, starting location updates");
                startLocationUpdates();
            }
        } else {
            showSnackbar(R.string.permission_denied_explanation,
                    R.string.settings, new View.OnClickListener() {
                        @Override
                        public void onClick(View view) {
                            Intent intent = new Intent();
                            intent.setAction(
                                    Settings.ACTION_APPLICATION_DETAILS_SETTINGS);
                            Uri uri = Uri.fromParts("package",
                                    BuildConfig.APPLICATION_ID, null);
                            intent.setData(uri);
                            intent.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
                            startActivity(intent);
                        }
                    });
        }
    }
}

}


person Rajat    schedule 22.12.2017    source источник
comment
Какой вопрос ? вы просто помещаете сюда весь код (кроме раздела импорта). В чем проблема ?   -  person ADM    schedule 22.12.2017
comment
проверьте это решение github.com/codepath/android_guides/issues/220   -  person sunil kushwah    schedule 22.12.2017
comment
@ADM Я использовал этот код для обновления местоположения, теперь я просто хочу создать сервис   -  person Rajat    schedule 22.12.2017
comment
Где проблема в этом коде.. Пожалуйста, укажите и выделите проблему.. ничего не нашел.. Ваш вопрос беспорядочный   -  person Learning Always    schedule 22.12.2017
comment
@Rajat Прочтите Сервис и следуйте инструкциям.   -  person ADM    schedule 22.12.2017
comment
в коде нет проблем. я просто хочу создать из него сервисную активность.   -  person Rajat    schedule 22.12.2017
comment
@Rajat ты проверил мой ответ?   -  person AbhayBohra    schedule 22.12.2017


Ответы (1)


Вы можете использовать службу плавного определения местоположения, чтобы определить местоположение в фоновом режиме. посмотрите мой ответ здесь https://stackoverflow.com/a/43155046/3789993. Для получения подробной информации перейдите по этой ссылке http://www.vogella.com/tutorials/AndroidLocationAPI/article.html

и не забудьте добавить разрешение на выполнение

person AbhayBohra    schedule 22.12.2017