无法在后台服务中使用locationmanager获取位置更新

7uzetpgm  于 2021-07-06  发布在  Java
关注(0)|答案(0)|浏览(275)

我试图使一个应用程序,监测用户的位置时,电源按钮被按下。通过mainactivity,我创建了一个前台服务&注册了一个监视电源按钮点击的广播接收器。当用户两次单击电源按钮时,将打开一个服务,其中使用locationmanager获取用户位置并将其存储在firebase中。
当我的应用程序打开时,我按了两次电源按钮,我的位置就会被正确跟踪。然后在最小化我的应用程序(不退出或关闭它)后,当我在大约10秒后再次按下电源按钮两次时,位置仍然会被跟踪。
但是,如果我在应用程序关闭后等待一分钟,并尝试执行相同的操作,而服务本身启动,则不会跟踪位置,因为onlocationchanged()不再接收位置更新。但是如果我重新打开应用程序,位置更新会突然再次启动&onlocationchanged()会被触发。我也没有收到任何错误消息。我在android方面没有太多的经验,所以非常抱歉我的错误解释,请原谅我所犯的任何我没有意识到的错误。
非常感谢您的帮助。谢谢。

public class ExecutionService extends Service {

    private LocationManager locationManager;
    private LocationListener locationListener;

    private final long MIN_TIME = 1000 * 60 * 2;
    private final long MIN_DIST = 20;

    DatabaseReference databaseReference, locRef;

    @Override
    public void onCreate() {
        databaseReference = FirebaseDatabase.getInstance().getReference("Address/");
        locRef = FirebaseDatabase.getInstance().getReference("Location/");

        super.onCreate();
    }

    public ExecutionService() {
//        Toast.makeText(this, "Execution Service Running!", Toast.LENGTH_LONG).show();
    }

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

    @Override
    public boolean onUnbind(Intent intent) {
        Log.d("ExecutionService", "Execution Service Unbinded!");
        return super.onUnbind(intent);
    }

    @Override
    public int onStartCommand(Intent intent, int flags, int startId) {
        Toast.makeText(this, "Execution Service Running!", Toast.LENGTH_LONG).show();
        Log.d("ExecutionService", "Execution Service Running!");
        locationDetector();

        return START_NOT_STICKY;
    }

    @Override
    public void onDestroy() {
        Log.d("ExecutionService", "Execution Service Destroyed!");
        super.onDestroy();
    }

    private void locationDetector() {

        locationListener = new LocationListener() {
            @Override
            public void onLocationChanged(Location location) {
                try {

                    Toast.makeText(getApplicationContext(), "LocationChanged!", Toast.LENGTH_LONG).show();
                    Log.d("ExecutionService", "LocationChanged!");

                    String phoneNumber = "6546768431";
                    double myLat = location.getLatitude();
                    double myLong = location.getLongitude();
                    String myLatitude = String.valueOf(location.getLatitude());
                    String myLongitude = String.valueOf(location.getLongitude());

                    String address = null;

                    address = getAddressFromLocation(myLat, myLong, ExecutionService.this);

                    String message = "Latitude = " + myLatitude + "   Longitude = " + myLongitude;

//                    SmsManager smsManager = SmsManager.getDefault();
//                    smsManager.sendTextMessage(phoneNumber,null,message,null,null);

                    String id = databaseReference.push().getKey();

                    locRef.child(id).setValue(message);

                    if(address!=null)
                    {
                        message = address;
                    }

                    databaseReference.child(id).setValue(message);
                } catch (Exception e) {
                    e.printStackTrace();
                }
            }

            @Override
            public void onStatusChanged(String provider, int status, Bundle extras) {
                Log.d("ExecutionService", "onStatusChanged triggered!");
            }

            @Override
            public void onProviderEnabled(String provider) {
                Log.d("ExecutionService", "onProviderEnabled triggered!");
            }

            @Override
            public void onProviderDisabled(String provider) {
                Log.d("ExecutionService", "onProviderDisabled triggered!");
            }
        };

        locationManager = (LocationManager) getSystemService(LOCATION_SERVICE);

        Log.d("ExecutionService", "After getting location service");

        try {
            Log.d("ExecutionService", "Requesting location updates");
            locationManager.requestLocationUpdates(LocationManager.NETWORK_PROVIDER, 1000, MIN_DIST, locationListener);
            locationManager.requestLocationUpdates(LocationManager.GPS_PROVIDER, 1000, MIN_DIST, locationListener);
        } catch (SecurityException e) {
            e.printStackTrace();
            Log.d("ExecutionService", "Security Exception Triggered!");
        }

    }

    public static String getAddressFromLocation(final double latitude, final double longitude, final Context context) {

                Geocoder geocoder = new Geocoder(context, Locale.getDefault());
                String result = null;
                try {
                    List<Address> addressList = geocoder.getFromLocation( latitude, longitude, 1);
                    if (addressList != null && addressList.size() > 0) {
                        Address address = addressList.get(0);
                        StringBuilder sb = new StringBuilder();
//                        sb.append(address);
                        for (int i = 0; i <= address.getMaxAddressLineIndex(); i++) {
//                            sb.append(address.getAddressLine(i)).append("\n");
                            sb.append(address.getAddressLine(i));
                        }
//                        sb.append(address.getLocality()).append("\n");
//                        sb.append(address.getPostalCode()).append("\n");
//                        sb.append(address.getCountryName());
                        result = sb.toString();
                    }
                } catch (IOException e) {
                    Log.e(TAG, "Unable connect to Geocoder", e);
                }

                return result;
            }

    }

暂无答案!

目前还没有任何答案,快来回答吧!

相关问题