【问题标题】:Working with GPS Location使用 GPS 定位
【发布时间】:2014-09-23 02:44:13
【问题描述】:

在活动启动时,GPS 启用并获取用户纬度、经度并将其报告为地理点解析。问题是 GPS 在后台持续运行并持续向 Parse 位置报告。我只希望 GPS 获取一次位置信息,然后立即停止,因为我自己注意到我在一天内使用 Parse 的请求达到了大约 20k,我认为这是因为它在后台连续运行。

以下是活动代码:

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

           }
          }
}

如果您需要任何说明,请告诉我。 提前致谢。

更新 我尝试过使用单一更新,但它似乎不起作用。

在 onCreate 下

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


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

    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

           }
          }
}

【问题讨论】:

    标签: java android android-activity gps parse-platform


    【解决方案1】:

    你必须找到一种方法来删除类似的更新

    mlocManager.removeUpdates(mlocListener);
    

    在您发送解析信息后

    【讨论】:

    • 感谢您的回复。我可以解决该代码。我会在 mlocManager.requestLocationUpdates(LocationManager.GPS_PROVIDER, 0, 0, mlocListener) 下添加它吗?在 onCreate 下?
    • 不,我要做的是让我的活动实现 LocationListener 并在类级别公开 LocationManager 然后只需在同一个类中完成工作并在解析工作后立即将 removeupdates 放入 onLocationChanged 跨度>
    • 嗨,我注意到 removeUpdates 的一个问题是它只抓取一次位置,这正是我想要的。我的意思是,每次有人启动应用程序时,它都会记录一次它的新位置,并且可以说每 30 分钟更新一次位置(因为可以说这个人从不关闭应用程序并且正在旅途中),而不是连续地。
    【解决方案2】:

    当您调用 LocationManager.requestLocationUpdates() 时,系统将通过该调用中给出的 LocationListener 不断提供位置更新。

    如果您只希望获得一次位置更新,您有两种选择:

    1. 使用 LocationManager.requestSingleUpdate()
    2. 使用 LocationManager.requestLocationUpdates() 但在收到第一个更新后取消更新。

    我将继续使用 2,因为您已经有了一些代码。您需要首先将变量 mLocManager 声明为类字段,而不是在 onCreate() 中本地声明它。然后,您需要在 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 ...
    
            }
    
       }
    

    【讨论】:

    • @user3907211:很难说 requestSingleUpdate() 可能存在什么问题。 requestLocationUpdates() 对您有用吗?你确定你有 GPS/WiFi 连接吗?
    • @user3907211:您可以同时从两个提供商(GPS 和网络)获取地理坐标。看到这个问题:stackoverflow.com/questions/4595522/…
    • @user3907211:每 30 分钟获取一次位置,有两种方法。 (1)在requestLocationUpdates()的调用中,可以设置minTime参数。请注意,它以毫秒为单位。 (2) 您可以使用单独的操作系统计时器调用来安排从现在起 30 分钟后的 requestLocationUpdate。找到地理坐标后,您可以取消 requestLocationUpdate,然后设置另一个计时器。见:stackoverflow.com/questions/3072173/…
    • @user3907211:据我了解,网络提供商要求有互联网连接。该提供商获取手机信号塔和 wi-fi 基站信号,将其发送给 Google,然后取回地理位置。见:blog.shinetech.com/2011/10/14/…
    • @user3907211:如果用户确实启用了 wi-fi(这与拥有网络连接不同),我通常会显示一条 Toast 消息,上面写着“要改进位置放置,请启用 WiFi”。另见:stackoverflow.com/questions/3145089/…
    【解决方案3】:

    除了@JRowan 说的,你还可以使用:

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

    如果您的位置时间不必精确,也就是说,如果您可以承受位置数据有些陈旧。

    Method link

    【讨论】:

    • 感谢您的及时回复。除了添加建议的行之外,我还需要删除任何行吗?
    • 要使用此代码,您实际上不需要更改任何内容。而不是在onLocationReceived 中获取位置,您只需使用myLocation 代替。对于@JRowan 的回答,您需要在收到信息并安全存储所有内容后致电removeUpdates
    • 嗨,我注意到 removeUpdates 的一个问题是它只抓取一次位置,这正是我想要的。我的意思是,每次有人启动应用程序时,它都会记录一次它的新位置,并且可以说每 30 分钟更新一次位置(因为可以说这个人从不关闭应用程序并且正在旅途中),而不是连续地。
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2013-04-27
    • 1970-01-01
    • 2012-11-05
    • 1970-01-01
    • 2017-11-28
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多