在android中保存当前位置

时间:2018-08-02 13:12:51

标签: java android firebase save location

我遇到一个问题,即每10秒更新一次我的位置。我也想在Firebase上存储我的起始位置....我无法理解如何存储起始点,因为Firebase正在更新...这是我的代码

 i am having an issue that i am updating my location after every 10 sec. i want to store my starting position as well on firebase .... i cant understand how to store the starting point because the firebase is updating ... here is my code 

我遇到一个问题,即每10秒更新一次我的位置。我也想在Firebase上存储我的起始位置....我无法理解如何存储起始点,因为Firebase正在更新...这是我的代码

import android.content.pm.PackageManager;
import android.os.Bundle;
import android.app.Activity;
import android.support.annotation.NonNull;
import android.support.v4.app.ActivityCompat;
import android.content.Context;
import android.location.Criteria;
import android.location.Location;
import android.location.LocationListener;
import android.location.LocationManager;
import android.view.View;
import android.widget.Button;
import android.widget.TextView;
import android.widget.Toast;

import com.google.android.gms.tasks.OnCompleteListener;
import com.google.android.gms.tasks.Task;
import com.google.firebase.auth.FirebaseAuth;
import com.google.firebase.auth.FirebaseUser;
import com.google.firebase.database.DatabaseReference;
import com.google.firebase.database.FirebaseDatabase;
import com.google.firebase.iid.FirebaseInstanceId;



import java.util.Collection;
import java.util.HashMap;
import java.util.List;
import java.util.concurrent.Callable;
import java.util.concurrent.ExecutionException;
import java.util.concurrent.Executors;
import java.util.concurrent.Future;
import java.util.concurrent.ScheduledExecutorService;
import java.util.concurrent.ScheduledFuture;
import java.util.concurrent.TimeUnit;
import java.util.concurrent.TimeoutException;


public class Location_activity extends Activity implements LocationListener  , ScheduledExecutorService{
    private TextView latituteField, longitudeField;
    private LocationManager lm;
    private String provider;
    private Button startbtn , cancelbtn;
    DatabaseReference mDatabaseref;
    FirebaseUser current_user;


    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_location_activity);


        latituteField = (TextView) findViewById(R.id.TextView02);
        longitudeField = (TextView) findViewById(R.id.TextView04);
        startbtn = (Button) findViewById(R.id.btn_start);
        cancelbtn = (Button) findViewById(R.id.btn_cancel);

        startbtn.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {

                final ScheduledExecutorService scheduleTaskExecutor = Executors.newScheduledThreadPool(5);

                scheduleTaskExecutor.scheduleAtFixedRate(new Runnable() {
                    public void run() {
                        lm = (LocationManager) getSystemService(Context.LOCATION_SERVICE);
                        Location myLocation = null;
                        if (lm != null) {
                            if (ActivityCompat.checkSelfPermission(Location_activity.this,
                                    android.Manifest.permission.ACCESS_FINE_LOCATION)
                                    != PackageManager.PERMISSION_GRANTED && ActivityCompat.checkSelfPermission(Location_activity.this,
                                    android.Manifest.permission.ACCESS_COARSE_LOCATION)
                                    != PackageManager.PERMISSION_GRANTED) {

                                return;
                            }

                                myLocation = lm.getLastKnownLocation(LocationManager.GPS_PROVIDER);




                            if (myLocation == null) {
                                Criteria criteria = new Criteria();
                                criteria.setAccuracy(Criteria.ACCURACY_COARSE);
                                String provider = lm.getBestProvider(criteria, true);
                                myLocation = lm.getLastKnownLocation(provider);
                            }

                            if (myLocation == null) {
                                myLocation = lm.getLastKnownLocation(LocationManager.NETWORK_PROVIDER);
                            }
                            if (myLocation != null){
                                System.out.println("Provider " + provider + " has been selected.");
                                onLocationChanged(myLocation);
                            }
                        }

                    }
                }, 1, 10, TimeUnit.SECONDS);

                cancelbtn.setOnClickListener(new View.OnClickListener() {
                    @Override
                    public void onClick(View v) {

                      scheduleTaskExecutor.shutdown();
                    }
                });
            }
        });

    }



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

    }


    @Override
    protected void onPause() {
        super.onPause();
        lm.removeUpdates(this);
    }

    @Override
        public void onLocationChanged(Location location) {

            double lat = (double) (location.getLatitude());
            double lng = (double) (location.getLongitude());



            current_user = FirebaseAuth.getInstance().getCurrentUser();
            String uid = current_user.getUid();
            mDatabaseref = FirebaseDatabase.getInstance().getReference().child("location").child(uid);
            String device_token = FirebaseInstanceId.getInstance().getToken();

            HashMap<String, String> userMap = new HashMap<>();
            userMap.put("latitude", String.valueOf(lat));
            userMap.put("longitude" , String.valueOf(lng));

            userMap.put("device_token", device_token);
            mDatabaseref.setValue(userMap).addOnCompleteListener(new OnCompleteListener<Void>() {
                @Override
                public void onComplete(@NonNull Task<Void> task) {
                    Toast.makeText(getApplicationContext() , "Location updated" , Toast.LENGTH_SHORT ).show();
                }
            });


    }

    @Override
    public void onStatusChanged(String provider, int status, Bundle extras) {
        // TODO Auto-generated method stub




    }

    @Override
    public void onProviderEnabled(String provider) {
        Toast.makeText(this, "Enabled new provider " + provider,
                Toast.LENGTH_SHORT).show();

    }

    @Override
    public void onProviderDisabled(String provider) {
        Toast.makeText(this, "Disabled provider " + provider,
                Toast.LENGTH_SHORT).show();
    }

    @NonNull
    @Override
    public ScheduledFuture<?> schedule(@NonNull Runnable command, long delay, @NonNull TimeUnit unit) {
        return null;
    }

    @NonNull
    @Override
    public <V> ScheduledFuture<V> schedule(@NonNull Callable<V> callable, long delay, @NonNull TimeUnit unit) {
        return null;
    }

    @NonNull
    @Override
    public ScheduledFuture<?> scheduleAtFixedRate(@NonNull Runnable command, long initialDelay, long period, @NonNull TimeUnit unit) {
        return null;
    }

    @NonNull
    @Override
    public ScheduledFuture<?> scheduleWithFixedDelay(@NonNull Runnable command, long initialDelay, long delay, @NonNull TimeUnit unit) {
        return null;
    }

    @Override
    public void shutdown() {

    }

    @NonNull
    @Override
    public List<Runnable> shutdownNow() {
        return null;
    }

    @Override
    public boolean isShutdown() {
        return false;
    }

    @Override
    public boolean isTerminated() {
        return false;
    }

    @Override
    public boolean awaitTermination(long timeout, @NonNull TimeUnit unit) throws InterruptedException {
        return false;
    }

    @NonNull
    @Override
    public <T> Future<T> submit(@NonNull Callable<T> task) {
        return null;
    }

    @NonNull
    @Override
    public <T> Future<T> submit(@NonNull Runnable task, T result) {
        return null;
    }

    @NonNull
    @Override
    public Future<?> submit(@NonNull Runnable task) {
        return null;
    }

    @NonNull
    @Override
    public <T> List<Future<T>> invokeAll(@NonNull Collection<? extends Callable<T>> tasks) throws InterruptedException {
        return null;
    }

    @NonNull
    @Override
    public <T> List<Future<T>> invokeAll(@NonNull Collection<? extends Callable<T>> tasks, long timeout, @NonNull TimeUnit unit) throws InterruptedException {
        return null;
    }

    @NonNull
    @Override
    public <T> T invokeAny(@NonNull Collection<? extends Callable<T>> tasks) throws InterruptedException, ExecutionException {
        return null;
    }

    @Override
    public <T> T invokeAny(@NonNull Collection<? extends Callable<T>> tasks, long timeout, @NonNull TimeUnit unit) throws InterruptedException, ExecutionException, TimeoutException {
        return null;
    }

    @Override
    public void execute(@NonNull Runnable command) {

    }
}

2 个答案:

答案 0 :(得分:0)

int i = 0;

mDatabaseref = FirebaseDatabase.getInstance().getReference().child("location").child(uid);
String device_token = FirebaseInstanceId.getInstance().getToken();

HashMap<String, String> userMap = new HashMap<>();
userMap.put("Startlatitude", String.valueOf(lat));
userMap.put("Startlongitude" , String.valueOf(lng));
userMap.put("Currentlatitude" , String.valueOf(lat));
userMap.put("Currentlongitude" , String.valueOf(lng));

if(i==0) {

    userMap.put("device_token", device_token);
    mDatabaseref.setValue(userMap).addOnCompleteListener(new OnCompleteListener<Void>() {
        @Override
        public void onComplete(@NonNull Task<Void> task) {
            Toast.makeText(getApplicationContext() , "Location updated" , Toast.LENGTH_SHORT ).show();
            i++;
        }
    });
}
else {
    userMap.child("Currentlatitude").setValue(String.valueOf(lat));
    userMap.child("Currentlongitude").setValue(String.valueOf(lng));

    // Attach addOnCompleteListener
    // You  can also use HashMap to update both together.
}

因此,只有第一次纬度和经度会保存在数据库中,因为最初i = 0。当开始lat时,将保存多长时间,i会增加。因此,从下一次开始,其他条件永远都是正确的。我希望这能完成您的工作。

答案 1 :(得分:0)

之所以发生这种情况,是因为您在位置上添加了一个侦听器,并且每次位置更改时,都会得到一个新的services.AddIdentity<IdentityUser, IdentityRole>()对象,该对象包含新坐标,并且每次将这些新坐标写入数据库中。如果只想将起点写入数据库,则应声明一个名为.AddDefaultTokenProviders()的布尔值,默认值为false。

Location

然后只需编写如下条件:

isStartingPointWritten

通过这种方式,您可以将写入操作限制为仅发生一次。