在Activity之外创建GPS的问题

时间:2016-01-12 17:04:26

标签: android gps

我是Android的初学者,由于所有示例都在新的API 23之前,我在活动之外创建GPS时遇到问题,由于需要询问权限,任何人都可以给出提示我在主要活动中创建GPS时没有遇到任何问题,因为我不知道如何绕过主要的checkSelfPermission(),因为如果我在调用requestLocationUpdate时没有测试它( )在main之外它给了我一个错误(我需要在两个文件中使用checkselfPermission(),否则它在GPStracker.java中给我一个错误),我怎么能在没有测试的情况下每次调用requestLocationUpdate()..... 我很怀疑是在这个测试中我真的必须这样做所以我可以使用requestLocationUpdate(),有一种方法只做一次吗? mContext.checkSelfPermission(Manifest.permission.ACCESS_FINE_LOCATION)== PackageManager.PERMISSION_GRANTED 这是我的代码:

GPSTracker.java

public class GpsTracker extends Service implements LocationListener {
// 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

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 locationGpS; // locationGPS
Location locationWIFI; // locationWifi
Location location;
double latitudeWifi,latitudeGps,latitude; // latitude
double longitudeWifi,longitudeGps,longitude; // longitude
double altitudeWifi,altitudeGps,altitude; //altitude
float accuracywifi,accuracyGps;

// Declaring a Location Manager
protected LocationManager locationManager;

    /*
     *Constructor
     */
    public GpsTracker(Context context) {
        this.mContext = context;
        getOptLocation();
    }

    /*
     * GET Best Location
     */
    public Location getOptLocation()
    {
        if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.M) {
                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) {
                        //Error message conncting to any type of Provider
                        Log.d("Conexão", "service not available ");
                    } else {
                        this.canGetLocation = true;
                        // First get location from Network Provider


                        //Get wifi and 3g location

 /*if i don't make the second part of this test(after &&) inside the 
 if the next line*/     

    if (isNetworkEnabled && mContext.checkSelfPermission(Manifest.permission.ACCESS_COARSE_LOCATION) == PackageManager.PERMISSION_GRANTED ) {

/*this line in the compiler wont work because it 
 says the request permissions hasn't been asked*/   

locationManager.requestLocationUpdates(
LocationManager.NETWORK_PROVIDER,   MIN_TIME_BW_UPDATES,       MIN_DISTANCE_CHANGE_FOR_UPDATES, this);
                            Log.d("Conexão", "Network");
                            if (locationManager != null) {
                                locationWIFI = locationManager.getLastKnownLocation(LocationManager.NETWORK_PROVIDER);
                                if (locationWIFI != null) {
                                    latitudeWifi = locationWIFI.getLatitude();
                                    longitudeWifi = locationWIFI.getLongitude();
                                    altitudeWifi = locationWIFI.getAltitude();
                                    accuracywifi = locationWIFI.getAccuracy();
                                    Log.d("Conexão", " Conn Network " + latitudeWifi + "," + longitudeWifi + "," + altitudeWifi + "," + accuracywifi + " ");
                                }
                            }
                        }

                        // if GPS Enabled get lat/long using GPS Services
                        if (isGPSEnabled && mContext.checkSelfPermission(Manifest.permission.ACCESS_FINE_LOCATION) == PackageManager.PERMISSION_GRANTED) {
                            if (locationGpS == null) {
                                locationManager.requestLocationUpdates(LocationManager.GPS_PROVIDER, MIN_TIME_BW_UPDATES, MIN_DISTANCE_CHANGE_FOR_UPDATES, this);
                                Log.d("Conexão", "GPS Enabled");
                                if (locationManager != null) {
                                    locationGpS = locationManager
                                            .getLastKnownLocation(LocationManager.GPS_PROVIDER);
                                    if (locationGpS != null) {
                                        latitudeGps = locationGpS.getLatitude();
                                        longitudeGps = locationGpS.getLongitude();
                                        altitudeGps = locationGpS.getAltitude();
                                        accuracyGps = locationGpS.getAccuracy();
                                        Log.d("GPS", " conn GPS" + latitudeGps + "," + longitudeGps + "," + altitudeGps + "," + accuracyGps + " ");
                                    }
                                }

                            }
                        }
                        Log.d("NET Antes", "Before Net: " + latitudeWifi + "," + longitudeWifi + "," + altitudeWifi + "," + accuracywifi + " ");
                        Log.d("Gps Antes", "before GPs: " + latitudeGps + "," + longitudeGps + "," + altitudeGps + "," + accuracyGps + " ");
                        location = getBestlocation(locationGpS, locationWIFI);
                        Log.d("Location", "FinalLocation: " + latitude + "," + longitude + "," + altitude + " ");


                        // locationManager.removeUpdates(GpsTracker.this);

                    }
                } catch (Exception e) {
                    e.printStackTrace();
                    Log.d("Erro ", e.getMessage());
                }
            }
        }
            return location;//getBestlocation(locationGpS, locationWIFI);
        }

    private Location getBestlocation(Location locationGpS, Location locationWIFI) {

        Log.d("GetBest","Best provider");
        if(locationWIFI.getAccuracy()>locationGpS.getAccuracy()) {
            Log.d("GetBest", "wifi ");
            return locationWIFI;


        }
        else{
            Log.d("GetBest", " GPS ");

            return locationGpS;
        }
    }

    /**
     * Function to get latitude
     * @return double
     * */
    public double getLatitude(){
        Log.d("GetLatitude", "Latitude");
        if(location != null){
            latitude = locationWIFI.getLatitude();
        }
        else{
            Log.d("GetLatitude", "Erro");
        }
        return latitude;
    }
    /**
     * Function to get longitude
     * @return double
     * */
    public double getLongitude(){
        Log.d("GetLongitude", "Longitude ");
        if(location != null){
            longitude = location.getLongitude();
        }
        else{
            Log.d("GetLatitude", "Erro");
        }
        return longitude;
    }
    /**
     * Function to get altitude
     * @return double
     * */
    public double getAltitude(){
        Log.d("GetAltitude", "Altitude");
        if(location != null){
            longitude = location.getAltitude();
        }
        else{
            Log.d("GetLatitude", "Erro");
        }
        return longitude;
    }

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

        return this.canGetLocation;
    }

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

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

}

GPS(活性)

public class MainActivity extends AppCompatActivity {
    public Button cord;
    public TextView lg;
    public TextView lat;
    public TextView alt;
    GpsTracker gps;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);
        cord = (Button) findViewById(R.id.bCoordenadas);
        lg = (TextView) findViewById(R.id.tvLong);
        lat = (TextView) findViewById(R.id.tvLat);
        alt = (TextView) findViewById(R.id.tvAlt);
        if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.M) {
            if (ActivityCompat.checkSelfPermission(this, Manifest.permission.ACCESS_FINE_LOCATION) != PackageManager.PERMISSION_GRANTED
                    && ActivityCompat.checkSelfPermission(this, Manifest.permission.ACCESS_COARSE_LOCATION) != PackageManager.PERMISSION_GRANTED) {
                try {

                    requestPermissions(new String[]{Manifest.permission.ACCESS_COARSE_LOCATION,
                            Manifest.permission.ACCESS_FINE_LOCATION,
                            Manifest.permission.INTERNET}, 1000);
                    Log.d("Request","Passa o Request Permission");
                } catch (SecurityException e) {
                    e.printStackTrace();
                    Log.e("TAG", "Falha nas Permissões");
                }
            }
        } else {
            Toast.makeText(this, "Entra no request Permissions", Toast.LENGTH_LONG).show();
            executaGps();
        }
    }

    @Override
    public void onRequestPermissionsResult(int requestCode, String[] permissions, int[] grantResults) {
        switch (requestCode) {
            case 1000:
                if (grantResults.length > 0 && grantResults[0] == PackageManager.PERMISSION_GRANTED) {
                    for (int i = 0; i < permissions.length; i++) {
                        if (grantResults[i] == PackageManager.PERMISSION_GRANTED) {
                            Log.d("Permissions", "Permission Granted: " + permissions[i]);
                        } else if (grantResults[i] == PackageManager.PERMISSION_DENIED) {
                            Log.d("Permissions", "Permission Denied: " + permissions[i]);
                        }
                        Toast.makeText(this, "Entra no on request Permissions", Toast.LENGTH_LONG).show();

                        executaGps();
                    }
                }
        }
    }

    public void executaGps() {
        try {

            if (gps.canGetLocation()) {

                cord.setOnClickListener(new View.OnClickListener() {

                    @Override
                    public void onClick(View arg0) {

                        // create class object
                        Log.d("Click", "Entra no botao");

                        gps = new GpsTracker(MainActivity.this);
                        double latitude = gps.getLatitude();
                        double longitude = gps.getLongitude();
                        double altitude = gps.getAltitude();
                        lg.append(" " + longitude + " ");
                        lat.append(" " + latitude + " ");
                        alt.append(" " + altitude + " ");


                    }
                });
            }
        }catch(Exception e)
        {
            e.printStackTrace();
            Log.e("TAG", e.getMessage());
            Log.d("Erro ", "try-catch");
        }
    }
}

任何人都可以给我一个提示,我可以做些什么来绕过主要活动和GpsTracker.java中权限的双重检查?要测试这个,只需创建一个3文本视图和一个按钮,并在Android Manifest.xml中添加使用权限 谢谢

0 个答案:

没有答案