簡體   English   中英

誰能告訴我如何通過Android應用中的消息發送經度和緯度坐標?

[英]Can anyone tell me how do i send longitude and lattitude co-ordinate via message in android app?

大家好,這是我要獲取經度和緯度的代碼,現在我想知道如何調用該類,以及如何通過字符串sms通過url發送協調的代碼,還有一件事我想告訴您此代碼沒有錯誤但是當我在我的應用程序中使用它時,它並不會給我吐司,有人可以幫助我嗎?

這是我的位置信息類:

    public class Location_Getter extends AppCompatActivity implements
        ConnectionCallbacks,
        OnConnectionFailedListener,
        LocationListener {

    //Define a request code to send to Google Play services
    private final static int CONNECTION_FAILURE_RESOLUTION_REQUEST = 9000;
    private GoogleApiClient mGoogleApiClient;
    private LocationRequest mLocationRequest;
    private double currentLatitude;
    private double currentLongitude;


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


    mGoogleApiClient = new GoogleApiClient.Builder(this)
            // The next two lines tell the new client that “this” current class will handle connection stuff
            .addConnectionCallbacks(this)
    .addOnConnectionFailedListener(this)
    //fourth line adds the LocationServices API endpoint from GooglePlayServices
    .addApi(LocationServices.API)
    .build();

    // Create the LocationRequest object
    mLocationRequest = LocationRequest.create()
            .setPriority(LocationRequest.PRIORITY_HIGH_ACCURACY)
    .setInterval(10 * 1000)        // 10 seconds, in milliseconds
    .setFastestInterval(1 * 1000); // 1 second, in milliseconds

}
    @Override
    protected void onResume() {
        super.onResume();
        //Now lets connect to the API
        mGoogleApiClient.connect();
    }

    @Override
    protected void onPause() {
        super.onPause();
        Log.v(this.getClass().getSimpleName(), "onPause()");

        //Disconnect from API onPause()
        if (mGoogleApiClient.isConnected()) {
            LocationServices.FusedLocationApi.removeLocationUpdates(mGoogleApiClient, this);
            mGoogleApiClient.disconnect();
        }


    }

    /**
     * If connected get lat and long
     *
     */
    @Override
    public void onConnected(Bundle bundle) {
        Location location = LocationServices.FusedLocationApi.getLastLocation(mGoogleApiClient);

        if (location == null) {
            LocationServices.FusedLocationApi.requestLocationUpdates(mGoogleApiClient, mLocationRequest, this);

        } else {
            //If everything went fine lets get latitude and longitude
            currentLatitude = location.getLatitude();
            currentLongitude = location.getLongitude();
            Log.e("check it", "lattitude    "+currentLatitude+" longitude    "+ currentLongitude);
            Toast.makeText(this, currentLatitude + " WORKS " + currentLongitude + "", Toast.LENGTH_LONG).show();
        }
    }


    @Override
    public void onConnectionSuspended(int i) {}

    @Override
    public void onConnectionFailed(ConnectionResult connectionResult) {
            /*
             * Google Play services can resolve some errors it detects.
             * If the error has a resolution, try sending an Intent to
             * start a Google Play services activity that can resolve
             * error.
             */
        if (connectionResult.hasResolution()) {
            try {
                // Start an Activity that tries to resolve the error
                connectionResult.startResolutionForResult(this, CONNECTION_FAILURE_RESOLUTION_REQUEST);
                    /*
                     * Thrown if Google Play services canceled the original
                     * PendingIntent
                     */
            } catch (IntentSender.SendIntentException e) {
                // Log the error
                e.printStackTrace();
            }
        } else {
                /*
                 * If no resolution is available, display a dialog to the
                 * user with the error.
                 */
            Log.e("Error", "Location services connection failed with code " + connectionResult.getErrorCode());
        }
    }

    /**
     * If locationChanges change lat and long
     *
     *
     * @param location
     */
    @Override
    public void onLocationChanged(Location location) {
        currentLatitude = location.getLatitude();
        currentLongitude = location.getLongitude();
        Log.e("check it   m nmln l nk ", "lattitude    "+currentLatitude+" longitude    "+currentLongitude);

        Toast.makeText(this, currentLatitude + " WORKS " + currentLongitude + "", Toast.LENGTH_LONG).show();
    }

}

這是我的字符串短信:

 String message= " https://www.google.com/maps?q=000000,000000";

這是發送方法:

 private void sendSMS(String ph, String message) {
        SmsManager smsManager = SmsManager.getDefault();
        smsManager.sendTextMessage(ph, null, message,  null, null);
        Toast.makeText(getApplicationContext(), "SMS SENT",
                Toast.LENGTH_LONG).show();
    }

我的服務:

public class MyService extends Service implements SensorEventListener {

    public MyService() {
    }

    @Override
    public IBinder onBind(Intent intent) {
        // TODO: Return the communication channel to the service.
        throw new UnsupportedOperationException("Not yet implemented");
    }

    int count = 1;
    private boolean init;
    private Sensor mySensor;
    private SensorManager SM;
    private float x1, x2, x3;
    private static final float ERROR = (float) 7.0;
    private static final float SHAKE_THRESHOLD = 15.00f; // m/S**2
    private static final int MIN_TIME_BETWEEN_SHAKES_MILLISECS = 1000;
    private long mLastShakeTime;


    @Override
    public void onCreate() {


        }


    @Override


    public void onSensorChanged(SensorEvent event) {

        if (event.sensor.getType() == Sensor.TYPE_ACCELEROMETER) {


            long curTime = System.currentTimeMillis();
            if ((curTime - mLastShakeTime) > MIN_TIME_BETWEEN_SHAKES_MILLISECS) {

                float x = event.values[0];
                float y = event.values[1];
                float z = event.values[2];

                double acceleration = Math.sqrt(Math.pow(x, 2) +
                        Math.pow(y, 2) +
                        Math.pow(z, 2)) - SensorManager.GRAVITY_EARTH;
                Log.d("mySensor", "Acceleration is " + acceleration + "m/s^2");

                if (acceleration > SHAKE_THRESHOLD) {
                    mLastShakeTime = curTime;
                    Toast.makeText(getApplicationContext(), "FALL DETECTED",
                            Toast.LENGTH_LONG).show();
                    SharedPreferences sharedPref = getSharedPreferences("nameInfo", Context.MODE_PRIVATE);
                    String ph = sharedPref.getString ("phone","");
                  //  String message=  "help me";
                    String message= " https://www.google.com/maps?q=39283,87353";
                    sendSMS(ph, message);
                }
            }
        }
    }

    private void sendSMS(String ph, String message) {
        SmsManager smsManager = SmsManager.getDefault();
        smsManager.sendTextMessage(ph, null, message,  null, null);
        Toast.makeText(getApplicationContext(), "SMS SENT",
                Toast.LENGTH_LONG).show();
    }


    public int onStartCommand(Intent intent, int flags, int startId) {
        Toast.makeText(this, "Start Detecting", Toast.LENGTH_LONG).show();
        SM = (SensorManager) getSystemService(SENSOR_SERVICE);
        mySensor = SM.getDefaultSensor(Sensor.TYPE_ACCELEROMETER);
        SM.registerListener(this, mySensor, SensorManager.SENSOR_DELAY_NORMAL);

        //here u should make your service foreground so it will keep working even if app closed


        return Service.START_STICKY;

    }


    @Override
    public void onDestroy() {
        Toast.makeText(this, "Stop Detecting", Toast.LENGTH_LONG).show();

    }

    public void onAccuracyChanged(Sensor sensor, int accuracy) {
        //Noting to do!!
    }

使java類類似於track,然后創建track類的對象,然后在復制google map url之后從您的Main類調用它,然后調用getlattitude和getlongitude。

像這樣更改您的班級:

public class Location_Getter extends AppCompatActivity implements
    ConnectionCallbacks,
    OnConnectionFailedListener,
    LocationListener {

//Define a request code to send to Google Play services
private final static int CONNECTION_FAILURE_RESOLUTION_REQUEST = 9000;
private GoogleApiClient mGoogleApiClient;
private LocationRequest mLocationRequest;
private double currentLatitude;
private double currentLongitude;
   private static int UPDATE_INTERVAL = 2 * 1000;
private static int FASTEST_INTERVAL = 1 * 1000;
private static int DISPLACEMENT = 1;


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


mGoogleApiClient = new GoogleApiClient.Builder(this)
        // The next two lines tell the new client that “this” current class will handle connection stuff
        .addConnectionCallbacks(this)
.addOnConnectionFailedListener(this)
//fourth line adds the LocationServices API endpoint from GooglePlayServices
.addApi(LocationServices.API)
.build();

// Create the LocationRequest object
mLocationRequest = LocationRequest.create()
        .setPriority(LocationRequest.PRIORITY_HIGH_ACCURACY)
.setInterval(10 * 1000)        // 10 seconds, in milliseconds
.setFastestInterval(1 * 1000); // 1 second, in milliseconds

  }
  @Override
   protected void onResume() {
    super.onResume();
    //Now lets connect to the API
    mGoogleApiClient.connect();
   }

@Override
protected void onPause() {
    super.onPause();
    Log.v(this.getClass().getSimpleName(), "onPause()");

    //Disconnect from API onPause()
    if (mGoogleApiClient.isConnected()) {
        LocationServices.FusedLocationApi.removeLocationUpdates(mGoogleApiClient, this);
        mGoogleApiClient.disconnect();
    }


}

/**
 * If connected get lat and long
 *
 */
@Override
public void onConnected(Bundle bundle) {

    createLocationRequest();
    Location location = LocationServices.FusedLocationApi.getLastLocation(mGoogleApiClient);

    if (location == null) {
        LocationServices.FusedLocationApi.requestLocationUpdates(mGoogleApiClient, mLocationRequest, this);

    } else {
        //If everything went fine lets get latitude and longitude
        currentLatitude = location.getLatitude();
        currentLongitude = location.getLongitude();
        Log.e("check it", "lattitude    "+currentLatitude+" longitude    "+ currentLongitude);
        Toast.makeText(this, currentLatitude + " WORKS " + currentLongitude + "", Toast.LENGTH_LONG).show();
    }
}


@Override
public void onConnectionSuspended(int i) {}

@Override
public void onConnectionFailed(ConnectionResult connectionResult) {
        /*
         * Google Play services can resolve some errors it detects.
         * If the error has a resolution, try sending an Intent to
         * start a Google Play services activity that can resolve
         * error.
         */
    if (connectionResult.hasResolution()) {
        try {
            // Start an Activity that tries to resolve the error
            connectionResult.startResolutionForResult(this,    CONNECTION_FAILURE_RESOLUTION_REQUEST);
                /*
                 * Thrown if Google Play services canceled the original
                 * PendingIntent
                 */
        } catch (IntentSender.SendIntentException e) {
            // Log the error
            e.printStackTrace();
        }
    } else {
            /*
             * If no resolution is available, display a dialog to the
             * user with the error.
             */
        Log.e("Error", "Location services connection failed with code " + connectionResult.getErrorCode());
    }
}

/**
 * If locationChanges change lat and long
 *
 *
 * @param location
 */
@Override
public void onLocationChanged(Location location) {
    currentLatitude = location.getLatitude();
    currentLongitude = location.getLongitude();
    Log.e("check it   m nmln l nk ", "lattitude    "+currentLatitude+" longitude    "+currentLongitude);

    Toast.makeText(this, currentLatitude + " WORKS " + currentLongitude + "", Toast.LENGTH_LONG).show();
}

    protected void createLocationRequest() {

    try {

        mLocationRequest = new LocationRequest();
        mLocationRequest.setInterval(UPDATE_INTERVAL);
        mLocationRequest.setFastestInterval(FASTEST_INTERVAL);
        mLocationRequest.setPriority(LocationRequest.PRIORITY_HIGH_ACCURACY);
        mLocationRequest.setSmallestDisplacement(DISPLACEMENT);

    } catch (Exception e) {
    }
}

}

像這樣更改sendMessage方法:

private void sendSMS(String ph, String message,Location location) {
    SmsManager smsManager = SmsManager.getDefault();
    String message = "Latitude :" +location.getLatitude() + " Longitude : "+location.getLongitude();
    smsManager.sendTextMessage(ph, null, message,  null, null);
    Toast.makeText(getApplicationContext(), "SMS SENT",
            Toast.LENGTH_LONG).show();
  }

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM