【问题标题】:One service to allow location updates for multiple activities一项服务允许对多项活动进行位置更新
【发布时间】:2018-05-25 13:48:40
【问题描述】:

我编写了一个应用程序,可以在单个活动中获取 位置 更新。现在我希望在同一应用程序的另一个活动中使用 位置 更新。

我不想在其他活动中重复代码。

所以我正在考虑使用绑定服务并在其中接收位置更新,其中 2 个活动从该绑定服务获取更新?

这是最好的方法吗?

【问题讨论】:

  • 你可以创建一个广播接收器并为此注册这两个活动,你可以为广播接收器和东西做谷歌。
  • No Bro,它是基本的 android 应用程序开发组件之一。U 可以使用备用 EventBus,只需在 Google 上输入这两个内容,然后就可以了……
  • @DhirajChoudhary 如果您将此作为答案,我会接受。我已经制作了一个广播位置更新的服务原型,它可以根据需要工作。

标签: android service location


【解决方案1】:

您可以像这样创建一个 GPSTracker 类:

public class GPSTracker 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; // 1 second

    // Declaring a Location Manager
    protected LocationManager locationManager;

    public GPSTracker(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;
                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 latitude/longitude 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(GPSTracker.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/Wi-Fi enabled
     * @return boolean
     * */
    public boolean canGetLocation() {
        return this.canGetLocation;
    }


    /**
     * Function to show settings alert dialog.
     * On pressing the Settings button it will launch 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 the 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 the 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;
    }
}

并且在您想要获取用户纬度和经度的每个活动中,您都可以使用以下代码(例如在 MainActivity 中):

GPSTracker gps = new GPSTracker(MainActivity.this);
double longitude, latitude;
if (gps.canGetLocation()) {
   latitude = gps.getLatitude();
   longitude = gps.getLongitude();
}

【讨论】:

  • 用户会经常在两个活动之间来回切换 - 即从使用位置详细信息显示对象的列表视图到在地图上显示对象的地图视图......所以对我来说很有意义使用仅启动一次的单独服务?
  • GPSTracker gps = new GPSTracker(MainActivity.this); 错误。无法使用new 运算符启动服务。必须为此使用意图并调用startService()。因此,您的课程将无法用作服务。您也可以将其声明为public class GPSTracker implements LocationListener {
【解决方案2】:

创建一个接收位置更新的 Android 服务。

此服务还广播最新位置。

这 2 个活动注册接收这些广播。

【讨论】:

    【解决方案3】:

    我后来发现我也可以这样做:

    map.setMyLocationEnabled(true);
    

    使当前位置显示在地图上。

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 2014-07-23
      • 1970-01-01
      • 2018-08-16
      • 1970-01-01
      • 1970-01-01
      • 2016-02-03
      • 2015-12-18
      相关资源
      最近更新 更多