calculating accumulated distance using GPS(cannot call run method)

梦想与她 提交于 2019-12-11 18:55:27

问题


I am still working on a project i have asked a question on here. it is to calculate the accumulated distance a person has traveled or run after a time.

I do not know whether i should start a new question or continuing from the first one i asked first since i progress a lot since then and my codes are a lot of different with different errors. i tried to use the debugger in eclipse but it did not work and i don't understand it.

The distance accumulating part is what was troubling me and i use the Runnable run method. but my application did not reach the Run method when it crashed. when i press start move, it display "Second value succeeded"and "Thread started", this is just to show me that it reach that point. but it did not display "Run is running" so it never reach the run method.

When i test the codes, i enter location data using a emulator. does it have any different effect when it is real time? i always thought it is impossible to use real time when developing codes in the laptop. if there is, could someone tell me? from the research, all people I've seen use emulator. i a new user and so do not understand how to use the debugger, i tried it but it did not show anything.

when i press get distance, return 0, and when i press again it the app say unfortunately app has stopped. maybe it is because it did not reach Run? when my thread was t1=new Thread(new MainActivity());, it crashed when i press start moving. right now it is t1=new Thread() but the distance is 0 and crashed. both scenario did not reach the Run method.

All distance turn out 0, so i thought it is because my lat2 value was null when it first calculated in the Run method, before becoming lat 1 value.. so i assigned it a value first when i start moving.
also, how do i stop the timer and make dist 0 when i first press start again? the time won't stop even if i pressed stop. basically, my problem is, how do it make the Run method run when thread is started when stopping, stop the timer and thread.

There was a time before when distance did not crash, but not accumulated(not the codes shown) i tested to stop the timer but the time still goes on. also Thread.Stop seem dangerous as many places suggest. do i just make the dis=0? i use bool to stop the distance from accumulating or to start again. so do i need to stop the thread?

EDIT: this is the updated codes.

public class MainActivity extends Activity implements Runnable{

 private static final long MINIMUM_DISTANCE_CHANGE_FOR_UPDATES = 1; // in Meters
    private static final long MINIMUM_TIME_BETWEEN_UPDATES = 30000;

    protected LocationManager locationManager;
    static double n=0;
    Long s1,r1;
    double lat1,lon1,lat3,lon3,lat2,lon2;
    double dis=0.0;
    MyCount counter;
    Thread t1;
    EditText e1;
    boolean bool=true;
    int count=0;

Button btnCurrentPosition,btnStartMove,btnPause,btnResume,btnStop,btnGetDistance;
/** Called when the activity is first created. */

@Override
protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.activity_main);     
    btnCurrentPosition=(Button)findViewById(R.id.CurrentPosition);//current position
    btnStartMove=(Button)findViewById(R.id.StartMove);//start moving.. calculates distance on clicking this
    btnPause=(Button)findViewById(R.id.Pause);//pause
    btnResume=(Button)findViewById(R.id.Resume);//resume
    btnStop=(Button)findViewById(R.id.Stopping);
    btnGetDistance=(Button)findViewById(R.id.GetDistance);//get distance
    e1=(EditText)findViewById(R.id.Text1);
    locationManager = (LocationManager) getSystemService(Context.LOCATION_SERVICE);
    locationManager.requestLocationUpdates(
            LocationManager.GPS_PROVIDER, 
            MINIMUM_TIME_BETWEEN_UPDATES, 
            MINIMUM_DISTANCE_CHANGE_FOR_UPDATES,
            new MyLocationListener()
    );
    btnCurrentPosition.setOnClickListener(new OnClickListener() 
    {
        @Override
        public void onClick(View v) {
            showCurrentLocation();
        }
    });  
    btnStartMove.setOnClickListener(new OnClickListener() 
    {
        @Override
        public void onClick(View v) {
            start(v);
        }
    });
    btnPause.setOnClickListener(new OnClickListener() 
    {
        @Override
        public void onClick(View v) {
            // TODO Auto-generated method stub
            start(v); 
        }
    });
    btnResume.setOnClickListener(new OnClickListener() 
    {
        @Override
        public void onClick(View v) {
            // TODO Auto-generated method stub
            start(v); 
        }
    });
    btnStop.setOnClickListener(new OnClickListener() 
    {
        @Override
        public void onClick(View v) {
            // TODO Auto-generated method stub
            start(v); 
        }
    });
    btnGetDistance.setOnClickListener(new OnClickListener() 
    {
        @Override
        public void onClick(View v) {
            // TODO Auto-generated method stub
            start(v);
        }
    });

}

protected void showCurrentLocation() 
{
    Location location = locationManager.getLastKnownLocation(LocationManager.GPS_PROVIDER);

    if (location != null) {
        String message = String.format(
                "Current Location \n Longitude: %1$s \n Latitude: %2$s",
                location.getLongitude(), location.getLatitude()
        );
        lat1=location.getLatitude();
        lon1=location.getLongitude();
        Toast.makeText(MainActivity.this, message,
                Toast.LENGTH_LONG).show();
        Toast.makeText(MainActivity.this,"distance in metres:"+String.valueOf(dis),Toast.LENGTH_LONG).show();
        Toast.makeText(MainActivity.this, "Value of Count:" + String.valueOf(count),
                Toast.LENGTH_LONG).show();
    }
    else{
        Toast.makeText(MainActivity.this, "null location",
                Toast.LENGTH_LONG).show();
    }


}

public void start (View v){

    switch(v.getId()){

    case R.id.StartMove:
        Location location = locationManager.getLastKnownLocation(LocationManager.GPS_PROVIDER);
        lat2=location.getLatitude();
        lon2=location.getLongitude();
        bool=true;
        t1=new Thread(this);
        t1.start();
        //  Thread t = new Thread(new MainActivity()); t.start()
        //new MainActivity()
        counter= new MyCount(30000,1000);
     counter.start();
     break;
    case R.id.Pause:
        counter.cancel();
        bool=false;
        break;
    case R.id.Resume:
        counter= new MyCount(s1,1000);
     counter.start();
     bool=true;
     break;
    case R.id.GetDistance:

        Toast.makeText(MainActivity.this, "reach get distance",
                Toast.LENGTH_LONG).show();
        //run();
        double time=n*30+r1;

        Toast.makeText(MainActivity.this,"distance in metres:"+String.valueOf(dis)+"Velocity in m/sec :"+String.valueOf(dis/time)+"Time :"+String.valueOf(time),Toast.LENGTH_LONG).show();

    case R.id.Stopping:
        counter.cancel();
        counter = null;
        bool = false;

        //r1 = (long) 0;

    }
}

private class MyLocationListener implements LocationListener {

    public void onLocationChanged(Location location) {
        String message = String.format(
                "New Location \n Longitude: %1$s \n Latitude: %2$s",
                location.getLongitude(), location.getLatitude()
        );
        Toast.makeText(MainActivity.this, message, Toast.LENGTH_LONG).show();
    }

    public void onStatusChanged(String s, int i, Bundle b) {
        Toast.makeText(MainActivity.this, "Provider status changed",
                Toast.LENGTH_LONG).show();
    }

    public void onProviderDisabled(String s) {
        Toast.makeText(MainActivity.this,
                "Provider disabled by the user. GPS turned off",
                Toast.LENGTH_LONG).show();
    }

    public void onProviderEnabled(String s) {
        Toast.makeText(MainActivity.this,
                "Provider enabled by the user. GPS turned on",
                Toast.LENGTH_LONG).show();
    }

}

public class MyCount extends CountDownTimer{
    public MyCount(long millisInFuture, long countDownInterval) {
    super(millisInFuture, countDownInterval);
    }
    @Override
    public void onFinish() {
        counter= new MyCount(30000,1000);
     counter.start();
     n=n+1;
    }
    @Override
    public void onTick(long millisUntilFinished) {
        s1=millisUntilFinished;
        r1=(30000-s1)/1000;
        e1.setText(String.valueOf(r1));


    }
}

@Override
public void run() 
{
    count=6;
    Location location = locationManager.getLastKnownLocation(LocationManager.GPS_PROVIDER);
    while(bool==true)
    {
        lat1=location.getLatitude();
        lon1=location.getLongitude();

        if(lat1!=lat2 || lon1!=lon2)
        {
            dis+=getDistance(lat2,lon2,lat1,lon1);
            lat2=lat1;
            lon2=lon1;
            count=7;
        }

    }

}

public double getDistance(double lat1, double lon1, double lat2, double lon2) {
    double latA = Math.toRadians(lat1);
    double lonA = Math.toRadians(lon1);
    double latB = Math.toRadians(lat2);
    double lonB = Math.toRadians(lon2);
    double cosAng = (Math.cos(latA) * Math.cos(latB) * Math.cos(lonB-lonA)) +
                    (Math.sin(latA) * Math.sin(latB));
    double ang = Math.acos(cosAng);
    double dist = ang *6371;
    return dist;
}

EDIT: the above updated codes is i use another method to determine whether it has reach the Run(). i tried to display the distance and count in the getCurrentPosition, not its purpose, just to test the codes. the distance appear,just that the value remains the same. the count value is 7, so it prove that it reach my Run method. i then click GetDistance, distance value result remains the same even when the location is updated, but when i click it again, it crash. i don't know the problem with my distance button. i click the first time, it display, wherther value is accurate or inaccurate. the second time, it did not even display "reach get distance". the screen hang for 1 second then it crashed. i even create another project with the same codes and run. the result is when i first run it, it crashed before displaying the application. i a new user both in android and here so if i done anything wrong, please tell me. thanks. I'm not sure if my question is too general.

this is the LogCat of the project that crashed when it first run.

01-21 22:13:05.950: D/dalvikvm(911): Not late-enabling CheckJNI (already on)
01-21 22:13:09.240: D/AndroidRuntime(911): Shutting down VM
01-21 22:13:09.250: W/dalvikvm(911): threadid=1: thread exiting with uncaught exception (group=0xb3a2cb90)
01-21 22:13:09.320: E/AndroidRuntime(911): FATAL EXCEPTION: main
01-21 22:13:09.320: E/AndroidRuntime(911): Process: com.example.gpsdistance, PID: 911
01-21 22:13:09.320: E/AndroidRuntime(911): java.lang.RuntimeException: Unable to start activity ComponentInfo{com.example.gpsdistance/com.example.gpsdistance.MainActivity}: java.lang.SecurityException: "gps" location provider requires ACCESS_FINE_LOCATION permission.
01-21 22:13:09.320: E/AndroidRuntime(911):  at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:2176)
01-21 22:13:09.320: E/AndroidRuntime(911):  at android.app.ActivityThread.handleLaunchActivity(ActivityThread.java:2226)
01-21 22:13:09.320: E/AndroidRuntime(911):  at android.app.ActivityThread.access$700(ActivityThread.java:135)
01-21 22:13:09.320: E/AndroidRuntime(911):  at android.app.ActivityThread$H.handleMessage(ActivityThread.java:1397)
01-21 22:13:09.320: E/AndroidRuntime(911):  at android.os.Handler.dispatchMessage(Handler.java:102)
01-21 22:13:09.320: E/AndroidRuntime(911):  at android.os.Looper.loop(Looper.java:137)
01-21 22:13:09.320: E/AndroidRuntime(911):  at android.app.ActivityThread.main(ActivityThread.java:4998)
01-21 22:13:09.320: E/AndroidRuntime(911):  at java.lang.reflect.Method.invokeNative(Native Method)
01-21 22:13:09.320: E/AndroidRuntime(911):  at java.lang.reflect.Method.invoke(Method.java:515)
01-21 22:13:09.320: E/AndroidRuntime(911):  at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:777)
01-21 22:13:09.320: E/AndroidRuntime(911):  at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:593)
01-21 22:13:09.320: E/AndroidRuntime(911):  at dalvik.system.NativeStart.main(Native Method)
01-21 22:13:09.320: E/AndroidRuntime(911): Caused by: java.lang.SecurityException: "gps" location provider requires ACCESS_FINE_LOCATION permission.
01-21 22:13:09.320: E/AndroidRuntime(911):  at android.os.Parcel.readException(Parcel.java:1461)
01-21 22:13:09.320: E/AndroidRuntime(911):  at android.os.Parcel.readException(Parcel.java:1415)
01-21 22:13:09.320: E/AndroidRuntime(911):  at android.location.ILocationManager$Stub$Proxy.requestLocationUpdates(ILocationManager.java:540)
01-21 22:13:09.320: E/AndroidRuntime(911):  at android.location.LocationManager.requestLocationUpdates(LocationManager.java:860)
01-21 22:13:09.320: E/AndroidRuntime(911):  at android.location.LocationManager.requestLocationUpdates(LocationManager.java:454)
01-21 22:13:09.320: E/AndroidRuntime(911):  at com.example.gpsdistance.MainActivity.onCreate(MainActivity.java:53)
01-21 22:13:09.320: E/AndroidRuntime(911):  at android.app.Activity.performCreate(Activity.java:5243)
01-21 22:13:09.320: E/AndroidRuntime(911):  at android.app.Instrumentation.callActivityOnCreate(Instrumentation.java:1087)
01-21 22:13:09.320: E/AndroidRuntime(911):  at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:2140)
01-21 22:13:09.320: E/AndroidRuntime(911):  ... 11 more

回答1:


add permission

  <uses-permission android:name="android.permission.ACCESS_FINE_LOCATION" />

any problem let me inform or done then +1



来源:https://stackoverflow.com/questions/21252939/calculating-accumulated-distance-using-gpscannot-call-run-method

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!