Android AsyncTask& LocationListener的 [英] Android AsyncTask & LocationListener

查看:196
本文介绍了Android AsyncTask& LocationListener的的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我创建了一个类 GPSController 。 onReceive被称为每分钟。

I created a class GPSController. The onReceive is called every Minute.

我想在 AsyncTask 中使用 GPSListener code>。
但是 onLocationChanged 方法永远不会被调用。 : - /

I want to get the current GPS Data with the GPSListener in my AsyncTask. But the onLocationChanged Method is never called. :-/

以下是我的课程:

Here is my Class:

public class GPSController extends SensorTimeController {

    // The minimum distance to change Updates in meters
    private static final long MIN_DISTANCE_CHANGE_FOR_UPDATES = 0;
    // The minimum time between updates in milliseconds
    private static final long MIN_TIME_BW_UPDATES = 2;
    private boolean isGPSEnabled = false;
    private boolean isNetworkEnabled = false;
    private double latitude = -1;
    private double longitude = -1;
    private double altitude = -1;
    private double speed = 0L;
    private double bearing = 0L;
    private LocationManager locationManager;
    private GPSLocationTask backgroundTask;

    public GPSController(GPSModule module) {
        super(module);
        backgroundTask = new GPSLocationTask();
    }

    private void SensorDataFinished(double longitude, double latitude, double altitude, double speed, double bearing) {
        Date date = new Date(System.currentTimeMillis());
        SensorRecord record = new SensorRecord(module.getNextIndex(), date, structure);
        if (longitude != -1)
            record.addData("longitude", String.valueOf(longitude));
        else
            record.addData("longitude", " ");

        if (latitude != -1)
            record.addData("latitude", String.valueOf(longitude));
        else
            record.addData("latitude", " ");

        if (altitude != -1)
            record.addData("altitude", String.valueOf(altitude));
        else
            record.addData("altitude", " ");

        if (bearing != 0L)
            record.addData("bearing", String.valueOf(bearing));
        else
            record.addData("bearing", " ");

        if (speed != 0L)
            record.addData("speed", String.valueOf(speed));
        else
            record.addData("speed", " ");

        module.log(record);

    }


    @Override
    public void onReceive(Context context, Intent intent) {
        locationManager = (LocationManager) context.getSystemService(Context.LOCATION_SERVICE);
        isGPSEnabled = locationManager.isProviderEnabled(LocationManager.GPS_PROVIDER);
        isNetworkEnabled = locationManager.isProviderEnabled(LocationManager.NETWORK_PROVIDER);
        backgroundTask.execute();
    }

    private class GPSLocationTask extends AsyncTask<Void, Void, Void> implements LocationListener {

        @Override
        protected Void doInBackground(Void... params) {
            System.out.println("THREAD STARTED");
            try {
                Looper.prepare();
                Looper.loop();
                if(isNetworkEnabled)
                    locationManager.requestLocationUpdates(LocationManager.NETWORK_PROVIDER, MIN_TIME_BW_UPDATES, MIN_DISTANCE_CHANGE_FOR_UPDATES, this);
                if(isGPSEnabled)
                    locationManager.requestLocationUpdates(LocationManager.GPS_PROVIDER, MIN_TIME_BW_UPDATES, MIN_DISTANCE_CHANGE_FOR_UPDATES, this);
            }catch(SecurityException e) {
                e.printStackTrace();
            }
            return null;
        }


        public void onLocationChanged(Location location) {
            if (location != null) {
                longitude = location.getLongitude();
                latitude = location.getLatitude();
                altitude = location.getAltitude();

                // don't do anything if we get a null reading for some reason
                if (longitude == 0.0f && latitude == 0.0f)
                    return;

                // any speed information?
                if (location.hasSpeed())
                    speed = (double) location.getSpeed();

                // any bearing information?
                if (location.hasBearing())
                    bearing = (double) location.getBearing();
                System.out.println(longitude+", "+ latitude+", "+ altitude+", "+ speed+", "+ bearing);
                SensorDataFinished(longitude, latitude, altitude, speed, bearing);
            }
        }

        public void onProviderDisabled(String provider) {

        }

        public void onProviderEnabled(String provider) {

        }

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

        }
    }
}


推荐答案

这个类提供当前经纬度,日志和In onLocationChanged您可以调用每个分钟调用的AsyncTask。

This class provide current lat , log and In onLocationChanged method you can call AsyncTask called every Minute.

public class GPSTracker extends Service implements LocationListener {

        private static final String TAG = GPSTracker.class.getSimpleName();
        private final Context mContext;

        // flag for GPS status
        boolean isGPSEnabled = false;

        // flag for network status
        boolean isNetworkEnabled = true;

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

                } else {
                    if (isGPSEnabled) {
                        if (location == null) {
                            locationManager.requestLocationUpdates(
                                    LocationManager.GPS_PROVIDER,
                                    MIN_TIME_BW_UPDATES,
                                    MIN_DISTANCE_CHANGE_FOR_UPDATES, this);
                            canGetLocation = true;
                            Log.d("GPS Enabled", "GPS Enabled");

                            if (locationManager != null) {
                                location = locationManager
                                        .getLastKnownLocation(LocationManager.GPS_PROVIDER);
                                if (location != null) {
                                    latitude = location.getLatitude();
                                    longitude = location.getLongitude();
    //                                SharedPreferenceUtil.putValue(Preferences.TAG_LATITUDE,""+latitude);
    //                                SharedPreferenceUtil.putValue(Preferences.TAG_LONGITUDE,""+longitude);
    //                                SharedPreferenceUtil.save();
    //                                Preferences.TAG_G_L = "G";
                                    Log.d("gps", latitude + "," + longitude);
                                }
                            }
                        } else {
                            canGetLocation = false;
                            Log.d("gps", "GPS Disable");
                        }
                    }
                }

                if (!isNetworkEnabled) {
                    // no network provider is enabled
                } else {
                    if (isNetworkEnabled) {
                        locationManager.requestLocationUpdates(
                                LocationManager.NETWORK_PROVIDER,
                                MIN_TIME_BW_UPDATES,
                                MIN_DISTANCE_CHANGE_FOR_UPDATES, this);
    //                    Preferences.TAG_G_L = "L";
                        Log.d("Network", "Network");
                        if (locationManager != null) {
                            location = locationManager
                                    .getLastKnownLocation(LocationManager.NETWORK_PROVIDER);
                            if (location != null) {
                                latitude = location.getLatitude();
                                longitude = location.getLongitude();
    //                            SharedPreferenceUtil.putValue(Preferences.TAG_LATITUDE,""+latitude);
    //                            SharedPreferenceUtil.putValue(Preferences.TAG_LONGITUDE,""+longitude);
    //                            SharedPreferenceUtil.save();
                                Log.d("network", latitude + "," + longitude);
                            }
                        }
                        Log.d("network", latitude + "," + longitude);
                    }
                }



               /* 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);
                        Log.d("Network", "Network");
                        if (locationManager != null) {
                            location = locationManager
                                    .getLastKnownLocation(LocationManager.NETWORK_PROVIDER);
                            if (location != null) {
                                latitude = location.getLatitude();
                                longitude = location.getLongitude();
                                SharedPreferenceUtil.putValue(Preferences.TAG_LATITUDE,""+latitude);
                                SharedPreferenceUtil.putValue(Preferences.TAG_LONGITUDE,""+longitude);
                                SharedPreferenceUtil.save();
                                Log.d("gps",latitude+","+longitude);
                            }
                        }
                    }
                    // 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();
                                    SharedPreferenceUtil.putValue(Preferences.TAG_LATITUDE,""+latitude);
                                    SharedPreferenceUtil.putValue(Preferences.TAG_LONGITUDE,""+longitude);
                                    SharedPreferenceUtil.save();
                                    Log.d("gps",latitude+","+longitude);
                                }
                            }
                        }
                    }
                }*/

            } 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
         *
         * @return double
         */
        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) {
            Log.e(TAG, "onLocationChanged: " + location.toString());
        }

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

    }

我希望这对您有所帮助。 。!

I hope it's help to you..!

这篇关于Android AsyncTask&amp; LocationListener的的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆