3

我在设置 GPS 服务时遇到问题。我想检查 GPS 是否启用。如果它被禁用,它将显示一个对话框让用户打开它。问题是它不等待用户启用 GPS 并获取位置。

我有一堂课

public class GPSTracker extends Service implements LocationListener{

private final Context mContext;

boolean isGPSEnable = false;
boolean isNetworkEnable = false;
boolean canGetLocation = false;
Location location;
double latitude;
double longitude;

private static final long MIN_DISTANCE_FOR_UPDATE = 10;             // 10 meters
private static final long MIN_TIME_BW_UPDATE = 1000 * 60 * 1;       // 1 minute
protected LocationManager locationManager;

public GPSTracker(Context ctx) {
    this.mContext = ctx;
    getLocation();
}

public Location getLocation()
{
    try {
        locationManager = (LocationManager)mContext.getSystemService(LOCATION_SERVICE);
        isGPSEnable = locationManager.isProviderEnabled(LocationManager.GPS_PROVIDER);
        isNetworkEnable = locationManager.isProviderEnabled(LocationManager.NETWORK_PROVIDER);
        if(!isGPSEnable)
        {
            showSettingsGPSAlert();
        }
        else if(!isNetworkEnable)
        {
            showSettingsNetWorkAlert();
        }
        else
        {
            this.canGetLocation = true;
            if(isNetworkEnable)
            {
                locationManager.requestLocationUpdates(LocationManager.NETWORK_PROVIDER,
                        MIN_TIME_BW_UPDATE,
                        MIN_DISTANCE_FOR_UPDATE, this);
                Log.d("Network", "Network");
                if (locationManager != null) {
                    location = locationManager
                            .getLastKnownLocation(LocationManager.NETWORK_PROVIDER);
                    if (location != null) {
                        latitude = location.getLatitude();
                        longitude = location.getLongitude();
                    }
                }
            }
            if (isGPSEnable) {
                if (location == null) {
                    locationManager.requestLocationUpdates(
                            LocationManager.GPS_PROVIDER,
                            MIN_TIME_BW_UPDATE,
                            MIN_DISTANCE_FOR_UPDATE, 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 ex)
    {
        Log.e("<<Location Error>>",ex.getMessage());
    }
    return location;
}

public void stopUsingGPS(){
    if(locationManager != null){
        locationManager.removeUpdates(GPSTracker.this);
    }
}

public double getLatitude(){
    if(location != null){
        latitude = location.getLatitude();
    }

    // return latitude
    return latitude;
}

public double getLongitude(){
    if(location != null){
        longitude = location.getLongitude();
    }

    // return longitude
    return longitude;
}

public boolean canGetLocation() {
    return this.canGetLocation;
}

public boolean canGetGPS() {
    return this.isGPSEnable;
}

public boolean canGetNetwork() {
    return this.isNetworkEnable;
}

public void showSettingsGPSAlert(){
    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.startService(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();
}

public void showSettingsNetWorkAlert(){
    AlertDialog.Builder alertDialog = new AlertDialog.Builder(mContext);

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

    // Setting Dialog Message
    alertDialog.setMessage("NetWork 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_NETWORK_OPERATOR_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 IBinder onBind(Intent intent) {
    return null;  
}

@Override
public void onLocationChanged(Location location) {

}

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

}

@Override
public void onProviderEnabled(String provider) {

}

@Override
public void onProviderDisabled(String provider) {

}

}

我有课可以使用它

public class RestaurantListFragment extends ListFragment {

private ArrayList<Restaurant> restaurants;
private SQLDataHelper dataHelper;
private GPSTracker gps;
private double UserLatitude;
private double UserLongitude;
private ProgressDialog progressBar;

public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
    return inflater.inflate(R.layout.restaurant_list, null);

}

public void onActivityCreated(Bundle savedInstanceState) {
    super.onActivityCreated(savedInstanceState);


            gps = new GPSTracker(getActivity());
            UserLatitude = gps.getLatitude();
            UserLongitude = gps.getLongitude();

            Toast.makeText(getActivity(),UserLatitude + "|" + UserLongitude,Toast.LENGTH_SHORT).show();

            dataHelper = new SQLDataHelper(getActivity(), "restaurantDB");

            restaurants = new ArrayList<Restaurant>();
            dataHelper.openDB();
            Cursor cursor = dataHelper.query("Restaurant", new String[]{"Id", "ResName", "Logo", "Address", "Latitude", "Longitude"}, null
                    , null, null, null, null);
            if (cursor.moveToFirst()) {
                do {
                    Restaurant restaurant = new Restaurant();
                    restaurant.setId(cursor.getInt(0));
                    restaurant.setResName(cursor.getString(1));
                    restaurant.setLogo(cursor.getString(2));
                    restaurant.setAddress(cursor.getString(3));
                    restaurants.add(restaurant);
                } while (cursor.moveToNext());
            }
            //Collections.sort(restaurants);
            RestaurantAdapter restaurantAdapter = new RestaurantAdapter(getActivity(),restaurants);
            setListAdapter(restaurantAdapter);
}

}

启用 GPS 时它工作正常。我希望用户可以先打开它。之后它显示用户位置。然后它可以查询数据库和 setListAdapter 。感谢您的任何建议。

4

0 回答 0