Working with GPS location

When the activity starts, the GPS is turned on and grabs the latitude, longitude of the user and reports it for parsing as a Geopoint. The problem is that the GPS is constantly running in the background and constantly reporting on Parse's location. I would like the GPS to only grab the location information once and then stop immediately as I myself have noticed that I have reached about 20k requests with Pars during the day and I think it is running constantly in the background mode.

Below is the activity code:

public class MoodActivity extends Activity {

    private FeedbackDialog feedBack;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_mood);
        feedBack = new FeedbackDialog(this, "");
         LocationManager mlocManager = (LocationManager)getSystemService(Context.LOCATION_SERVICE);
           LocationListener mlocListener = new MyLocationListener();

           mlocManager.requestLocationUpdates(LocationManager.GPS_PROVIDER, 0, 0, mlocListener);







        final TextView teating = (TextView) this.findViewById(R.id.tdinning);
        teating.setOnClickListener(new OnClickListener() {

            @Override
            public void onClick(View v) {
                MoodActivity.this.startActivity(new Intent(MoodActivity.this, CasualEventsActivity.class));
            }
        });

        final ImageView ieating = (ImageView) this.findViewById(R.id.idinning);
        ieating.setOnClickListener(new OnClickListener() {

            @Override
            public void onClick(View v) {
                MoodActivity.this.startActivity(new Intent(MoodActivity.this, CasualEventsActivity.class));
            }
        });

        final TextView tdrinks = (TextView) this.findViewById(R.id.tcasual);
        tdrinks.setOnClickListener(new OnClickListener() {

            @Override
            public void onClick(View v) {
                MoodActivity.this.startActivity(new Intent(MoodActivity.this, CasualEventsActivity.class));
            }
        });

        final ImageView idrinks = (ImageView) this.findViewById(R.id.icasual);
        idrinks.setOnClickListener(new OnClickListener() {

            @Override
            public void onClick(View v) {
                MoodActivity.this.startActivity(new Intent(MoodActivity.this, CasualEventsActivity.class));
            }
        });

        final TextView tshows = (TextView) this.findViewById(R.id.tshows);
        tshows.setOnClickListener(new OnClickListener() {

            @Override
            public void onClick(View v) {
                MoodActivity.this.startActivity(new Intent(MoodActivity.this, EntertainmentEventsActivity.class));
            }
        });

        final ImageView ishows = (ImageView) this.findViewById(R.id.ishows);
        ishows.setOnClickListener(new OnClickListener() {

            @Override
            public void onClick(View v) {
                MoodActivity.this.startActivity(new Intent(MoodActivity.this, EntertainmentEventsActivity.class));
            }
        });

        final TextView tarts = (TextView) this.findViewById(R.id.tculture);
        tarts.setOnClickListener(new OnClickListener() {

            @Override
            public void onClick(View v) {
                MoodActivity.this.startActivity(new Intent(MoodActivity.this, CultureEventsActivity.class));
            }
        });

        final ImageView iarts = (ImageView) this.findViewById(R.id.iculture);
        iarts.setOnClickListener(new OnClickListener() {

            @Override
            public void onClick(View v) {
                MoodActivity.this.startActivity(new Intent(MoodActivity.this, CultureEventsActivity.class));
            }
        });

        final Button viewall = (Button) this.findViewById(R.id.brandom);
        viewall.setOnClickListener(new OnClickListener() {

            @Override
            public void onClick(View v) {
                MoodActivity.this.startActivity(new Intent(MoodActivity.this, CasualEventsActivity.class));
            }
        });
    }



    @Override
    public boolean onCreateOptionsMenu(Menu menu) {

        // Inflate the menu; this adds items to the action bar if it is present.
        getMenuInflater().inflate(R.menu.main_activity_actions, menu);
        getActionBar().setDisplayShowTitleEnabled(false);



        return true;
    }

    @Override
    public boolean onOptionsItemSelected(MenuItem item) {
        // Handle presses on the action bar items
        switch (item.getItemId()) {
            case R.id.pageExperience:
                openPageExperience();
                return true;
            case R.id.pageMessaging:
                openPageMessage();
                return true;

            case R.id.pageEventsBooking:
                openPageBook();
                return true;

            case R.id.pageProfile:
                openPageProfile();
                return true;

            case R.id.pageReport:
                openPageReport();
                return true;

            case R.id.pageAbout:
                openPageAbout();
                return true;

            case R.id.pageLogout:
                openPageLogout();
                return true;

            default:
                return super.onOptionsItemSelected(item);
        }
    }

    private void openPageLogout() {
        // TODO Auto-generated method stub
        //Now call logout
        ParseUser.logOut();
        Intent intent = new Intent(getApplicationContext(), LoginActivity.class);
        startActivity(intent);
    }



    private void openPageAbout() {
        // TODO Auto-generated method stub

    }

    private void openPageReport() {
        // TODO Auto-generated method stub
        FeedbackSettings feedbackSettings = new FeedbackSettings();

        //SUBMIT-CANCEL BUTTONS
        feedbackSettings.setCancelButtonText("No");
        feedbackSettings.setSendButtonText("Send");

        //DIALOG TEXT
        feedbackSettings.setText("Hey, would you like to give us some feedback so that we can improve your experience?");
        feedbackSettings.setYourComments("Type your question here...");
        feedbackSettings.setTitle("Feedback Dialog Title");

        //TOAST MESSAGE
        feedbackSettings.setToast("Thank you so much!");
        feedbackSettings.setToastDuration(Toast.LENGTH_SHORT);  // Default
        feedbackSettings.setToastDuration(Toast.LENGTH_LONG);

        //RADIO BUTTONS
        feedbackSettings.setRadioButtons(false); // Disables radio buttons
        feedbackSettings.setBugLabel("Bug");
        feedbackSettings.setIdeaLabel("Idea");
        feedbackSettings.setQuestionLabel("Question");

        //RADIO BUTTONS ORIENTATION AND GRAVITY
        feedbackSettings.setOrientation(LinearLayout.HORIZONTAL); // Default
        feedbackSettings.setOrientation(LinearLayout.VERTICAL);
        feedbackSettings.setGravity(Gravity.RIGHT); // Default
        feedbackSettings.setGravity(Gravity.LEFT);
        feedbackSettings.setGravity(Gravity.CENTER);

        //SET DIALOG MODAL
        feedbackSettings.setModal(true); //Default is false

        //DEVELOPER REPLIES
        feedbackSettings.setReplyTitle("Message from the Developer");
        feedbackSettings.setReplyCloseButtonText("Close");
        feedbackSettings.setReplyRateButtonText("RATE!");

        //DEVELOPER CUSTOM MESSAGE (NOT SEEN BY THE END USER)
        feedbackSettings.setDeveloperMessage("This is a custom message that will only be seen by the developer!");
        feedBack.show();
    }

    private void openPageProfile() {
        // TODO Auto-generated method stub
        Intent intent = new Intent(this, profileDetailsActivity.class);
        startActivity(intent);

    }

    private void openPageBook() {
        // TODO Auto-generated method stub

    }

    private void openPageMessage() {
        // TODO Auto-generated method stub

    }

    private void openPageExperience() {
        // TODO Auto-generated method stub
        Intent intent = new Intent(this, MoodActivity.class);
        startActivity(intent);
    }

    public class MyLocationListener implements LocationListener {

        @Override
        public void onLocationChanged(Location loc) {
            // TODO Auto-generated method stub
            double lati = loc.getLatitude();
            double longi = loc.getLongitude();

            ParseUser currentUser = ParseUser.getCurrentUser();
            currentUser.saveInBackground();

            ParseGeoPoint point = new ParseGeoPoint(lati, longi);
            currentUser.put("location", point);

            currentUser.saveInBackground(new SaveCallback() {
                @Override
                public void done(ParseException e) {
                    setProgressBarIndeterminateVisibility(false);

                    if (e == null) {
                        // Success!

                    } else {

                    }
                }
            });

        }

           @Override
           public void onProviderDisabled(String provider) {
               // TODO Auto-generated method stub
               Toast.makeText(getApplicationContext(),"Gps Disabled",Toast.LENGTH_SHORT).show();

           }

           @Override
           public void onProviderEnabled(String provider) {
               // TODO Auto-generated method stub
               Toast.makeText(getApplicationContext(),"Gps Enabled",Toast.LENGTH_SHORT).show();


           }

           @Override
           public void onStatusChanged(String provider, int status, Bundle extras) {
               // TODO Auto-generated method stub

           }
          }
}

      

If you need any clarification, let me know. Thanks in advance.

Update  I tried to work with Single update instead, but it doesn't seem to work.

In onCreate

LocationManager mlocManager = (LocationManager)getSystemService(Context.LOCATION_SERVICE);
           LocationListener mlocListener = new MyLocationListener();


           mlocManager.requestSingleUpdate(LocationManager.GPS_PROVIDER, mlocListener, Looper.myLooper());

      

and

    public class MyLocationListener implements LocationListener {

        @Override
        public void onLocationChanged(Location loc) {
            // TODO Auto-generated method stub
            double lati = loc.getLatitude();
            double longi = loc.getLongitude();

            ParseUser currentUser = ParseUser.getCurrentUser();
            currentUser.saveInBackground();

            ParseGeoPoint point = new ParseGeoPoint(lati, longi);
            currentUser.put("location", point);

            currentUser.saveInBackground(new SaveCallback() {
                @Override
                public void done(ParseException e) {
                    setProgressBarIndeterminateVisibility(false);

                    if (e == null) {
                        // Success!

                    } else {

                    }
                }
            });

        }

           @Override
           public void onProviderDisabled(String provider) {
               // TODO Auto-generated method stub
               Toast.makeText(getApplicationContext(),"Gps Disabled",Toast.LENGTH_SHORT).show();

           }

           @Override
           public void onProviderEnabled(String provider) {
               // TODO Auto-generated method stub
               Toast.makeText(getApplicationContext(),"Gps Enabled",Toast.LENGTH_SHORT).show();


           }

           @Override
           public void onStatusChanged(String provider, int status, Bundle extras) {
               // TODO Auto-generated method stub

           }
          }
}

      

+3


source to share


3 answers


When you call LocationManager.requestLocationUpdates (), the system will continually provide location updates through the LocationListener specified in that call.

If you are interested in receiving only one location update, you have two options:

  • Use LocationManager.requestSingleUpdate ()
  • Use LocationManager.requestLocationUpdates (), but discard updates after getting the first update.


I'll continue with 2 since you already have the code. You need to first declare the variable mLocManager

as a class field and not declare it locally in onCreate (). Then you need to add the following code to your LocationListener.

    public class MyLocationListener implements LocationListener {

        @Override
        public void onLocationChanged(Location loc) {

            double lati = loc.getLatitude();
            double longi = loc.getLongitude();

            mlocManager.remoteUpdates(this); // ADD THIS STATEMENT

            // The rest of your code goes here ...

        }

   }

      

+1


source


you need to find a way to remove updates like

mlocManager.removeUpdates(mlocListener);

      



after sending parsing information

+2


source


Besides what @JRowan said, you can also use:

String provider = LocationManager.getBestProvider(new Criteria(), true);
Location myLocation = LocationManager.getLastKnowLocation(provider);

      

If the time of your location doesn't have to be accurate, that is, if you can let the location data be somewhat old.

Method reference

+1


source







All Articles