以下是我的代码,当我接近此代码时


  (距离我当前位置不到100米)
  9.443469,76.540650


gps位置,我需要振动手机,但是到达那里时,它没有振动,并且显示错误的lan和lon。我的代码有什么问题?

import android.Manifest;
import android.app.ActivityManager;
import android.app.AlarmManager;
import android.app.PendingIntent;
import android.app.Service;
import android.content.Context;
import android.content.Intent;
import android.content.IntentFilter;
import android.content.pm.PackageManager;
import android.location.Address;
import android.location.Geocoder;
import android.location.Location;
import android.location.LocationListener;
import android.location.LocationManager;
import android.os.Build;
import android.os.Bundle;
import android.os.Handler;
import android.os.IBinder;
import android.os.SystemClock;
import android.os.VibrationEffect;
import android.os.Vibrator;
import android.util.Log;
import android.widget.Toast;

import java.io.IOException;
import java.util.List;
import java.util.Locale;

import androidx.annotation.Nullable;
import io.nlopez.smartlocation.OnLocationUpdatedListener;
import io.nlopez.smartlocation.SmartLocation;
import io.nlopez.smartlocation.location.config.LocationAccuracy;
import io.nlopez.smartlocation.location.config.LocationParams;

public class OfferLocator extends Service {
    SmartLocation mSmartLocation;
    LocationParams locationParam = null;
    double l2 = 9.443469, lo2 = 76.540650, lan = 0, lon = 0;
    boolean running = false;
    double prelan = 0, prelon = 0;
    MyLocationListener locationListener;
    int ct = 0;
    LocationManager locationManager;

    private void info() {
        if (locationManager == null) {
            locationManager = (LocationManager)
                    getSystemService(Context.LOCATION_SERVICE);
        }
        if (locationListener == null) {
            locationListener = new MyLocationListener();
            if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.M) {
                if (checkSelfPermission(Manifest.permission.ACCESS_FINE_LOCATION) != PackageManager.PERMISSION_GRANTED && checkSelfPermission(Manifest.permission.ACCESS_COARSE_LOCATION) != PackageManager.PERMISSION_GRANTED) {
                    return;
                }
            }
        }

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

        Log.i("OfferLocator_info","info called "+ct+" times  lan lon "+lan+","+lon);
        ct++;
        new Handler().postDelayed(new Runnable() {
            @Override
            public void run() {
                info();
            }
        },10000);
        try {
           if(locationParam==null) locationParam = new LocationParams.Builder().setAccuracy(LocationAccuracy.HIGH).build();
        } catch (Exception e){
            Log.i("OfferLocatorv2","error2 :"+e.getMessage()+"");
        }
    }

    @Override
    public void onCreate() {
        super.onCreate();
        Log.d("myLog", "Service: onCreate");
        try {
            locationParam = new LocationParams.Builder().setAccuracy(LocationAccuracy.HIGH).build();
        } catch (Exception e){
            Log.i("OfferLocatorv2","error2 :"+e.getMessage()+"");
        }
        info();
    }

    @Override
    public int onStartCommand(Intent intent, int flags, int startId) {
        Log.d("myLog", "Service: onStartCommand");
        return START_STICKY;
    }

    @Override
    public void onTaskRemoved(Intent rootIntent) {
        Log.d("myLog", "Service: onTaskRemoved");

        Intent restartService = new Intent(getApplicationContext(), this.getClass());
        restartService.setPackage(getPackageName());
        PendingIntent restartServicePI = PendingIntent.getService(
                getApplicationContext(), 1, restartService,
                PendingIntent.FLAG_ONE_SHOT);
        AlarmManager alarmService = (AlarmManager) getApplicationContext().getSystemService(Context.ALARM_SERVICE);
        alarmService.set(AlarmManager.ELAPSED_REALTIME, SystemClock.elapsedRealtime() + 1000, restartServicePI);

        if (Build.VERSION.SDK_INT <= 19) {
            Intent restart = new Intent(getApplicationContext(), this.getClass());
            restart.setPackage(getPackageName());
            startService(restart);
        }

        super.onTaskRemoved(rootIntent);
    }

    @Override
    public void onDestroy() {
        super.onDestroy();
        if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.O) {
            startForegroundService(new Intent(getApplicationContext(),OfferLocator.class));
        } else {
            startService(new Intent(getApplicationContext(),OfferLocator.class));
        }
        Log.d("myLog", "Service: onDestroy");
        // unregisterReceiver(batteryReceiver);
    }

    private boolean isMyServiceRunning(Class<?> serviceClass) {
        ActivityManager manager = (ActivityManager) getSystemService(Context.ACTIVITY_SERVICE);
        for (ActivityManager.RunningServiceInfo service : manager.getRunningServices(Integer.MAX_VALUE)) {
            if (serviceClass.getName().equals(service.service.getClassName())) {
                return true;
            }
        }
        return false;
    }

    @Nullable
    @Override
    public IBinder onBind(Intent intent) {
        return null;
    }

    class MyLocationListener implements LocationListener {
        String TAG="newloc";
        @Override
        public void onLocationChanged(Location loc) {
            //  editLocation.setText("");
            // pb.setVisibility(View.INVISIBLE);
            double l2 = 9.443469, lo2 = 76.540650;
            float[] results = new float[1];
            Location.distanceBetween( loc.getLatitude(), loc.getLongitude(),l2,lo2, results);
            if (results[0]<100) {
                Toast.makeText(getApplicationContext(),"vibrate please "+results[0],Toast.LENGTH_SHORT).show();
                try {
                    Vibrator v = (Vibrator) getSystemService(getApplicationContext().VIBRATOR_SERVICE);
                    // Vibrate for 500 milliseconds
                    if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.O) {
                        v.vibrate(VibrationEffect.createOneShot(1500, VibrationEffect.DEFAULT_AMPLITUDE));
                    } else {
                        //deprecated in API 26
                        v.vibrate(1500);
                    }
                } catch (Exception e){
                    Log.i("OfferLocatorv2","error4 :"+e.getMessage()+"");
                }
            } else {
                if (results[0]>500) {
                    try {
                        Vibrator v = (Vibrator) getSystemService(getApplicationContext().VIBRATOR_SERVICE);
                        // Vibrate for 500 milliseconds
                        if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.O) {
                            v.vibrate(VibrationEffect.createOneShot(1500, VibrationEffect.DEFAULT_AMPLITUDE));
                        } else {
                        //deprecated in API 26
                            v.vibrate(1500);
                        }
                    }catch (Exception e){
                        Log.i("OfferLocatorv2","error4 :"+e.getMessage()+"");
                    }
                }
                Toast.makeText(getApplicationContext(),"my current location is "+results[0],Toast.LENGTH_SHORT).show();
            }

            String longitude = "Longitude: " + loc.getLongitude();
            Log.v(TAG, longitude);
            String latitude = "Latitude: " + loc.getLatitude();
            Log.v(TAG, latitude);

            /*------- To get city name from coordinates -------- */
            String cityName = null;
            Geocoder gcd = new Geocoder(getBaseContext(), Locale.getDefault());
            List<Address> addresses;
            try {
                addresses = gcd.getFromLocation(loc.getLatitude(),
                        loc.getLongitude(), 1);
                if (addresses.size() > 0) {
                    System.out.println(addresses.get(0).getLocality());
                    cityName = addresses.get(0).getLocality();
                }
            } catch (IOException e) {
                e.printStackTrace();
            }
            String s = longitude + "\n" + latitude + "\n\nMy Current City is: " + cityName;
            // editLocation.setText(s);
        }

        @Override
        public void onProviderDisabled(String provider) {}

        @Override
        public void onProviderEnabled(String provider) {}

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

最佳答案

如果您已从Google地图获取坐标,则它们可能与通过MapsActivity从同一位置获取的坐标略有不同。尝试使用MapsActivity来获取您希望手机通过另一个应用程序振动的点的坐标,该MapsActivity可以简单地为您提供位置坐标。

10-02 23:59