3

Upon activity launch, the GPS is enabled and grabs the user latitude, longitude and report it to parse as a Geopoint. The issue is that the GPS continuously runs in the background and continuously report to Parse location. I would only want the GPS to grab the location information once and then stops immediately, as by myself I have notice that I have reached around 20k request with Parse on a day and I think its because it runs continuously in the background.

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've tried working with Single update instead, but it does not seem to be working.

Under 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

           }
          }
}
code_legend
  • 3,547
  • 15
  • 51
  • 95

3 Answers3

2

you have to find a way to removeupdates like

mlocManager.removeUpdates(mlocListener);

after you send your parse information

JRowan
  • 6,824
  • 8
  • 40
  • 59
  • Thanks for your response. I can work around that code. Would I add it under mlocManager.requestLocationUpdates(LocationManager.GPS_PROVIDER, 0, 0, mlocListener); under onCreate? – code_legend Sep 23 '14 at 04:42
  • 1
    no, what i would do is have my activity implement LocationListener and make the LocationManager public at class level then just do the work in the same class and put removeupdates in the onLocationChanged right after your parse work – JRowan Sep 23 '14 at 04:49
  • Hi, the one issue I notice with removeUpdates is that it only grabs the location once, which is somehow how I wanted it. I meant more that every time someone launches the application it would record its new location once, and lets say update the location once every 30 minute (because lets say the person never close the application and is on a road trip) as oppose to continuously. – code_legend Sep 23 '14 at 15:34
1

Besides what @JRowan said, You can also use:

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

If your location timing doesn't have to be exact, that is, if you can afford the location data to be somewhat old.

Method link

nem035
  • 34,790
  • 6
  • 87
  • 99
  • Thanks for your prompt response. Along with adding the suggested line Would I need to remove any lines? – code_legend Sep 23 '14 at 04:41
  • to use this code you don't really need to change anything. Instead of obtaining location in `onLocationReceived` you just use `myLocation` instead. For @JRowan's answer, you need to call `removeUpdates` after you are done receiving information and everything is stored safely. – nem035 Sep 23 '14 at 04:45
  • Hi, the one issue I notice with removeUpdates is that it only grabs the location once, which is somehow how I wanted it. I meant more that every time someone launches the application it would record its new location once, and lets say update the location once every 30 minute (because lets say the person never close the application and is on a road trip) as oppose to continuously. – code_legend Sep 23 '14 at 15:34
1

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

If you are interested in getting only one location update, you have two choices:

  1. Use LocationManager.requestSingleUpdate()
  2. Use LocationManager.requestLocationUpdates() but cancel the updates after receiving the first update.

I will go ahead with 2 since you already have some code.You need to first declare your variable mLocManager to be a class field rather than declare it locally in onCreate(). You then need to add the following code in 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 ...

        }

   }
stackoverflowuser2010
  • 38,621
  • 48
  • 169
  • 217
  • Thank you for your prompt response and clarification. Out of curiosity, how would the first option work? – code_legend Sep 23 '14 at 06:23
  • I've tried working with Single update instead, but it does not seem to be working. I have included what I have done under the update section of my initial post – code_legend Sep 23 '14 at 15:17
  • 1
    @user3907211: It's hard to say what the problem may be with requestSingleUpdate(). Is requestLocationUpdates() working for you? Are you sure you have GPS/WiFi connectivity? – stackoverflowuser2010 Sep 23 '14 at 18:01
  • Yes it has managed to work. I have two issues 1)It uses GPS abd U have quickly realized that its not the best solution since most devices GPS takes a while to load, and hence I am thinking of how I could grab the latitude and longitude information based on wi-fi or mobile data as oppose to GPS.On top of not having the application continuously search for the user location and report it to parse, I would want it to update the location once every 30 minute (because lets say the person never close the application and is on a road trip) as oppose to continuously – code_legend Sep 23 '14 at 21:32
  • 1
    @user3907211: You can get the geocoordinate from two providers at the same time (GPS and network). See this question: http://stackoverflow.com/questions/4595522/use-gps-and-network-provider-at-the-same-time-in-android – stackoverflowuser2010 Sep 24 '14 at 20:26
  • 1
    @user3907211: To get the location once every 30 minutes, there are two ways. (1) In the call to requestLocationUpdates(), you can set the `minTime` parameter. Note that it is in milliseconds. (2) You can use a separate OS timer call to schedule requestLocationUpdate 30 minutes from now. When the geocoordinate is found, you can cancel the requestLocationUpdate and then set another timer. See: http://stackoverflow.com/questions/3072173/how-to-call-a-method-after-a-delay-in-android – stackoverflowuser2010 Sep 24 '14 at 20:29
  • Thanks for your prompt responses, and for the link, and clarification: 1) Does your phone require mobile data to be able to use Network_Provider, or would the device wi-fi also works since it does not run on emulator with wi-fi enabled. mlocManager.requestLocationUpdates(LocationManager.NETWORK_PROVIDER, 0, 0, mlocListener); In the event that the person does not have wi-fi or mobile data, could I display a popup message instead of the unexpected error that is shown indicating that no network is found. – code_legend Sep 24 '14 at 21:59
  • 1
    @user3907211: From my understanding, network provider requires that there is Internet connectivity. This provider obtains cell tower and wi-fi base station signals, sends it to Google, and then gets back the geolocation. See: http://blog.shinetech.com/2011/10/14/a-good-look-at-android-location-data/ – stackoverflowuser2010 Sep 25 '14 at 06:00
  • 1
    @user3907211: If the user does have wi-fi enabled (which is different from having network connectivity), I usually display a Toast message saying "To improve location placement, please enable WiFi". Also see: http://stackoverflow.com/questions/3145089/what-is-the-simplest-and-most-robust-way-to-get-the-users-current-location-in-a – stackoverflowuser2010 Sep 25 '14 at 06:02
  • 1
    @user3907211: More good answers: http://stackoverflow.com/questions/21734907/why-does-having-wifi-on-but-not-connected-help-network-location-when-using-loca – stackoverflowuser2010 Sep 25 '14 at 06:05