简体   繁体   中英

How do i make an image move based on location input?

Trying to make an image represent the person's location, but not sure how to pass the variables x and y into the onDraw...

I have it retrieving my location then drawing the symbol and it worked previously when i had just numbers inside the

package com.corey.navigationtest;

import android.app.Activity;
import android.content.Context;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.graphics.Canvas;
import android.graphics.Color;
import android.location.Criteria;
import android.location.Location;
import android.location.LocationListener;
import android.location.LocationManager;
import android.os.Bundle;
import android.telephony.SmsManager;
import android.util.DisplayMetrics;
import android.util.Log;
import android.view.SurfaceHolder;
import android.view.SurfaceView;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.Button;
import android.widget.EditText;
import android.widget.LinearLayout;
import android.widget.FrameLayout.LayoutParams;
import android.widget.Toast;

public class MainActivity extends Activity {

private static final long MINIMUM_DISTANCE_CHANGE_FOR_UPDATES = 5; // in Meters
private static final long MINIMUM_TIME_BETWEEN_UPDATES = 1000; // in Milliseconds

protected LocationManager locationManager;
protected Button retrieveLocationButton;
protected Button buttonSend;

Canvas canvas; //Your canvas to draw on
LinearLayout myLayout; //The layout that holds the surfaceview
SurfaceView surface;
SurfaceHolder surfaceHolder;

public double oldlat = 0;
public double oldlong = 0;
public double newlat;
public double newlong;
public int count = 0;

DisplayMetrics metrics;
int width;
int height;

@Override
public void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.activity_main);
    retrieveLocationButton = (Button) findViewById(R.id.retrieve_location_button);
    locationManager = (LocationManager) getSystemService(Context.LOCATION_SERVICE);

    Criteria criteria = new Criteria();
    criteria.setAccuracy(Criteria.ACCURACY_FINE);
    criteria.setAltitudeRequired(false);
    criteria.setBearingRequired(false);
    criteria.setCostAllowed(true);
    criteria.setPowerRequirement(Criteria.POWER_LOW);

    String provider = locationManager.getBestProvider(criteria, true);

    locationManager.requestLocationUpdates(
            provider,
            MINIMUM_TIME_BETWEEN_UPDATES,
            MINIMUM_DISTANCE_CHANGE_FOR_UPDATES,
            new MyLocationListener()
    );
    buttonSend = (Button) findViewById(R.id.buttonSend);
    retrieveLocationButton.setOnClickListener(onClickListener);
    buttonSend.setOnClickListener(onClickListener);   
    myLayout = (LinearLayout) findViewById(R.id.myLayout);

    LinearLayout.LayoutParams params_surfaceCanvas = new LinearLayout.LayoutParams(LayoutParams.MATCH_PARENT, LayoutParams.MATCH_PARENT);

    surface = new SurfaceView(this);
    surface.setLayoutParams(params_surfaceCanvas);

          //Assign a surfaceholder to the surface
    surfaceHolder = surface.getHolder();

    myLayout.addView(surface);
    canvas = new Canvas();

    metrics = this.getResources().getDisplayMetrics();
    width = metrics.widthPixels;
    height = metrics.heightPixels;


}   

private OnClickListener onClickListener = new OnClickListener () {
    @Override
    public void onClick(final View v) {
        switch(v.getId()) {
            case R.id.buttonSend:
                Location location = locationManager.getLastKnownLocation(LocationManager.PASSIVE_PROVIDER);
                String phoneNo = "8473027766";
                 String sms = String.format(
                            "Current Location \n Longitude: %1$s \n Latitude: %2$s",
                            location.getLongitude(), location.getLatitude()
                 );
                 try {
                    SmsManager smsManager = SmsManager.getDefault();
                    smsManager.sendTextMessage(phoneNo, null, sms, null, null);
                    Toast.makeText(getApplicationContext(), "SMS Sent!",
                                Toast.LENGTH_SHORT).show();
                 } catch (Exception e) {
                    Toast.makeText(getApplicationContext(),
                        "SMS failed, please try again later!",
                        Toast.LENGTH_SHORT).show();
                    e.printStackTrace();
                 }
            break;
            case R.id.retrieve_location_button:             
                    showCurrentLocation();              
            break;
        }

    }
};

protected void showCurrentLocation() {
    Location location = locationManager.getLastKnownLocation(LocationManager.PASSIVE_PROVIDER);
    if (location != null) {

         String message = String.format(
                "Current Location \n Longitude: %1$s \n Latitude: %2$s",
                location.getLongitude(), location.getLatitude()
         );
         Toast.makeText(MainActivity.this, message,
                Toast.LENGTH_SHORT).show();
    }
}  
private class MyLocationListener implements LocationListener {
    public void onLocationChanged(Location location) {
        newlat = location.getLatitude();
        newlong = location.getLatitude();
        String message1 = String.format(
                "New Location \n Longitude: %1$s \n Latitude: %2$s",
                location.getLongitude(), location.getLatitude()
         );
         Toast.makeText(MainActivity.this, message1,
                Toast.LENGTH_SHORT).show();

These are the variables I want to make the coordinates of the image:

        double x;
        double y;
        x = ((newlong - (-81.366553))/.003803)*width;
        y = ((newlat - 41.273816)/.001709)*height;

And heres the rest of the code

        if ((newlat < 41.274871 & newlong > -81.3659) & (oldlong < -81.3659 || oldlat > 41.274871)) {
            String phoneNo = "8473027766";
            count++;
            String sms = String.format(
                    "You are behind enemy lines \n Longitude: %1$s \n Latitude: %2$s \n Count: %3$s",
                    location.getLongitude(), location.getLatitude(), count
            );
            try {
                SmsManager smsManager = SmsManager.getDefault();
                smsManager.sendTextMessage(phoneNo, null, sms, null, null);
                Toast.makeText(getApplicationContext(), "SMS Sent!",
                Toast.LENGTH_SHORT).show();
            } catch (Exception e) {
                Toast.makeText(getApplicationContext(),
                "SMS failed, please try again later!",
                Toast.LENGTH_SHORT).show();
                e.printStackTrace();
            }

        }
        onDraw();
        oldlat = newlat;
        oldlong = newlong;    
    }
    public void onStatusChanged(String s, int i, Bundle b) {
        Toast.makeText(MainActivity.this, "Provider status changed",
                Toast.LENGTH_SHORT).show();
    }
    public void onProviderDisabled(String s) {
        Toast.makeText(MainActivity.this,
                "Provider disabled by the user. GPS turned off",
                Toast.LENGTH_SHORT).show();
    }
    public void onProviderEnabled(String s) {
        Toast.makeText(MainActivity.this,
                "Provider enabled by the user. GPS turned on",
                Toast.LENGTH_SHORT).show();
    }
}

public void onDraw() {
    //Starts a thread
    new Thread(new Runnable() {
        public void run() {
            while(true) {
                //Loops until surfaceHolder is valid to use
                if (surfaceHolder.getSurface().isValid()) {
                    Log.i("Drawing","Drawing"); 
                    //Always lock the canvas if you want to draw in surfaceview
                    canvas = surfaceHolder.lockCanvas();

                    Bitmap image2 = BitmapFactory.decodeResource(getResources(), R.drawable.vertical);
                    Bitmap image1 = BitmapFactory.decodeResource(getResources(), R.drawable.ic_launcher);
                    canvas.drawColor(Color.WHITE); //The background color of the canvas
                    canvas.drawBitmap(image2,0,0, null);                        
                    canvas.drawBitmap(image1, x, y, null);

                    //Don't forget to unlock it after you draw in the surfaceview
                    surfaceHolder.unlockCanvasAndPost(canvas);

                    //breaks the while and end the thread.
                    break;
                }   
            }   
        }
    }).start();
}

You should use an ImageView for each of your images. This would make everything easy, since you would simply call setX(...) and setY(...) , and your app will automatically redraw your image in the right location.

It would also greatly reduce the memory and time needed for your onDraw() method to perform - since as it is currently creating new bitmaps every time (and not destroying the old ones), your app will not last too many clicks.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM