简体   繁体   English

使用GPS位置

[英]Working with GPS Location

Upon activity launch, the GPS is enabled and grabs the user latitude, longitude and report it to parse as a Geopoint. 在活动启动时,GPS启用并抓取用户的纬度,经度并报告它作为Geopoint进行解析。 The issue is that the GPS continuously runs in the background and continuously report to Parse location. 问题是GPS连续在后台运行并不断向Parse位置报告。 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. 我只希望GPS一次获取位置信息然后立即停止,因为我自己已经注意到我已经在一天内达到了大约20k的Parse请求并且我认为它因为它在后台持续运行。

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 在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

           }
          }
}

you have to find a way to removeupdates like 你必须找到一种方法来删除更新

mlocManager.removeUpdates(mlocListener);

after you send your parse information 发送您的解析信息后

Besides what @JRowan said, You can also use: 除了@JRowan所说的,你还可以使用:

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 方法链接

When you call LocationManager.requestLocationUpdates(), the system will continuously provide location updates through the LocationListener given in that call. 当您调用LocationManager.requestLocationUpdates()时,系统将通过该调用中给出的LocationListener继续提供位置更新。

If you are interested in getting only one location update, you have two choices: 如果您只想获得一个位置更新,则有两种选择:

  1. Use LocationManager.requestSingleUpdate() 使用LocationManager.requestSingleUpdate()
  2. Use LocationManager.requestLocationUpdates() but cancel the updates after receiving the first update. 使用LocationManager.requestLocationUpdates()但在收到第一次更新后取消更新。

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(). 我将继续使用2,因为你已经有了一些代码。你需要首先声明你的变量mLocManager是一个类字段,而不是在onCreate()中本地声明它。 You then need to add the following code in your LocationListener. 然后,您需要在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 ...

        }

   }

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM