【发布时间】:2014-04-01 06:06:57
【问题描述】:
我是 Android 开发的新手。我想构建一个 android 应用程序,它使用后台服务以指定的时间间隔(比如 15 分钟)将 GPS 坐标发送到 ASP.net Webservice。我成功地将 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 分钟间隔获取该位置的实际坐标,我需要做哪些更改。提前谢谢你。
【问题讨论】:
-
真正的问题是什么?你没有得到真实的位置?或者你不能每 15 分钟做一次?
-
我正在从我安装应用程序的位置获取坐标,即服务 - TimeServiceGPS 开始的位置
-
真正的问题是什么?您的位置错误或无法每 15 分钟获取一次位置
-
两者。位置不对,频率也有波动。
-
你能在下面看到我的答案吗?
标签: android asp.net sql-server web-services gps