How To Get Location Using AsyncTask

前端 未结 4 481
栀梦
栀梦 2020-12-05 09:08

I am pulling my hair out with trying to find a good solution to this problem. I made my app so it finds my location. It seems overly complicated but easy enough. However fol

相关标签:
4条回答
  • 2020-12-05 09:28
    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
                Log.w("DOCOMO-2","Network Connection failed");
            } 
            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);
                    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);
                        if (locationManager != null) 
                        {
                            location = locationManager
                                    .getLastKnownLocation(LocationManager.GPS_PROVIDER);
                            if (location != null) 
                            {
                                latitude = location.getLatitude();
                                longitude = location.getLongitude();
                            }
    
                        }
                    }
                }
            }
            locationManager=null;
            location=null;
    
        } 
        catch (Exception e) 
        {
            locationManager=null;
            location=null;
            e.printStackTrace();
        }
        return location;
    }
    
    0 讨论(0)
  • 2020-12-05 09:30

    Just add Looper.prepare() before calling locationManager.requestLocationUpdates(locationManager.GPS_PROVIDER, 0, 0, locationListener); Remember to call Looper.loop() after.

    0 讨论(0)
  • 2020-12-05 09:36

    First to fix your compilation problem, move

    LocationManager locationManager = (LocationManager)params[0].getSystemService(Context.LOCATION_SERVICE);        
    

    So that it's a private member variable of the class.

    LocationManager does not have to be in an AsyncTask. It does not tie up the UI, all updates are already asynchronous. This will just add needless complication to your project.

    You probably only need to move useLocation into onLockationChanged.

    0 讨论(0)
  • 2020-12-05 09:37
    public class FastMainActivity extends Activity {
    
        Button searchBtn = null;
        Intent locatorService = null;
        AlertDialog alertDialog = null;
    
        /** Called when the activity is first created. */
        @Override
        public void onCreate(Bundle savedInstanceState) {
            super.onCreate(savedInstanceState);
            setContentView(R.layout.main);
            searchBtn = (Button) findViewById(R.id.searchBtn);
    
            searchBtn.setOnClickListener(new OnClickListener() {
    
                @Override
                public void onClick(View v) {
                    // TODO Auto-generated method stub
    
                    if (!startService()) {
                        CreateAlert("Error!", "Service Cannot be started");
                    } else {
                        Toast.makeText(FastMainActivity.this, "Service Started",
                                Toast.LENGTH_LONG).show();
                    }
    
                }
            });
    
        }
    
        public boolean stopService() {
            if (this.locatorService != null) {
                this.locatorService = null;
            }
            return true;
        }
    
        public boolean startService() {
            try {
                // this.locatorService= new
                // Intent(FastMainActivity.this,LocatorService.class);
                // startService(this.locatorService);
    
                FetchCordinates fetchCordinates = new FetchCordinates();
                fetchCordinates.execute();
                return true;
            } catch (Exception error) {
                return false;
            }
    
        }
    
        public AlertDialog CreateAlert(String title, String message) {
            AlertDialog alert = new AlertDialog.Builder(this).create();
    
            alert.setTitle(title);
    
            alert.setMessage(message);
    
            return alert;
    
        }
    
        public class FetchCordinates extends AsyncTask<String, Integer, String> {
            ProgressDialog progDailog = null;
    
            public double lati = 0.0;
            public double longi = 0.0;
    
            public LocationManager mLocationManager;
            public VeggsterLocationListener mVeggsterLocationListener;
    
            @Override
            protected void onPreExecute() {
                mVeggsterLocationListener = new VeggsterLocationListener();
                mLocationManager = (LocationManager) getSystemService(Context.LOCATION_SERVICE);
    
                mLocationManager.requestLocationUpdates(
                        LocationManager.NETWORK_PROVIDER, 0, 0,
                        mVeggsterLocationListener);
    
                progDailog = new ProgressDialog(FastMainActivity.this);
                progDailog.setOnCancelListener(new OnCancelListener() {
                    @Override
                    public void onCancel(DialogInterface dialog) {
                        FetchCordinates.this.cancel(true);
                    }
                });
                progDailog.setMessage("Loading...");
                progDailog.setIndeterminate(true);
                progDailog.setCancelable(true);
                progDailog.show();
    
            }
    
            @Override
            protected void onCancelled(){
                System.out.println("Cancelled by user!");
                progDialog.dismiss();
                mLocationManager.removeUpdates(mVeggsterLocationListener);
            }
    
            @Override
            protected void onPostExecute(String result) {
                progDailog.dismiss();
    
                Toast.makeText(FastMainActivity.this,
                        "LATITUDE :" + lati + " LONGITUDE :" + longi,
                        Toast.LENGTH_LONG).show();
            }
    
            @Override
            protected String doInBackground(String... params) {
                // TODO Auto-generated method stub
    
                while (this.lati == 0.0) {
    
                }
                return null;
            }
    
            public class VeggsterLocationListener implements LocationListener {
    
                @Override
                public void onLocationChanged(Location location) {
    
                    int lat = (int) location.getLatitude(); // * 1E6);
                    int log = (int) location.getLongitude(); // * 1E6);
                    int acc = (int) (location.getAccuracy());
    
                    String info = location.getProvider();
                    try {
    
                        // LocatorService.myLatitude=location.getLatitude();
    
                        // LocatorService.myLongitude=location.getLongitude();
    
                        lati = location.getLatitude();
                        longi = location.getLongitude();
    
                    } catch (Exception e) {
                        // progDailog.dismiss();
                        // Toast.makeText(getApplicationContext(),"Unable to get Location"
                        // , Toast.LENGTH_LONG).show();
                    }
    
                }
    
                @Override
                public void onProviderDisabled(String provider) {
                    Log.i("OnProviderDisabled", "OnProviderDisabled");
                }
    
                @Override
                public void onProviderEnabled(String provider) {
                    Log.i("onProviderEnabled", "onProviderEnabled");
                }
    
                @Override
                public void onStatusChanged(String provider, int status,
                        Bundle extras) {
                    Log.i("onStatusChanged", "onStatusChanged");
    
                }
    
            }
    
        }
    
    }
    
    0 讨论(0)
提交回复
热议问题