0

こんにちは、これは経度と緯度を取得するための私のコードです。このクラスを呼び出す方法と、URL を介して文字列 sms で調整して送信する方法を知りたいのですが、このコードにエラーがないことをもう 1 つ伝えたいと思います。しかし、アプリでこれを使用すると、トーストが表示されません。誰か助けてください。

ここに私のロケーションクラスがあります:

    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();
    }

}

ここに私の文字列SMSがあります:

 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!!
    }
4

2 に答える 2

1

トラックのようなJavaクラスを作成し、トラッククラスのオブジェクトを作成し、メインクラスから呼び出してから、GoogleマップのURLをコピーしてから、 getlattitude と getlongitude を呼び出します。

于 2016-04-13T06:04:09.903 に答える
0

次のようにクラスを変更します。

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();
  }
于 2016-04-07T05:55:07.933 に答える