我是Android开发的新手。我想构建一个Android应用程序,它使用后台服务以指定的间隔(比如15分钟)向ASP.net Webservice发送GPS坐标。我成功地将ASP.net Webservice中的坐标从Android设备获取到SQL Server 2008数据库,但是,即使我行进了50公里的距离,纬度和经度值也保持不变,更新间隔有时以秒为单位,有时以小时为单位。我引用了许多示例源代码并实现了以下代码。
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;
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) {
// TODO Auto-generated method stub
}
@Override
public void onProviderDisabled(String provider) {
// TODO Auto-generated method stub
}
@Override
public void onProviderEnabled(String provider) {
// TODO Auto-generated method stub
}
@Override
public void onStatusChanged(String provider, int status, Bundle extras) {
// TODO Auto-generated method stub
}
@Override
public IBinder onBind(Intent intent) {
// TODO Auto-generated method stub
return null;
}
}
public class TimeServiceGPS extends Service {
// constant
public static final long NOTIFY_INTERVAL = 900 * 1000; // 15 mins
GPSTracker gps;
DatabaseAdapter dba;
final Context context = this;
private Cursor cursor;
// run on another Thread to avoid crash
private Handler mHandler = new Handler();
// timer handling
private Timer mTimer = null;
private double latitude,longitude;
public static final String PREFS_NAME = "MyPrefsFile";
private final String log = "ServiceGPS";
private static String responseJSON;
private String JSONStr;
UserSessionManager session;
HashMap<String, String> user;
Common common;
@Override
public IBinder onBind(Intent intent) {
return null;
}
@Override
public void onCreate() {
dba=new DatabaseAdapter(this);
// Session class instance
session = new UserSessionManager(getApplicationContext());
// get user data from session
user = session.getUserDetails();
common= new Common(getApplicationContext());
// cancel if already existed
if(mTimer != null) {
mTimer.cancel();
} else {
// recreate new
mTimer = new Timer();
}
// schedule task
mTimer.scheduleAtFixedRate(new TimeDisplayTimerTask(), 0, NOTIFY_INTERVAL);
}
class TimeDisplayTimerTask extends TimerTask {
@Override
public void run() {
// run on another thread
mHandler.post(new Runnable() {
@Override
public void run() {
gps = new GPSTracker(TimeServiceGPS.this);
if(gps.canGetLocation()){
latitude = gps.getLatitude();
longitude = gps.getLongitude();
AsyncGPSWSCall task= new AsyncGPSWSCall();
task.execute();
//common.showToast("Your Location is - \nLat: " + latitude + "\nLong: " + longitude + "\nDate: " + dba.getDateTime()+ "\nUsername: " + user.get(UserSessionManager.KEY_USERNAME)+ "\nIMEI: " + user.get(UserSessionManager.KEY_IMEI));
}
else{
gps.showSettingsAlert();
}
}
});
}
//Async Class to send Credentials
private class AsyncGPSWSCall extends AsyncTask<String, Void, Void> {
@Override
protected Void doInBackground(String... params) {
Log.i(log, "doInBackground");
dba.openR();
try {
//Creation of JSON string
JSONObject json = new JSONObject();
json.put("latitude", latitude);
json.put("longitude", longitude);
json.put("username",user.get(UserSessionManager.KEY_USERNAME));
json.put("imeino",user.get(UserSessionManager.KEY_IMEI));
json.put("createddate",dba.getDateTime());
JSONStr=json.toString();
} catch (JSONException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
finally
{
dba.close();
}
if(common.isConnected())
{
try {
dba.openR();
cursor = dba.GetUrl();
if (cursor.moveToFirst()) {
Log.i(log,"Calling Cursor url");
Log.i(log,cursor.getString(cursor.getColumnIndex("URL")));
responseJSON = common.invokeJSONWS(JSONStr,"json","InsertGPSDetails",cursor.getString(cursor.getColumnIndex("URL")) );
Log.i(log,"Value of Json to Server - GPS: "+ JSONStr);
//Testing purpose. returns success on insert on SqlServer
common.showToast(responseJSON);
latitude=0;
longitude=0;
}
} catch (Exception e) {
// TODO: handle exception
e.printStackTrace();
} finally {cursor.close();dba.close(); }
}
return null;
}
@Override
protected void onPostExecute(Void result) {
Log.i(log, "onPostExecute");
}
@Override
protected void onPreExecute() {
Log.i(log, "onPreExecute");
}
@Override
protected void onProgressUpdate(Void... values) {
Log.i(log, "onProgressUpdate");
}
}
}
}
我正在检查我的应用仪表板活动中是否正在运行TimeServiceGPS服务。在清单文件中,我添加了<service android:name="com.example.test.TimeServiceGPS" />
我需要做什么改变才能每隔15分钟获得该位置的实际坐标。提前谢谢。
答案 0 :(得分:1)
GPSTracker gps;
gps = new GPSTracker(MainActivity.this);
if(gps.canGetLocation()){
latitude = gps.getLatitude();
longitude = gps.getLongitude();
}else{
gps.showSettingsAlert();
}
和gpstracker类是这样的:
package com.your.package;
import android.app.AlertDialog;
import android.app.Service;
import android.content.Context;
import android.content.DialogInterface;
import android.content.Intent;
import android.location.Location;
import android.location.LocationListener;
import android.location.LocationManager;
import android.os.Bundle;
import android.os.IBinder;
import android.provider.Settings;
import android.util.Log;
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;
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;
}
}
你每隔15分钟就可以使用这个功能:
Timer myTimer;
private boolean timerRunning = false;
private long RETRY_TIME = 15000;
private long START_TIME = 2000;
并在创建:
mcont=this;
myTimer = new Timer();
myTimer.scheduleAtFixedRate(new Task(), START_TIME, RETRY_TIME);
timerRunning = true;
你可以像这样触发它:
if (!timerRunning) {
mcont=this;
myTimer = new Timer();
myTimer.scheduleAtFixedRate(new Task(), START_TIME, RETRY_TIME);
timerRunning = true;
}
,任务类在这里:
public class Task extends TimerTask {
@Override
public void run() {
//you can put your upload code here
}
}