0

我必须每半小时打开一次 gps 并获取位置并将其关闭是否有此功能的代码,因为我是 android 新手,请帮助我。

谢谢你。

这是我的代码:

public void checkLocation(View v) {
        //initialize location manager
        manager =  (LocationManager) getSystemService(Context.LOCATION_SERVICE);
        //check if GPS is enabled
        //if not, notify user with a toast
        if (!manager.isProviderEnabled(LocationManager.GPS_PROVIDER)) {
            Toast.makeText(this, "GPS is disabled.", Toast.LENGTH_SHORT).show();
        } else {
            //get a location provider from location manager
            //empty criteria searches through all providers and returns the best one
            String providerName = manager.getBestProvider(new Criteria(), true);
            Location location = manager.getLastKnownLocation(providerName);

            TextView tv = (TextView)findViewById(R.id.locationResults);
            if (location != null) {
                tv.setText(location.getLatitude() + " latitude, " + location.getLongitude() + " longitude");
            } else {
                tv.setText("Last known location not found. Waiting for updated location...");
            }
            //sign up to be notified of location updates every 15 seconds - for production code this should be at least a minute
            manager.requestLocationUpdates(providerName, 60000*3, 1, this);
        }
    }
4

4 回答 4

0

这次我没有编码,但我会建议你使用系统闹钟并保持半小时的时间间隔。android 闹钟通常用于我们必须在每个间隔后做一些工作的地方,这样电池也不会受到影响。

于 2013-04-19T10:06:51.423 回答
0

您应该使用requestLocationUpdates方法,该方法采用您可以响应的PendindIntent 。

于 2013-04-19T10:26:53.293 回答
0

我会用一个可运行的函数来实现它。这是一个很好的例子

你应该设置handler.postDelayed(r, 5400000);(如果我计算正确)。该值以毫秒为单位。

于 2013-04-19T10:04:13.860 回答
-1
thread1=new Thread(new Runnable() {

        public void run() {
            // TODO Auto-generated method stub
            while (true) {
                try {
                    Thread.sleep(1000*60*30);
                    mHandler.post(new Runnable() {


                        public void run() {
                            // TODO Auto-generated method stub
                            // Write your code here to get the gps location.
                   });
                } catch (Exception e) {
                    // TODO: handle exception
                }
            }
        }
    });
于 2013-04-19T10:09:54.237 回答