GPS监听器永无止境

时间:2019-02-14 17:32:58

标签: java android

我的APP的GPS功能有问题。我已经把整个互联网都抛在脑后,找到了解决方案,但是没有什么可以解决问题的。

我们的团队开发了具有多种功能的应用程序,其中包括将位置信息保存在数据库中,从而实现了员工到客户的访问路线。

问题在于,完成巡回赛后,他应该关闭GPS侦听器,但是他并未关闭GPS侦听器并一直在使用,这会消耗电池电量。

有人会给出答案,甚至有其他替代方法来执行这种功能吗?

谢谢。

GPSTracker:

import android.app.AlertDialog;
import android.app.Service;
import android.content.Context;
import android.content.DialogInterface;
import android.content.Intent;
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.util.Log;

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 * 60 * 1; // 1 minute

    // 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;
                // First get location from Network Provider
//                if (isNetworkEnabled) {
//               //     locationManager.requestLocationUpdates(LocationManager.NETWORK_PROVIDER,MIN_TIME_BW_UPDATES,MIN_DISTANCE_CHANGE_FOR_UPDATES, this);
//                   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(GPSTracker.this);
            locationManager = null;
        }       
    }

    /**
     * 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;
    }

}

接收器

import android.app.Activity;
import android.app.AlarmManager;
import android.app.PendingIntent;
import android.content.BroadcastReceiver;
import android.content.Context;
import android.content.Intent;
import android.util.Log;
import java.util.Calendar;
import java.util.Date;
import br.com.infogen.projetec.cadastro.empresa.Empresa;
import br.com.infogen.projetec.cadastro.empresa.EmpresaDAO;
import br.com.infogen.projetec.cadastro.visitaTecnica.VisitaTecnica;
import br.com.infogen.projetec.cadastro.visitaTecnica.VisitaTecnicaDAO;
import br.com.infogen.projetec.gps.GPSTracker;

public class VisitaTecnicaGPSBroadcastReceiver extends BroadcastReceiver{

    VisitaTecnicaGPSDAO visitaTecnicaGPSDAO;
    VisitaTecnicaGPS visitaTecnicaGPS;
    VisitaTecnicaDAO visitaTecnicaDAO;
    VisitaTecnica visitaTecnica;
    Empresa empresa;
    EmpresaDAO empresaDAO;

    public static final int horaFinal = 20;
    private int conVisAbe;
    private Date dataInicial;

    double latitude;
    double longitude;

    GPSTracker gps;
    @Override
    public void onReceive(Context context, Intent intent) {
        empresaDAO          = new EmpresaDAO(context);
        visitaTecnicaGPSDAO = new VisitaTecnicaGPSDAO(context);
        visitaTecnicaGPS    = new VisitaTecnicaGPS();
        visitaTecnicaDAO    = new VisitaTecnicaDAO(context);

        empresa = empresaDAO.buscar(1);
        conVisAbe = empresa.getConVisAbe();

        Log.i("receiver", "testando receiver");
        gps = new GPSTracker(context);

        if (gps.canGetLocation()) {
            latitude = gps.getLatitude();
            longitude = gps.getLongitude();
        //  Toast.makeText(context, "Latitude: "+latitude+ "   e   Longitude"+longitude, Toast.LENGTH_SHORT).show();
            Log.i("Localização", "Latitude: "+latitude+ "   e   Longitude"+longitude);
        } else {
            gps.showSettingsAlert();
            Log.i("Localização", "Não encontrou");
        }

        visitaTecnica = visitaTecnicaDAO.buscarVisitasAbertas();
        if ((visitaTecnica instanceof VisitaTecnica)) {
            if (conVisAbe == 1) {
                    dataInicial = visitaTecnica.getDataEmissao();
                    Date dataAtual = new Date();
                    Date dataF1 = getDatePart(dataInicial);
                    Date dataF2 = getDatePart(dataAtual);

                    if (dataF1.before(dataF2)) {
                        gps.stopUsingGPS();
                        visitaTecnica.setConVisAbe(1);
                        dataF1.setHours(22);
                        dataF1.setMinutes(00);
                        dataF1.setSeconds(00);
                        visitaTecnica.setDataFinal(dataF1);
                        visitaTecnicaGPS.setData(dataF1);
                        visitaTecnicaDAO.salvarDoAlarme(visitaTecnica);

                        visitaTecnicaGPS.setVisitaTecnica(visitaTecnica);
                        visitaTecnicaGPS.setLatitude(String.valueOf(latitude));
                        visitaTecnicaGPS.setLongitude(String.valueOf(longitude));

                        try {
                            visitaTecnicaGPSDAO.salvar(visitaTecnicaGPS);
                            Log.i("testando banco", "localização salva com sucesso");

                            } catch (Exception e) {
                                Log.i("testando banco", "localização não foi salva");
                            }
                            cancelarAlarme(context);
                    } else {
                        visitaTecnicaGPS.setVisitaTecnica(visitaTecnica);
                        visitaTecnicaGPS.setLatitude(String.valueOf(latitude));
                        visitaTecnicaGPS.setLongitude(String.valueOf(longitude));
                        try {
                            visitaTecnicaGPSDAO.salvar(visitaTecnicaGPS);
                            Log.i("testando banco", "localização salva com sucesso");

                        } catch (Exception e) {
                            Log.i("testando banco", "localização não foi salva");
                        }
                    }

            } else {
                visitaTecnicaGPS.setVisitaTecnica(visitaTecnica);
                visitaTecnicaGPS.setLatitude(String.valueOf(latitude));
                visitaTecnicaGPS.setLongitude(String.valueOf(longitude));
                try {
                    visitaTecnicaGPSDAO.salvar(visitaTecnicaGPS);
                    Log.i("testando banco", "localização salva com sucesso");
                } catch (Exception e) {
                    Log.i("testando banco", "localização não foi salva");
                }
            }
        }

    }

    private void cancelarAlarme(Context context) {
        Log.i("alarme", "Alarme cancelado");
//      Intent it = new Intent("EXECUTAR_GPS");
        Intent it = new Intent(context, VisitaTecnicaGPSBroadcastReceiver.class);
        PendingIntent p = PendingIntent.getBroadcast(context,0, it, 0);
        AlarmManager alarme = (AlarmManager) context.getSystemService(Activity.ALARM_SERVICE);
        alarme.cancel(p);
    }

    private static Date getDatePart(Date data) {
        Calendar calendar = Calendar.getInstance();
        calendar.setTime(data);
        calendar.set(Calendar.HOUR_OF_DAY, 0);
        calendar.set(Calendar.MINUTE,      0);
        calendar.set(Calendar.SECOND,      0);
        calendar.set(calendar.MILLISECOND, 0);
        data = calendar.getTime();
        return data;
    }

}

0 个答案:

没有答案