有什么方法可以将位置详细信息从android应用保存到firebase?

时间:2019-09-20 07:41:10

标签: android firebase firebase-realtime-database

我创建了一个android应用程序,该应用程序为我提供了当前位置的详细信息,即单击按钮后即可获得纬度和经度。该应用程序充当服务。我想将纬度和经度详细信息存储到实时数据库(firebase)中。

我在build.gradle中添加了firebase依赖项并进行了连接。已在控制台中创建了一个数据库,但未存储数据。

 package com.google.android.gms.location.sample.locationupdates;

 import android.Manifest;
 import android.annotation.TargetApi;
import android.app.Activity;
import android.content.Intent;
import android.content.IntentSender;
import android.content.pm.PackageManager;
import android.location.Location;
import android.net.Uri;
import android.os.Build;
import android.os.Bundle;
import android.os.Looper;
import android.provider.Settings;
import androidx.annotation.NonNull;
import com.google.android.material.snackbar.Snackbar;
import androidx.core.app.ActivityCompat;
import androidx.appcompat.app.AppCompatActivity;
import androidx.appcompat.widget.Toolbar;
import android.util.Log;
import android.view.View;
import android.widget.Button;
import android.widget.TextView;
import android.widget.Toast;
import com.google.android.gms.common.api.ApiException;
import com.google.android.gms.common.api.ResolvableApiException;
import com.google.android.gms.location.FusedLocationProviderClient;
import com.google.android.gms.location.LocationCallback;
import com.google.android.gms.location.LocationRequest;
import com.google.android.gms.location.LocationResult;
import com.google.android.gms.location.LocationServices;
import com.google.android.gms.location.LocationSettingsRequest;
import com.google.android.gms.location.LocationSettingsResponse;
import com.google.android.gms.location.LocationSettingsStatusCodes;
import com.google.android.gms.location.SettingsClient;
import com.google.android.gms.tasks.OnCompleteListener;
import com.google.android.gms.tasks.OnFailureListener;
import com.google.android.gms.tasks.OnSuccessListener;
import com.google.android.gms.tasks.Task;
import java.text.DateFormat;
import java.util.Date;
import java.util.Locale;

public class MainActivity extends AppCompatActivity {

private static final String TAG = MainActivity.class.getSimpleName();

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 = 10000;

private static final long FASTEST_UPDATE_INTERVAL_IN_MILLISECONDS =
        UPDATE_INTERVAL_IN_MILLISECONDS / 2;

// Keys for storing activity state in the Bundle.
 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;

// UI Widgets.
  private Button mStartUpdatesButton;
  private Button mStopUpdatesButton;
  private TextView mLastUpdateTimeTextView;
  private TextView mLatitudeTextView;
  private TextView mLongitudeTextView;

// Labels.
  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);

    // Locate the UI widgets.
    mStartUpdatesButton = (Button) findViewById(R.id.start_updates_button);
    mStopUpdatesButton = (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);

    // Set labels.
    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 = "";

    // Update values using data stored in the Bundle.
    updateValuesFromBundle(savedInstanceState);

    mFusedLocationClient = LocationServices.getFusedLocationProviderClient(this);
    mSettingsClient = LocationServices.getSettingsClient(this);

    // Kick off the process of building the LocationCallback, LocationRequest, and
    // LocationSettingsRequest objects.
    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 = savedInstanceState.getParcelable(KEY_LOCATION);
        }


        if (savedInstanceState.keySet().contains(KEY_LAST_UPDATED_TIME_STRING)) {
            mLastUpdateTime = savedInstanceState.getString(KEY_LAST_UPDATED_TIME_STRING);
        }
        updateUI();
    }
}


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) {
        .
        case REQUEST_CHECK_SETTINGS:
            switch (resultCode) {
                case Activity.RESULT_OK:
                    Log.i(TAG, "User agreed to make required location settings changes.");

                    break;
                case Activity.RESULT_CANCELED:
                    Log.i(TAG, "User chose not to make required location settings changes.");
                    mRequestingLocationUpdates = false;
                    updateUI();
                    break;
            }
            break;
    }
}


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


public void stopUpdatesButtonHandler(View view) {

    stopLocationUpdates();
}


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() {
                @TargetApi(Build.VERSION_CODES.DONUT)
                @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 {

                                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));
    }
}


  private void stopLocationUpdates() {
    if (!mRequestingLocationUpdates) {
        Log.d(TAG, "stopLocationUpdates: updates never requested, no-op.");
        return;
    }

    .
    mFusedLocationClient.removeLocationUpdates(mLocationCallback)
            .addOnCompleteListener(this, new OnCompleteListener<Void>() {
                @Override
                public void onComplete(@NonNull Task<Void> task) {
                    mRequestingLocationUpdates = false;
                    setButtonsEnabledState();
                }
            });
}

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

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

    updateUI();
}

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

    // Remove location updates to save battery.
    stopLocationUpdates();
}


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 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) {


 ActivityCompat.requestPermissions(MainActivity.this,
                                new String[]{Manifest.permission.ACCESS_FINE_LOCATION},
                                REQUEST_PERMISSIONS_REQUEST_CODE);
                    }
                });
    } else {
        Log.i(TAG, "Requesting permission");
        ActivityCompat.requestPermissions(MainActivity.this,
                new String[]{Manifest.permission.ACCESS_FINE_LOCATION},
                REQUEST_PERMISSIONS_REQUEST_CODE);
    }
}

   @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) {

            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) {
                            // Build intent that displays the App settings screen.
                            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);
                        }
                    });
        }
    }
  }
}

build.gradle(app)

  apply plugin: 'com.android.application'

  android {
    compileSdkVersion 28

    defaultConfig {
    applicationId "com.google.android.gms.location.sample.locationupdates"
    minSdkVersion 16
    //noinspection OldTargetApi
    targetSdkVersion 28
    versionCode 1
    versionName "1.0"
}
buildTypes {
    release {
        minifyEnabled false
        proguardFiles getDefaultProguardFile('proguard-android.txt'), 'proguard-rules.pro'
    }
  }
}
  dependencies {
   implementation fileTree(dir: 'libs', include: ['*.jar'])
   implementation 'com.google.firebase:firebase-database:11.0.4'
   androidTestImplementation('androidx.test.espresso:espresso-core:3.1.1', {
    exclude group: 'com.android.support', module: 'support-annotations'
})
   implementation 'androidx.appcompat:appcompat:1.1.0'
testImplementation 'junit:junit:4.12'

   implementation 'com.google.android.material:material:1.0.0'
//noinspection GradleCompatible
   implementation 'com.google.android.gms:play-services-location:11.0.4'
}
   apply plugin: 'com.google.gms.google-services'

main_activity.xml

   <?xml version="1.0" encoding="utf-8"?>
   <androidx.coordinatorlayout.widget.CoordinatorLayout 
   xmlns:android="http://schemas.android.com/apk/res/android"
   xmlns:app="http://schemas.android.com/apk/res-auto"
   xmlns:tools="http://schemas.android.com/tools"
   android:layout_width="match_parent"
   android:layout_height="match_parent"
   android:fitsSystemWindows="true"
   tools:context=".MainActivity">

    <com.google.android.material.appbar.AppBarLayout
    android:layout_width="match_parent"
    android:layout_height="wrap_content"
    android:theme="@style/AppTheme.AppBarOverlay">

    <androidx.appcompat.widget.Toolbar
        android:id="@+id/toolbar"
        android:layout_width="match_parent"
        android:layout_height="?attr/actionBarSize"
        android:background="?attr/colorPrimary"
        app:popupTheme="@style/AppTheme.PopupOverlay" />

</com.google.android.material.appbar.AppBarLayout>


<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
    android:layout_width="match_parent"
    android:layout_height="wrap_content"
    android:orientation="vertical"
    android:paddingBottom="@dimen/activity_vertical_margin"
    android:paddingLeft="@dimen/activity_horizontal_margin"
    android:paddingRight="@dimen/activity_horizontal_margin"
    android:paddingTop="@dimen/activity_vertical_margin"
    app:layout_behavior="@string/appbar_scrolling_view_behavior">

    <LinearLayout
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:baselineAligned="false"
        android:orientation="horizontal">

        <Button
            android:id="@+id/start_updates_button"
            android:layout_width="0dp"
            android:layout_height="wrap_content"
            android:layout_marginEnd="10dp"
            android:layout_marginRight="10dp"
            android:layout_weight="1"
            android:gravity="center"
            android:onClick="startUpdatesButtonHandler"
            android:text="@string/start_updates" />

        <Button
            android:id="@+id/stop_updates_button"
            android:layout_width="0dp"
            android:layout_height="wrap_content"
            android:layout_marginLeft="@dimen/small_margin"
            android:layout_marginStart="@dimen/small_margin"
            android:layout_weight="1"
            android:enabled="false"
            android:gravity="center"
            android:onClick="stopUpdatesButtonHandler"
            android:text="@string/stop_updates" />
    </LinearLayout>

    <TextView
        android:id="@+id/latitude_text"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:layout_marginLeft="@dimen/small_margin"
        android:layout_marginStart="@dimen/small_margin"
        android:textSize="@dimen/default_text_size" />

    <TextView
        android:id="@+id/longitude_text"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:layout_marginLeft="@dimen/small_margin"
        android:layout_marginStart="@dimen/small_margin"
        android:textSize="@dimen/default_text_size" />

    <TextView
        android:id="@+id/last_update_time_text"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:layout_marginLeft="@dimen/small_margin"
        android:layout_marginStart="@dimen/small_margin"
        android:textSize="@dimen/default_text_size" />

    <TextView
        android:id="@+id/location_inadequate_warning"
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:text="@string/location_settings_inadequate_warning"
        android:visibility="invisible" />
</LinearLayout>
</androidx.coordinatorlayout.widget.CoordinatorLayout>

0 个答案:

没有答案