无需GPS和移动网络即可获取当前位置(城市名称)

时间:2018-11-16 09:23:07

标签: dictionary networking gps location wifi

我有一个Android平板电脑,它没有SIM卡,也没有将GPS设置为保存电池模式。 平板电脑通过以太网(通过电缆)连接到Internet,并通过WIFI连接到LAN。 我写了一个代码来查找当前位置(城市名称),并且在手机中效果很好。 (我的手机的GPS处于活动状态,并通过wifi(调制解调器)或移动网络连接到了互联网。)

package com.xenon.location;
import android.app.Activity;
import android.app.Service;
import android.content.Context;
import android.content.DialogInterface;
import android.content.Intent;
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.Bundle;
import android.os.IBinder;
import android.provider.Settings;
import android.support.annotation.Nullable;
import android.support.v4.app.ActivityCompat;
import android.support.v4.content.ContextCompat;
import android.support.v7.app.AlertDialog;

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

import static android.content.Context.LOCATION_SERVICE;

public class GPSTracker extends Service implements LocationListener {

private final Context mContext;
private final Activity mActivity;

boolean isGPSEnabled = false;
boolean isNetworkEnabled = false;
boolean canGetLocation = false;

Location location;
double latitude;
double longitude;

private static final long MIN_DISTANCE_CHANGE_FOR_UPDATES = 10;

private static final long MIN_TIME_BW_UPDATES = 1000 * 60 * 1;

protected LocationManager locationManager;

public GPSTracker(Activity activity) {
    this.mContext = activity.getBaseContext();
    this.mActivity = activity;
    getLocation();
}

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

        isGPSEnabled = locationManager.isProviderEnabled(LocationManager.GPS_PROVIDER);
        isNetworkEnabled = locationManager.isProviderEnabled(LocationManager.NETWORK_PROVIDER);

        if (!isGPSEnabled && !isNetworkEnabled) {
          // no network provider is enabled
        }else{
            this.canGetLocation = true;
            if (isNetworkEnabled) {
                if (ContextCompat.checkSelfPermission(
                        mActivity, android.Manifest.permission.ACCESS_COARSE_LOCATION) != PackageManager.PERMISSION_GRANTED) {
                    ActivityCompat.requestPermissions(mActivity
                            , new String[]{android.Manifest.permission.ACCESS_COARSE_LOCATION}
                            , 0);
                }
                locationManager.requestLocationUpdates(
                        LocationManager.NETWORK_PROVIDER,
                        MIN_TIME_BW_UPDATES,
                        MIN_DISTANCE_CHANGE_FOR_UPDATES, this);
                if (locationManager != null) {
                    location = locationManager
                            .getLastKnownLocation(LocationManager.NETWORK_PROVIDER);
                    if (location != null) {
                        latitude = location.getLatitude();
                        longitude = location.getLongitude();
                    }
                }
            }
            if (isGPSEnabled) {
                if (location == null) {
                    locationManager.requestLocationUpdates(
                            LocationManager.GPS_PROVIDER,
                            MIN_TIME_BW_UPDATES,
                            MIN_DISTANCE_CHANGE_FOR_UPDATES, this);
                    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;
}

public void stopUsingGPS() {
    if (locationManager != null) {
        if (ContextCompat.checkSelfPermission(mActivity, android.Manifest.permission.ACCESS_COARSE_LOCATION) != PackageManager.PERMISSION_GRANTED) {

            ActivityCompat.requestPermissions(mActivity, new String[]{android.Manifest.permission.ACCESS_COARSE_LOCATION},
                    0);
            locationManager.removeUpdates(GPSTracker.this);
        }
    }
}

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

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

public String getCityName() {
    String result = "";
    if (location != null) {
        double latitude, longitude;
        List<Address> list;
        Locale locale = new Locale("tr");
        Geocoder geocoder = new Geocoder(mContext, locale);
        try {
            list = geocoder.getFromLocation(getLatitude(), getLongitude(), 2);

            Address address = list.get(0);

/*
            String gpsMsg = "CountryCode: " + address.getCountryCode() +
                    " ,AdminArea : " + address.getAdminArea() +
                    " ,CountryName : " + address.getCountryName() +
                    " ,SubLocality : " + address.getSubLocality();
*/
            result = address.getAdminArea();

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

        catch (Exception e){

        }
    }
    return result;
}

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

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

    alertDialog.setTitle("GPS is settings");

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

    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);
        }
    });

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

    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) {
}

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

在平板电脑上运行时:

boolean isNetworkEnabled = false;
boolean canGetLocation = false;
        locationManager = (LocationManager) mContext.getSystemService(LOCATION_SERVICE);

        isGPSEnabled = locationManager.isProviderEnabled(LocationManager.GPS_PROVIDER);
        isNetworkEnabled = locationManager.isProviderEnabled(LocationManager.NETWORK_PROVIDER);

isNetworkEnabled和canGetLocation始终返回false;

1 个答案:

答案 0 :(得分:0)

由于禁用了GPS,因此无法获取位置。 但是如果您想在没有GPS的情况下获取位置信息,请尝试获取设备连接位置的CELL信息(MNC MCC CELLID AND LAC),然后尝试使用USE API(unwiredlab.com)将该Cell INFO转换为位置。