当手机锁定时在 Android 中获取用户的位置

2024-02-25

我正在寻找一种解决方案,以在 Android API 17 (Android 4.2) 中的特定时间间隔以及手机锁定时获取用户的位置。

我已经尝试过一些不同的代码,检查了很多教程并搜索了网络上的几乎所有地方。解决方案可能就在那里,但我认为这是由于缺乏 Android 开发和解释不同正确解决方案和方法的经验。

起初,我有一些非常基本的代码,当屏幕打开时,它们运行得很好。即使在后台,位置也会更新(因为我可以通过 Toast 消息检查经度和纬度)。 我使用了一个处理程序来执行此操作:

    public void locationRunnable() {
    final Handler locationHandler = new Handler();
    final int distanceDelay = 5000; // milliseconds

    locationHandler.postDelayed(new Runnable(){
        public void run() {
            // code
            mMap.clear();

            if (ActivityCompat.checkSelfPermission(this, android.Manifest.permission.ACCESS_FINE_LOCATION) != PackageManager.PERMISSION_GRANTED && ActivityCompat.checkSelfPermission(this, android.Manifest.permission.ACCESS_COARSE_LOCATION) != PackageManager.PERMISSION_GRANTED) {
                // TODO: Consider calling
                //    ActivityCompat#requestPermissions
                // here to request the missing permissions, and then overriding
                //   public void onRequestPermissionsResult(int requestCode, String[] permissions,
                //                                          int[] grantResults)
                // to handle the case where the user grants the permission. See the documentation
                // for ActivityCompat#requestPermissions for more details.
                return;
            }

            mMap.setMyLocationEnabled(true);
            mMap.setBuildingsEnabled(true);
            mMap.getUiSettings().setMyLocationButtonEnabled(false);

            LocationManager locationManager = (LocationManager) getSystemService(Context.LOCATION_SERVICE);
            Criteria criteria = new Criteria();
            String provider = locationManager.getBestProvider(criteria, true);

            myLocation = locationManager.getLastKnownLocation(provider);

            if (myLocation != null) {
                latitudeCurrentPosition = myLocation.getLatitude();
                longitudeCurrentPosition = myLocation.getLongitude();
            }

            currentPattern = shortTest;
            Notification.Builder notificationBuilderChecking = new Notification.Builder(this)
                    .setSmallIcon(R.mipmap.ic_launcher)
                    .setLargeIcon(BitmapFactory.decodeResource(getResources(), R.mipmap.ic_launcher))
                    .setContentTitle("Test app")
                    .setAutoCancel(true)
                    .setOnlyAlertOnce(false)
                    .setContentText("Getting location!")
                    .setPriority(Notification.PRIORITY_MAX)
                    .setLights(0xffffffff, 200, 200)
                    .setVibrate(currentPattern);

            Notification notification2 = notificationBuilderChecking.build();

            NotificationManager notificationMngr2 = (NotificationManager) getSystemService(Context.NOTIFICATION_SERVICE);
            notificationMngr2.notify(NOTIFICATION_ID, notification2);

            locationHandler.postDelayed(this, distanceDelay);
        }

    }, distanceDelay);

}

这只是一个片段,目的是在后台,当屏幕锁定时,每 10 秒循环一次。确实如此。即使手机被锁定,也只能锁定3次左右。 3 次后,计时器开始计时,手机振动频率降低(妨碍打瞌睡功能?)。 此外,手机会振动,但位置不会更新。当我在前台使用应用程序解锁手机时,位置仍然是锁定手机时的位置。一段时间(10 秒)后它会更新。我使用地图上的标记来检查。

再次强调:当手机解锁时它可以工作。

现在我尝试使用服务、服务(意图服务)或广播接收器,并启动一个新线程,但我不知道如何操作,也没有任何效果。

我最后的一些代码包含一个无法正常工作的广播接收器,而最新的代码包含一个 AlarmManager:

    public void getLocation(Context context) {

    AlarmManager am = (AlarmManager) context.getSystemService(Context.ALARM_SERVICE);
    Intent intent = new Intent(context, AlarmIntent.class);
    PendingIntent pi = PendingIntent.getBroadcast(context, 0, intent, 0);
    //After after 30 seconds
    am.setRepeating(AlarmManager.ELAPSED_REALTIME_WAKEUP, System.currentTimeMillis(), 10000, pi);


    context.getSystemService(Context.CONNECTIVITY_SERVICE);

    mMap.clear();

    mMap.setMyLocationEnabled(true);
    mMap.getUiSettings().setMyLocationButtonEnabled(false);

    LocationManager locationManager = (LocationManager) context.getSystemService(Context.LOCATION_SERVICE);
    Criteria criteria = new Criteria();
    String provider = locationManager.getBestProvider(criteria, true);

    myLocation = locationManager.getLastKnownLocation(provider);

    latitudeCurrentPosition = myLocation.getLatitude();
    longitudeCurrentPosition = myLocation.getLongitude();

    LatLng latLngCurrent = new LatLng(latitudeCurrentPosition, longitudeCurrentPosition);

    mMap.moveCamera(CameraUpdateFactory.newLatLng(latLngCurrent));
    mMap.animateCamera(CameraUpdateFactory.zoomTo(distZoom));

    currentPattern = shortTest;
    showNotification(context);

    mHereIAm = mMap.addMarker(new MarkerOptions()
            .position(new LatLng(latitudeCurrentPosition, longitudeCurrentPosition))
            .title(weAreHere)
            .draggable(false)
            .icon(BitmapDescriptorFactory
                    .fromResource(R.drawable.marker_iconv3)));
    mHereIAm.setTag(0);
    mHereIAm.showInfoWindow();
}

AndroidManifest权限:

    <uses-permission android:name="android.permission.ACCESS_FINE_LOCATION" />
<uses-permission android:name="android.permission.VIBRATE" />
<uses-permission android:name="android.permission.WAKE_LOCK" />
<uses-permission android:name="com.android.alarm.permission.SET_ALARM" />

但在长到 10000 时,Android Studio 告诉我“从 Android 5.1 开始,值将被强制达到 60000;不要依赖于此......”等等。因此 AlarmManager 也没有用。 使用最后的代码,我的应用程序甚至不再运行。

但仍然:振动和其他东西仍然会发生,但位置更新不会。

简而言之: 我需要一些基本的(至少,我认为它不会那么困难,因为唯一的问题是当屏幕锁定时它不起作用)代码,以特定的可变间隔更新我的位置。

也许我必须使用处理程序/可运行的,启动一个新线程,使用服务或广播接收器。也许 AlarmManager 也可以工作,但我不知道如何使用以及使用哪个。

这是我的第一篇文章。如果有什么遗漏或者你们需要更多信息,请询问。我试图尽可能精确,而不使用太多开销。

Edit 01我可以使用就业服务来做到这一点吗? - 我已将 API 更新到 21,因此我可以使用此服务,但我不知道这是否是我正在寻找的正确解决方案?有一些很棒的使用教程。

Edit 02让我以更少的开销说得更清楚:我正在寻找一种解决方案,以在设备锁定时获取用户的当前位置:使用 API、服务、IntentService、BroadcastReceiver,... - 每个教程都告诉我一些不同的内容,即使在 Stack Overflow,我也很难找到正确的解决方案。 我能够使用服务和意图服务,但由于一些错误,我无法请求任何位置更新,例如:java.lang.RuntimeException: Unable to start activity ComponentInfo{com.name.name/com.name.name.MapsActivity}: java.lang.NullPointerException: Attempt to invoke virtual method 'void com.google.android.gms.maps.GoogleMap.setMyLocationEnabled(b‌​oolean)' on a null object reference- 寻找这个错误的解决方案,后来又给了我另一个错误,然后,然后……我陷入了错误循环和很多不必要的代码。

我希望有一种简单的方法来获取用户的位置,你们可以帮助我。再次感谢。

Edit 03我已按照以下说明进行操作本教程 http://www.androidhive.info/2012/07/android-gps-location-manager-tutorial/并且正在检查位置。请看下面的代码:

public class LocationService extends Service implements LocationListener {

private final Context mContext;

// flag for GPS status
boolean isGPSEnabled = false;

// flag for network status
boolean isNetworkEnabled = false;

// flag for GPS status
boolean canGetLocation = false;

Location location; // location
double latitude; // latitude
double longitude; // longitude

// The minimum distance to change Updates in meters
private static final long MIN_DISTANCE_CHANGE_FOR_UPDATES = 10; // 10 meters

// The minimum time between updates in milliseconds
private static final long MIN_TIME_BW_UPDATES = 1000 * 60 * 1; // 1 minute

// Declaring a Location Manager
protected LocationManager locationManager;

public LocationService(Context context) {
    this.mContext = context;
    getLocation();
}

public Location getLocation() {
    try {
        locationManager = (LocationManager) mContext
                .getSystemService(LOCATION_SERVICE);

        // getting GPS status
        isGPSEnabled = locationManager
                .isProviderEnabled(LocationManager.GPS_PROVIDER);

        // getting network status
        //isNetworkEnabled = locationManager
        //        .isProviderEnabled(LocationManager.NETWORK_PROVIDER);

        if (!isGPSEnabled && !isNetworkEnabled) {
            // no network provider is enabled
        } else {
            this.canGetLocation = true;
            // First get location from Network Provider
            if (isNetworkEnabled) {
                locationManager.requestLocationUpdates(
                        LocationManager.NETWORK_PROVIDER,
                        MIN_TIME_BW_UPDATES,
                        MIN_DISTANCE_CHANGE_FOR_UPDATES, this);
                Log.d("Network", "Network");
                if (locationManager != null) {
                    location = locationManager
                            .getLastKnownLocation(LocationManager.NETWORK_PROVIDER);
                    if (location != null) {
                        latitude = location.getLatitude();
                        longitude = location.getLongitude();
                    }
                }
            }
            // if GPS Enabled get lat/long using GPS Services
            if (isGPSEnabled) {
                if (location == null) {
                    locationManager.requestLocationUpdates(
                            LocationManager.GPS_PROVIDER,
                            MIN_TIME_BW_UPDATES,
                            MIN_DISTANCE_CHANGE_FOR_UPDATES, this);
                    Log.d("GPS Enabled", "GPS Enabled");
                    if (locationManager != null) {
                        location = locationManager
                                .getLastKnownLocation(LocationManager.GPS_PROVIDER);
                        if (location != null) {
                            latitude = location.getLatitude();
                            longitude = location.getLongitude();
                        }
                    }
                }
            }
        }

    } catch (Exception e) {
        e.printStackTrace();
    }

    return location;
}

/**
 * Stop using GPS listener
 * Calling this function will stop using GPS in your app
 * */
public void stopUsingGPS(){
    if(locationManager != null){
        locationManager.removeUpdates(LocationService.this);
    }
}

/**
 * Function to get latitude
 * */
public double getLatitude(){
    if(location != null){
        latitude = location.getLatitude();
    }

    // return latitude
    return latitude;
}

/**
 * Function to get longitude
 * */
public double getLongitude(){
    if(location != null){
        longitude = location.getLongitude();
    }

    // return longitude
    return longitude;
}

/**
 * Function to check GPS/wifi enabled
 * @return boolean
 * */
public boolean canGetLocation() {
    return this.canGetLocation;
}

/**
 * Function to show settings alert dialog
 * On pressing Settings button will lauch Settings Options
 * */
public void showSettingsAlert(){
    AlertDialog.Builder alertDialog = new AlertDialog.Builder(mContext);

    // Setting Dialog Title
    alertDialog.setTitle("GPS is settings");

    // Setting Dialog Message
    alertDialog.setMessage("GPS is not enabled. Do you want to go to settings menu?");

    // On pressing Settings button
    alertDialog.setPositiveButton("Settings", new DialogInterface.OnClickListener() {
        public void onClick(DialogInterface dialog,int which) {
            Intent intent = new Intent(Settings.ACTION_LOCATION_SOURCE_SETTINGS);
            mContext.startActivity(intent);
        }
    });

    // on pressing cancel button
    alertDialog.setNegativeButton("Cancel", new DialogInterface.OnClickListener() {
        public void onClick(DialogInterface dialog, int which) {
            dialog.cancel();
        }
    });

    // Showing Alert Message
    alertDialog.show();
}

@Override
public void onLocationChanged(Location location) {
}

@Override
public void onProviderDisabled(String provider) {
}

@Override
public void onProviderEnabled(String provider) {
}

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

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

}

我已禁用网络位置,只允许 GPS 位置进行测试 - 两者都进行了测试。

还有我的 MapsActivity:

    public void getLocation(){
    gps = new LocationService(MapsActivity.this);
    if(gps.canGetLocation()) { // gps enabled} // return boolean true/false
        latitudeCurrentPosition = gps.getLatitude(); // returns latitude
        longitudeCurrentPosition = gps.getLongitude(); // returns longitude

        latLngCurrent = new LatLng(latitudeCurrentPosition, longitudeCurrentPosition);

        Toast toastLatCur = makeText(getApplicationContext(), "Lat Current: " + latitudeCurrentPosition + "" ,Toast.LENGTH_SHORT);
        toastLatCur.show();

        Toast toastLongCur = makeText(getApplicationContext(), "Long Current: " + longitudeCurrentPosition + "" ,Toast.LENGTH_SHORT);
        toastLongCur.show();
    }

    else {
        gps.showSettingsAlert();
    }

    if(goToLocation){
        mMap.moveCamera(CameraUpdateFactory.newLatLng(latLngCurrent));
        goToLocation = false;

        if(firstStart){
            mMap.animateCamera(CameraUpdateFactory.zoomTo(distZoom));
            firstStart = false;
        }
    }

    vibrateNotification();
}

当屏幕锁定时,手机会振动,正如我所说的vibrateNotificatoin()- 每 10 秒完美运行一次。但位置没有更新!所以服务并不是解决这个问题的正确方法。帮助!


您应该使用service即使应用程序未运行,也可以执行需要完成的任务。试一下。

本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系:hwhale#tublm.com(使用前将#替换为@)

当手机锁定时在 Android 中获取用户的位置 的相关文章

随机推荐