Android GPS无法在MyService中运行

时间:2014-04-26 08:14:35

标签: java android gps

祝你有个美好的一天,2天我无法解决问题。

采取的应用程序非常相似 http://www.androidhive.info/2012/07/android-gps-location-manager-tutorial/

一切正常,我得到GPS坐标。 然后进程将获取坐标+将它们发送到服务器以移动到后台服务并且出现问题,来坐标0.0 0.0

MainActivity.java(全部工作)

    public class MainActivity extends Activity {

    Button btnShowLocation;

    // GPSTracker class
    GPSTracker gps;

    final String LOG_TAG = "myLogs";

    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);

        btnShowLocation = (Button) findViewById(R.id.button1);

        // show location button click event
        btnShowLocation.setOnClickListener(new View.OnClickListener() {

            @Override
            public void onClick(View arg0) {       
                // create class object
                gps = new GPSTracker(MainActivity.this);

                // check if GPS enabled    
                if(gps.canGetLocation()){

                    double latitude = gps.getLatitude();
                    double longitude = gps.getLongitude();

                    // \n is for new line
                    Toast.makeText(getApplicationContext(), "Your Location is - \nLat: " + latitude + "\nLong: " + longitude, Toast.LENGTH_LONG).show();
                    //                                               #/mygps.php?lat=33.995834&lon=22.93707&timestamp=1375235923365&hdop=16.0&altitude=107.65327&speed=0.0
                    new RequestTask().execute("http://map.domain.ru/mygps.php?lat="+latitude+"&lon="+longitude+"&timestamp=1375235923365&hdop=16.0&altitude=107.65327&speed=0.0");
                }else{
                    // can't get location
                    // GPS or Network is not enabled
                    // Ask user to enable GPS/network in settings
                    gps.showSettingsAlert();

                }

            }
        });


    }
    public void onClickStart(View v) {
         startService(new Intent(this, MyService.class));
        }

      public void onClickStop(View v) {
          stopService(new Intent(this, MyService.class));
        }

}

class RequestTask extends AsyncTask<String, String, String>{

    @Override
    protected String doInBackground(String... uri) {
        HttpClient httpclient = new DefaultHttpClient();
        HttpResponse response;
        String responseString = null;
        try {
            response = httpclient.execute(new HttpGet(uri[0]));
            StatusLine statusLine = response.getStatusLine();
            if(statusLine.getStatusCode() == HttpStatus.SC_OK){
                ByteArrayOutputStream out = new ByteArrayOutputStream();
                response.getEntity().writeTo(out);
                out.close();
                responseString = out.toString();
            } else{
                //Closes the connection.
                response.getEntity().getContent().close();
                throw new IOException(statusLine.getReasonPhrase());
            }
        } catch (ClientProtocolException e) {
            //TODO Handle problems..
        } catch (IOException e) {
            //TODO Handle problems..
        }
        return responseString;
    }

    @Override
    protected void onPostExecute(String result) {
        super.onPostExecute(result);
        //Do anything with response..
    }
}

GPSTracker.java

public class GPSTracker extends Service implements LocationListener {

    private final Context mContext;

    // flag for GPS status
    boolean isGPSEnabled = false;

    // flag for network status
    boolean isNetworkEnabled = false;

    // flag for GPS status
    boolean canGetLocation = false;

    Location location; // location
    double latitude; // latitude
    double longitude; // longitude

    // The minimum distance to change Updates in meters
    private static final long MIN_DISTANCE_CHANGE_FOR_UPDATES = 10; // 10 meters

    // The minimum time between updates in milliseconds
    private static final long MIN_TIME_BW_UPDATES = 1000 * 60 * 1; // 1 minute

    // Declaring a Location Manager
    protected LocationManager locationManager;

    public GPSTracker(Context context) {
        this.mContext = context;
        getLocation();
    }

    public Location getLocation() {
        try {
            locationManager = (LocationManager) mContext
                    .getSystemService(LOCATION_SERVICE);

            // getting GPS status
            isGPSEnabled = locationManager
                    .isProviderEnabled(LocationManager.GPS_PROVIDER);

            // getting network status
            isNetworkEnabled = locationManager
                    .isProviderEnabled(LocationManager.NETWORK_PROVIDER);

            if (!isGPSEnabled && !isNetworkEnabled) {
                // no network provider is enabled
            } else {
                this.canGetLocation = true;
                // First get location from Network Provider
                if (isNetworkEnabled) {
                    locationManager.requestLocationUpdates(
                            LocationManager.NETWORK_PROVIDER,
                            MIN_TIME_BW_UPDATES,
                            MIN_DISTANCE_CHANGE_FOR_UPDATES, this);
                    Log.d("Network", "Network");
                    if (locationManager != null) {
                        location = locationManager
                                .getLastKnownLocation(LocationManager.NETWORK_PROVIDER);
                        if (location != null) {
                            latitude = location.getLatitude();
                            longitude = location.getLongitude();
                        }
                    }
                }
                // if GPS Enabled get lat/long using GPS Services
                if (isGPSEnabled) {
                    if (location == null) {
                        locationManager.requestLocationUpdates(
                                LocationManager.GPS_PROVIDER,
                                MIN_TIME_BW_UPDATES,
                                MIN_DISTANCE_CHANGE_FOR_UPDATES, this);
                        Log.d("GPS Enabled", "GPS Enabled");
                        if (locationManager != null) {
                            location = locationManager
                                    .getLastKnownLocation(LocationManager.GPS_PROVIDER);
                            if (location != null) {
                                latitude = location.getLatitude();
                                longitude = location.getLongitude();
                            }
                        }
                    }
                }
            }

        } catch (Exception e) {
            e.printStackTrace();
        }

        return location;
    }

    /**
     * Stop using GPS listener
     * Calling this function will stop using GPS in your app
     * */
    public void stopUsingGPS(){
        if(locationManager != null){
            locationManager.removeUpdates(GPSTracker.this);
        }      
    }

    /**
     * Function to get latitude
     * */
    public double getLatitude(){
        if(location != null){
            latitude = location.getLatitude();
        }

        // return latitude
        return latitude;
    }

    /**
     * Function to get longitude
     * */
    public double getLongitude(){
        if(location != null){
            longitude = location.getLongitude();
        }

        // return longitude
        return longitude;
    }

    /**
     * Function to check GPS/wifi enabled
     * @return boolean
     * */
    public boolean canGetLocation() {
        return this.canGetLocation;
    }

    /**
     * Function to show settings alert dialog
     * On pressing Settings button will lauch Settings Options
     * */
    public void showSettingsAlert(){
        AlertDialog.Builder alertDialog = new AlertDialog.Builder(mContext);

        // Setting Dialog Title
        alertDialog.setTitle("GPS is settings");

        // Setting Dialog Message
        alertDialog.setMessage("GPS is not enabled. Do you want to go to settings menu?");

        // On pressing Settings button
        alertDialog.setPositiveButton("Settings", new DialogInterface.OnClickListener() {
            public void onClick(DialogInterface dialog,int which) {
                Intent intent = new Intent(Settings.ACTION_LOCATION_SOURCE_SETTINGS);
                mContext.startActivity(intent);
            }
        });

        // on pressing cancel button
        alertDialog.setNegativeButton("Cancel", new DialogInterface.OnClickListener() {
            public void onClick(DialogInterface dialog, int which) {
            dialog.cancel();
            }
        });

        // Showing Alert Message
        alertDialog.show();
    }

    @Override
    public void onLocationChanged(Location location) {
    }

    @Override
    public void onProviderDisabled(String provider) {
    }

    @Override
    public void onProviderEnabled(String provider) {
    }

    @Override
    public void onStatusChanged(String provider, int status, Bundle extras) {
    }

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

}

MyService.java

public class MyService extends Service {

final String LOG_TAG = "myLogs";

    // GPSTracker class
    GPSTracker gps;

  MyBinder binder = new MyBinder();

  Timer timer;
  TimerTask tTask;
  long interval = 10000;



  public void onCreate() {
    super.onCreate();
    Log.d(LOG_TAG, "onCreate");
//    timer = new Timer();
//    schedule();
  }

  public void schedule() {
        if (tTask != null) tTask.cancel();
        if (interval > 0) {
          tTask = new TimerTask() {
            public void run() {
                Log.d(LOG_TAG, "run");

                gps = new GPSTracker(getApplicationContext()); // also tried MyService.this

                if(gps!=null){
                    if(gps.canGetLocation()){
                          double latitude = gps.getLatitude();
                          double longitude = gps.getLongitude();
                          Log.d(LOG_TAG, "geo"+latitude+" lon"+longitude);


                          new RequestTask().execute("http://map.domain.ru/mygps.php?lat="+latitude+"&lon="+longitude+"&timestamp=1375235923365&hdop=16.0&altitude=107.65327&speed=0.0");
                        }
                    }else{
                        Log.d(LOG_TAG, "GPS null");
                    }

            }
          };
          timer.schedule(tTask, 10000, interval);
        }
      }

      long upInterval(long gap) {
        interval = interval + gap;
        schedule();
        return interval;
      }

      long downInterval(long gap) {
        interval = interval - gap;
        if (interval < 0) interval = 0;
        schedule();
        return interval;
      }

     // public IBinder onBind(Intent arg0) {
    //    Log.d(LOG_TAG, "MyService onBind");
    //    return binder;
    //  }

      class MyBinder extends Binder {
        MyService getService() {
          return MyService.this;
        }
      }
    //}

  public int onStartCommand(Intent intent, int flags, int startId) {
    Log.d(LOG_TAG, "onStartCommand");
  //  someTask();
  timer = new Timer();

  schedule();
    return super.onStartCommand(intent, flags, startId);
  }

  public void onDestroy() {
    super.onDestroy();
    Log.d(LOG_TAG, "onDestroy");
   // stopSelf();
    timer.cancel();
  }

  public IBinder onBind(Intent intent) {
    Log.d(LOG_TAG, "onBind");
    return null;
  }

  void someTask() {

  }
}

为什么在最后一个类而不是坐标中出现空值

代码

Log.d(LOG_TAG, "geo "+latitude+" lon "+longitude);

写日志“geo 0.0 lon 0.0”

1 个答案:

答案 0 :(得分:0)

这是因为在那个时候gps无法获得位置 几乎是你在建造这件事的时候 并且没有最后的位置  你刚刚检查了gps启用了 之后,您必须通过设备时间和位置时间戳之间的差异检查位置时间戳来确认返回的位置