在服务范围内访问GPS?安卓/ Java的

时间:2012-09-23 07:40:25

标签: java android gps

我正在尝试运行后台服务,该服务将提取最新的GPS坐标,然后通过PHP脚本将它们发布到服务器。

我有这个工作,因为它将信息发布到服务器,它将在后台(作为服务)发布。

在下面的代码段中,它始终为false(location == null)。

我是Java编程的新手,我认为我没有正确地做到这一点。每当有GPS更新时我是否应该更新我正在更新的变量然后从我的后台服务中读取?

我是否应该将GPS功能与此Service类分开,并在需要数据时调用它?或者我应该使用AsyncTask?

很抱歉,如果问题是noobish,那么与PHP相比,Java相当复杂。

谢谢。

    Location location = locationManager.getLastKnownLocation(LocationManager.GPS_PROVIDER);

    String Long = null;
    String Lat = null;

    if (location != null) {
    Long =  String.format("%1$s",location.getLongitude());
    Lat = String.format("%1$s", location.getLatitude());
     } 
     else{
     Long = "error";
     Lat = "error";

     }

以下是完整的代码。

    public class UpdaterService extends Service {
      private static final String TAG = UpdaterService.class.getSimpleName();
      private Updater updater;

      private static final long MINIMUM_DISTANCE_CHANGE_FOR_UPDATES = 1; // in Meters
      private static final long MINIMUM_TIME_BETWEEN_UPDATES = 1000; // in Milliseconds
      protected LocationManager locationManager;

      @Override
      public IBinder onBind(Intent intent) {
        return null;
      }

      @Override
      public void onCreate() {
        super.onCreate();
        updater = new Updater();

        locationManager = (LocationManager) getSystemService(Context.LOCATION_SERVICE);
        locationManager.requestLocationUpdates(
                LocationManager.GPS_PROVIDER, 
                MINIMUM_TIME_BETWEEN_UPDATES, 
                MINIMUM_DISTANCE_CHANGE_FOR_UPDATES, 
                new MyLocationListener()
                );

        Log.d(TAG, "onCreate'd");

      }


        private class MyLocationListener implements LocationListener {

            public void onLocationChanged(Location location) {
            }

            public void onStatusChanged(String s, int i, Bundle b) {
            }

            public void onProviderDisabled(String s) {
            }

            public void onProviderEnabled(String s) {
            }

        }


    @Override
      public synchronized void onStart(Intent intent, int startId) {
          // Start the updater
        if (!updater.isRunning()) {
          updater.start();
        }

        Log.d(TAG, "onStart'd");
      }


      @Override
      public synchronized void onDestroy() {
        super.onDestroy();
        // Stop the updater
        if (updater.isRunning()) {
          updater.interrupt();
        }
        updater = null;
        Log.d(TAG, "onDestroy'd");
      }

      // ///// Updater Thread
      class Updater extends Thread {
        private static final long DELAY = 10000; // one minute
        private boolean isRunning = false;

        public Updater() {
          super("Updater");
        }

        @Override
        public void run() {
          isRunning = true;
          while (isRunning) {
            try {

              Log.d(TAG, "Updater run'ing");
              HttpClient httpclient = new DefaultHttpClient();
              HttpPost httppost = new HttpPost("http://www.mydomain.com/save.php");

              try {
                // Add your data
                  Log.d(TAG, "Working..");

                  Location location = locationManager.getLastKnownLocation(LocationManager.GPS_PROVIDER);

                 String Long = null;
                 String Lat = null;

                  if (location != null) {
                     Long =  String.format("%1$s",location.getLongitude());
                     Lat = String.format("%1$s", location.getLatitude());
                  } 
                  else{
                    Long = "error";
                    Lat = "error";

                  }


                 List<NameValuePair> nameValuePairs = new ArrayList<NameValuePair>(3);
                  nameValuePairs.add(new BasicNameValuePair("lid", "1"));
                  nameValuePairs.add(new BasicNameValuePair("lat",Lat));
                  nameValuePairs.add(new BasicNameValuePair("long", Long));
                  httppost.setEntity(new UrlEncodedFormEntity(nameValuePairs));

                  // Execute HTTP Post Request
                  HttpResponse response = httpclient.execute(httppost);


              } catch (ClientProtocolException e) {
                  // TODO Auto-generated catch block
              } catch (IOException e) {
                  // TODO Auto-generated catch block
              }


              // Sleep
              Thread.sleep(DELAY);
            } catch (InterruptedException e) {
              // Interrupted
              isRunning = false;
            }
          } // while
        }

        public boolean isRunning() {
          return this.isRunning;
        }

      }

    }

以下是主要活动:

    public class Main extends Activity {
              /** Called when the activity is first created. */
          @Override
          public void onCreate(Bundle savedInstanceState) {
            super.onCreate(savedInstanceState);
            setContentView(R.layout.activity_main);
          }

          @Override
          protected void onStop() {
            super.onStop();

          }

          // /////// Menu Stuff

          @Override
          public boolean onCreateOptionsMenu(Menu menu) {
            getMenuInflater().inflate(R.menu.activity_main, menu);
            return true;
          }

          @Override
          public boolean onOptionsItemSelected(MenuItem item) {

            switch (item.getItemId()) {
            case R.id.itemPrefs:
           //     startService(new Intent(this, UpdaterService.class));
             break;
            case R.id.itemServiceStart:
              startService(new Intent(this, UpdaterService.class));
              break;
            case R.id.itemServiceStop:
              stopService(new Intent(this, UpdaterService.class));
              break;
            }

            return true;
          }



        }

1 个答案:

答案 0 :(得分:0)

  

在下面的代码段中,它始终为false (location == null)

如果您在模拟器上运行代码,则需要手动将GPS数据提供给模拟器(从Eclipse中的DDMS角度)。

  

我是Java编程的新手,我认为我没有正确地做到这一点。每当有GPS更新时,我是否应该更新我正在更新的变量,然后从我的后台服务中读取它?

是的,你可以这样做。我之前做过类似的事情并且有效。

  

我是否应该将GPS功能与此Service类分开,并在需要数据时调用它?或者我应该使用AsyncTask?

都能跟得上!但是,如果你做了类似的事情,那将是一个好主意:

public class UpdaterService extends Service implements LocationListener{
}

至于noob-ish部分。毫无疑问是愚蠢的,我们都是新手,无论是一种还是另一种方式。 希望这会有所帮助。