首页
学习
活动
专区
圈层
工具
发布
社区首页 >问答首页 >需要从onLocationChanged获得更新的位置/数据

需要从onLocationChanged获得更新的位置/数据
EN

Stack Overflow用户
提问于 2022-09-20 05:58:02
回答 1查看 25关注 0票数 0

只是一个警告:我真的不为我编写的这段代码感到骄傲,但无论如何我都需要它来工作。别太苛刻地评价我。

嘿,各位,我正在编写一个速度表android应用程序,我遇到了一个基本的问题。我需要使用Android定位服务来计算两个GPS坐标之间的距离(我知道融合定位提供商更优越,但请容忍这一点)。

位置侦听器类位于一个名为CurrentLocationListener.java的Java文件中。到目前为止,我已经能够获得两个坐标,并在上面的java文件中获得更新的坐标和旧的坐标之间的距离,但是我需要一些方法将它传递到MainActivity.java文件,在那里我可以用所述的距离更新UI。这两个java文件的代码如下:

MainActivity.java

代码语言:javascript
复制
package com.example.speedometer;

import androidx.appcompat.app.AppCompatActivity;
import androidx.core.app.ActivityCompat;
import androidx.core.content.ContextCompat;

import android.Manifest;
import android.annotation.SuppressLint;
import android.content.Context;
import android.content.pm.PackageManager;
import android.location.Location;
import android.location.LocationManager;
import android.os.Bundle;
import android.view.View;
import android.widget.TextView;
import android.widget.Toast;
import java.lang.Thread;

public class MainActivity extends AppCompatActivity {

    CurrentLocationListener currentLocationListener;
    LocationManager locationManager;
    TextView textCurrentSpeed, textOdometer, textAvgSpeed;
//    MainActivity mainActivity;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);
//        mainActivity = this;

        currentLocationListener = new CurrentLocationListener();
        textCurrentSpeed = findViewById(R.id.dispCurrentSpeed);
        textOdometer = findViewById(R.id.dispOdometer);
        textAvgSpeed = findViewById(R.id.dispAvgSpeed);

        locationManager = (LocationManager) getSystemService(Context.LOCATION_SERVICE);

        if (ActivityCompat.checkSelfPermission(this, Manifest.permission.ACCESS_FINE_LOCATION) != PackageManager.PERMISSION_GRANTED && ActivityCompat.checkSelfPermission(this, Manifest.permission.ACCESS_COARSE_LOCATION) != PackageManager.PERMISSION_GRANTED)
        {
            Toast.makeText(this, "Location permission not granted. Please grant permission.", Toast.LENGTH_LONG).show();
            alertbox();
        }
        locationManager.requestLocationUpdates(LocationManager.GPS_PROVIDER, 2000, 5, currentLocationListener);
    }

    protected void alertbox()
    {
        if (ContextCompat.checkSelfPermission(this, Manifest.permission.ACCESS_FINE_LOCATION) != PackageManager.PERMISSION_GRANTED && ActivityCompat.checkSelfPermission(this, Manifest.permission.ACCESS_COARSE_LOCATION) != PackageManager.PERMISSION_GRANTED)
        {
            ActivityCompat.requestPermissions(this, new String[]{Manifest.permission.ACCESS_FINE_LOCATION, Manifest.permission.ACCESS_COARSE_LOCATION}, 1);
        }
    }

    public void updateLocation() {
        Location location = null;
        double[] coords = new double[2];

        if (ActivityCompat.checkSelfPermission(this, Manifest.permission.ACCESS_FINE_LOCATION) != PackageManager.PERMISSION_GRANTED && ActivityCompat.checkSelfPermission(this, Manifest.permission.ACCESS_COARSE_LOCATION) != PackageManager.PERMISSION_GRANTED) {
            Toast.makeText(this, "Permission to gps not granted. Grant permissions and try again or restart the application.", Toast.LENGTH_LONG).show();
            alertbox();
        }
        else {
            location = locationManager.getLastKnownLocation(Context.LOCATION_SERVICE);
        }

        locationManager.requestLocationUpdates(LocationManager.GPS_PROVIDER, 5000, 5, currentLocationListener);

        if (location == null)
        {
            location = currentLocationListener.getLocation();
        }
        else {
            Toast.makeText(this, "unknown location", Toast.LENGTH_LONG).show();
        }

    }

    @SuppressLint("SetTextI18n")
    protected void main()
    {
        double oldlat, newlat, oldlong, newlong;
        double[] coords;
        double odometer = 0, timeElapsed = 0, distanceTravelled, currentSpeed, avgSpeed;
        double startTime, endTime;

//        coords = updateLocation();
//        oldlong = coords[0];
//        oldlat = coords[1];



//        while(true)
//        {
//            startTime = System.nanoTime();
//            try
//            {
//                Thread.sleep(10000);
//            } catch (InterruptedException e)
//            {
//                e.printStackTrace();
//            }
//
//            coords = updateLocation();
//
//            newlong = coords[0];
//            newlat = coords[1];
//            System.out.println(newlat + " " + newlong);
//
//            distanceTravelled = earthDistance(oldlat, oldlong, newlat, newlong);
//
//            odometer += distanceTravelled;
//
//            endTime = System.nanoTime();
//
//            timeElapsed += (endTime - startTime);
//            currentSpeed = (distanceTravelled)/((endTime-startTime)/1e9); // m/s to km/hr
//            avgSpeed = (odometer/1000)/(timeElapsed/1e9);
//
////            System.out.println("odo: " + odometer);
////            System.out.println("currspeed: " + currentSpeed);
//            System.out.println("dist: " + distanceTravelled);
//
//            textCurrentSpeed.setText(currentSpeed + " m/s");
//            textOdometer.setText((odometer) + " m");
//            textAvgSpeed.setText(avgSpeed + " km/hr");
//
//            oldlat = newlat;
//            oldlong = newlong;
//        }
    }


    protected double earthDistance(double lat1, double lon1, double lon2, double lat2)
    {

        final double R = 6371e3; // Radius of the earth

        double latDistance = Math.toRadians(lat2 - lat1);
        double lonDistance = Math.toRadians(lon2 - lon1);
        double a = Math.sin(latDistance / 2) * Math.sin(latDistance / 2)
                + Math.cos(Math.toRadians(lat1)) * Math.cos(Math.toRadians(lat2))
                * Math.sin(lonDistance / 2) * Math.sin(lonDistance / 2);
        double c = 2 * Math.atan2(Math.sqrt(a), Math.sqrt(1 - a));

        return R * c;
    }

    public void setTextFields(double distance)
    {
        System.out.println(distance);
    }

    public void buttonStart(View MainActivity)
    {
//        main();
        updateLocation();
    }
}

CurrentLocationListener.java

代码语言:javascript
复制
package com.example.speedometer;

import android.location.Location;
import android.location.LocationListener;
import android.os.Bundle;
import android.os.Message;
import android.widget.TextView;
import android.view.View;
import android.content.Context;

public class CurrentLocationListener implements LocationListener {
    Location myLocation;
    double templat = 404, templong = 404;
    double odometer = 0, totalTime = 0, currentDist, currentSpeed, avgSpeed;
    TextView textCurrentSpeed, textOdometer, textAvgSpeed;
    MainActivity mainActivity;


    public Location getLocation()
    {
        return myLocation;
    }

    @Override
    public void onLocationChanged(Location location)
    {
//        textCurrentSpeed = mainActivity.findViewById(R.id.dispCurrentSpeed);
//        textOdometer = mainActivity.findViewById(R.id.dispOdometer);
//        textAvgSpeed = mainActivity.findViewById(R.id.dispAvgSpeed);
        double startTime, endTime;
        myLocation = location;
        if (templat == 404 && templong == 404)
        {
            templat = location.getLatitude();
            templong = location.getLongitude();
        }
        else
        {
            currentDist = earthDistance(location.getLatitude(), location.getLongitude(), templong, templat);
            templat = location.getLatitude();
            templong = location.getLongitude();
            System.out.println("dist: " + currentDist);
            odometer += currentDist;
            totalTime += 10;
            currentSpeed = currentDist/10;
            avgSpeed = odometer/totalTime;

            mainActivity.setTextFields(odometer);
//            textCurrentSpeed.setText(currentSpeed + " m/s");
        }
//        System.out.println("update");
//        System.out.println(location.getLatitude() + " " + location.getLongitude());
    }

    @Override
    public void onStatusChanged(String provider, int status, Bundle extras) {

    }

    @Override
    public void onProviderEnabled(String provider) {

    }

    @Override
    public void onProviderDisabled(String provider) {

    }

    protected double earthDistance(double lat1, double lon1, double lon2, double lat2)
    {

        final double R = 6371e3; // Radius of the earth

        double latDistance = Math.toRadians(lat2 - lat1);
        double lonDistance = Math.toRadians(lon2 - lon1);
        double a = Math.sin(latDistance / 2) * Math.sin(latDistance / 2)
                + Math.cos(Math.toRadians(lat1)) * Math.cos(Math.toRadians(lat2))
                * Math.sin(lonDistance / 2) * Math.sin(lonDistance / 2);
        double c = 2 * Math.atan2(Math.sqrt(a), Math.sqrt(1 - a));

        return R * c;
    }
}

我的主要目标是用计算值更新TextView字段,比如里程表读数。我知道有很多重复的代码和评论,但老实说,我已经超出了我的深度,迫切需要帮助。如果还需要更多的信息,请告诉我。提前谢谢。

EN

回答 1

Stack Overflow用户

回答已采纳

发布于 2022-09-20 09:14:01

您可以让您的MainActivity实现LocationListener:

代码语言:javascript
复制
public class MainActivity 
extends 
AppCompactActivity implements 
LocationListener {
//Rest of the code

@Override
public void 
onLocationChanged(Location 
location){
//do your stuff       
 }

@Override
public void onStatusChanged(String 
provider, int status, Bundle 
extras) {
//do your stuff
}

@Override
public void 
onProviderEnabled(String provider) 
{
//do your stuff
}

@Override
public void 
onProviderDisabled(String 
provider) {
//do your stuff
}
    }
票数 0
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/73782187

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档