- html - 出于某种原因,IE8 对我的 Sass 文件中继承的 html5 CSS 不友好?
- JMeter 在响应断言中使用 span 标签的问题
- html - 在 :hover and :active? 上具有不同效果的 CSS 动画
- html - 相对于居中的 html 内容固定的 CSS 重复背景?
我的 Android 应用程序有问题。我需要一个应用程序在打开另一个应用程序时获取后台 GPS 位置。应用程序在后台运行,但我也想在后台获取 GPS 位置。
创建开始和停止按钮以获取 gps 位置它正常工作但是当单击主页按钮时 gps 停止获取位置
这是我的代码..
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_gps);
/* get TextView to display the GPS data */
txtLat = (TextView) findViewById(R.id.textview1);
/* the location manager is the most vital part it allows access
* to location and GPS status services */
locationManager = (LocationManager) getSystemService(Context.LOCATION_SERVICE);
locationManager.requestLocationUpdates(LocationManager.GPS_PROVIDER ,10000,10, this);
// locationManager.requestLocationUpdates(LocationManager.GPS_PROVIDER, 10 * 1000L, 0, this);
btnShow = (Button) findViewById(R.id.btnstart);
btnStop = (Button) findViewById(R.id.btnstop);
btnShow.setOnClickListener(new OnClickListener() {
public void onClick(View arg0) {
Toast.makeText(getBaseContext(), "Trip Start.", Toast.LENGTH_SHORT).show();
txtLat.setVisibility(View.VISIBLE);
onResume();
btnShow.setEnabled(false);
btnStop.setEnabled(true);
}
});
Button btnstop = (Button) findViewById(R.id.btnstop);
btnstop.setOnClickListener(new OnClickListener() {
public void onClick(View v) {
onPause();
Toast.makeText(getBaseContext(), "Trip Ended.", Toast.LENGTH_SHORT).show();
btnShow.setEnabled(true);
btnStop.setEnabled(false);
}
});
}
public void onLocationChanged(Location location) {
if (location == null) {
Toast.makeText(getApplicationContext(),"Searching for your location.", Toast.LENGTH_SHORT).show();
locationManager.requestLocationUpdates(provider, 10000, 10,locationListener);
onLocationChanged(location);
}
else
{
double cell_lat=location.getLatitude();
double cell_long=location.getLongitude();
double altitude=location.getAltitude();
double accuracy=location.getAccuracy();
String status="true";
sb = new StringBuilder(512);
noOfFixes++;
/* display some of the data in the TextView */
sb.append("Tracking: ");
sb.append(noOfFixes);
sb.append('\n');
sb.append('\n');
sb.append("Londitude: ");
sb.append(location.getLongitude());
sb.append('\n');
sb.append("Latitude: ");
sb.append(location.getLatitude());
sb.append('\n');
sb.append("Altitiude: ");
sb.append(location.getAltitude());
sb.append('\n');
sb.append("Accuracy: ");
sb.append(location.getAccuracy());
sb.append("ft");
sb.append('\n');
txtLat.setText(sb.toString());
}
public void onProviderDisabled(String provider) {
/* this is called if/when the GPS is disabled in settings */
Log.v(tag, "Disabled");
/* bring up the GPS settings */
Intent intent = new Intent(
android.provider.Settings.ACTION_LOCATION_SOURCE_SETTINGS);
startActivity(intent);
}
public void onProviderEnabled(String provider) {
Log.v(tag, "Enabled");
Toast.makeText(this, "GPS Enabled", Toast.LENGTH_SHORT).show();
}
public void onStatusChanged(String provider, int status, Bundle extras) {
/* This is called when the GPS status alters */
switch (status) {
case LocationProvider.OUT_OF_SERVICE:
Log.v(tag, "Status Changed: Out of Service");
Toast`enter code here`.makeText(this, "Status Changed: Out of Service",
Toast.LENGTH_SHORT).show();
break;
case LocationProvider.TEMPORARILY_UNAVAILABLE:
Log.v(tag, "Status Changed: Temporarily Unavailable");
Toast.makeText(this, "Status Changed: Temporarily Unavailable",
Toast.LENGTH_SHORT).show();
break;
case LocationProvider.AVAILABLE:
Log.v(tag, "Status Changed: Available");
Toast.makeText(this, "Status Changed: Available",
Toast.LENGTH_SHORT).show();
break;
}
}
@Override
protected void onResume() {
/*
* onResume is is always called after onStart, even if the app hasn't been
* paused
*
* add location listener and request updates every 1000ms or 10m
*/
locationManager.requestLocationUpdates(LocationManager.GPS_PROVIDER, 1000, 10f, this);
super.onResume();
}
@Override
protected void onPause() {
/* GPS, as it turns out, consumes battery like crazy */
locationManager.removeUp`enter code here`dates(this);
super.onPause();
}
@Override
public boolean onKeyDown(int keyCode, KeyEvent event) {
if ((keyCode == KeyEvent.KEYCODE_HOME)) {
System.out.println("KEYCODE_HOME");
Toast.makeText(getBaseContext(), "Home Button.", Toast.LENGTH_SHORT).show();
this.moveTaskToBack(true);
//showDialog("'HOME'");
return true;
}
if ((keyCode == KeyEvent.KEYCODE_BACK)) {
System.out.println("KEYCODE_BACK");
finish();
showDialog("'BACK'");
return true;
}
if ((keyCode == KeyEvent.KEYCODE_MENU)) {
System.out.println("KEYCODE_MENU");
//showDialog("'MENU'");
return true;
}
return false;
}
void showDialog(String the_key){
AlertDialog.Builder builder = new AlertDialog.Builder(this);
builder.setMessage("You have pressed the " + the_key + " button. Would you like to exit the app?")
.setCancelable(true)
.setPositiveButton("OK", new DialogInterface.OnClickListener() {
public void onClick(DialogInterface dialog, int id) {
dialog.cancel();
finish();
}
})
.setNegativeButton("Cancel", new DialogInterface.OnClickListener() {
public void onClick(DialogInterface dialog, int id) {
dialog.cancel();
}
});
AlertDialog alert = builder.create();
alert.setTitle("GPS.");
alert.show();
}
最佳答案
我在某处找到了这段代码它对我有用 LINK ,我已经按照自己的要求修改了代码,试试吧。
它从后台服务中将数据保存到数据库中,您只需要从一个 Activity 中启动该服务,注意:只有当第一个位置的距离大于给定的最小距离时,它才会保存到数据库中。
public class BackgroundLocationService extends Service implements
GooglePlayServicesClient.ConnectionCallbacks,
GooglePlayServicesClient.OnConnectionFailedListener, LocationListener {
private static final String TAG = "BackgroundLocationService";
IBinder mBinder = new LocalBinder();
private LocationClient mLocationClient;
private LocationRequest mLocationRequest;
// Flag that indicates if a request is underway.
private boolean mInProgress;
private Boolean servicesAvailable = false;
private double previousLatitude = 0;
private double previousLongitude = 0;
private SharedPreferences stopLocatinServicePreferance;
private float[] distance;
// public static boolean isStopSelf = false;
public class LocalBinder extends Binder {
public BackgroundLocationService getServerInstance() {
return BackgroundLocationService.this;
}
}
@Override
public void onCreate() {
super.onCreate();
mInProgress = false;
// Create the LocationRequest object
mLocationRequest = LocationRequest.create();
// Use high accuracy
mLocationRequest.setPriority(LocationRequest.PRIORITY_HIGH_ACCURACY);
// Set the update interval to 5 seconds
mLocationRequest.setInterval(Constants.UPDATE_INTERVAL);
// Set the fastest update interval to 1 second
mLocationRequest.setFastestInterval(Constants.FASTEST_INTERVAL);
servicesAvailable = servicesConnected();
/*
* Create a new location client, using the enclosing class to handle
* callbacks.
*/
mLocationClient = new LocationClient(this, this, this);
}
private boolean servicesConnected() {
// Check that Google Play services is available
int resultCode = GooglePlayServicesUtil
.isGooglePlayServicesAvailable(this);
// If Google Play services is available
if (ConnectionResult.SUCCESS == resultCode) {
return true;
} else {
return false;
}
}
public int onStartCommand(Intent intent, int flags, int startId) {
super.onStartCommand(intent, flags, startId);
if (!servicesAvailable || mLocationClient.isConnected() || mInProgress)
return START_STICKY;
setUpLocationClientIfNeeded();
if (!mLocationClient.isConnected() || !mLocationClient.isConnecting()
&& !mInProgress) {
appendLog(DateFormat.getDateTimeInstance().format(new Date())
+ ": Started", Constants.LOG_FILE);
mInProgress = true;
mLocationClient.connect();
}
return START_STICKY;
}
/*
* Create a new location client, using the enclosing class to handle
* callbacks.
*/
private void setUpLocationClientIfNeeded() {
if (mLocationClient == null)
mLocationClient = new LocationClient(this, this, this);
}
// Define the callback method that receives location updates
@Override
public void onLocationChanged(Location location) {
// Report to the UI that the location was updated
String msg = Double.toString(location.getLatitude()) + ","
+ Double.toString(location.getLongitude());
Log.d("debug", msg);
SimpleDateFormat s = new SimpleDateFormat("ddMMyyyyhhmmss");
String timeStamp = s.format(new Date());
System.out.println("TimeStamp ddMMyyyyhhmmss =" + timeStamp);
if (isDistanceAccountable(location.getLatitude(),
location.getLongitude(), previousLatitude, previousLongitude)) {
DatabaseHelper dbm = DatabaseHelper
.getInstance(getApplicationContext());
ContentValues cv = new ContentValues();
cv.put(DatabaseHelper.KEY_LATLONG, location.getLatitude() + "@"
+ location.getLongitude());
cv.put(DatabaseHelper.KEY_TIMESTAMP, timeStamp);
cv.put(DatabaseHelper.KEY_STATUS, "0");
cv.put(DatabaseHelper.KEY_USER_ID, "");
dbm.insert(DatabaseHelper.TABLE_TRACKINFO_TABLE, cv);
// }
// Toast.makeText(this, msg, Toast.LENGTH_SHORT).show();
appendLog(msg, Constants.LOCATION_FILE);
}
previousLatitude = location.getLatitude();
previousLongitude = location.getLongitude();
stopLocatinServicePreferance = getSharedPreferences("SERVICE_PREF", 0);
boolean check = stopLocatinServicePreferance.getBoolean("isStop", true);
Log.e(TAG, "isStop?" + check);
if (check) {
Log.e(TAG, "is self stoping ");
if (mLocationClient != null) {
mLocationClient.removeLocationUpdates(this);
// Destroy the current location client
mLocationClient = null;
}
this.stopSelf();
}
}
/**
* Returns true if distance is grater than MINIMUM_DISTANCE_ACCOUNTABLE
* NOTE: returns true if there is no previousLatitude,previousLongitude, it
* means this is first time it needs to save the data
*
* @param currentLatitude
* @param currentLongitude
* @param previousLatitude
* @param previousLongitude
* @return
*/
private boolean isDistanceAccountable(double currentLatitude,
double currentLongitude, double previousLatitude,
double previousLongitude) {
distance = new float[1];
if (previousLatitude > 0 && previousLongitude > 0) {
Location.distanceBetween(currentLatitude, currentLongitude,
previousLatitude, previousLongitude, distance);
Log.v(TAG + " > isDistanceAccountable()", "previousLatitude = "
+ previousLatitude + "previousLongitude = "
+ previousLongitude + " currentLatitude = "
+ currentLatitude + " , currentLongitude = "
+ currentLongitude);
} else {
Log.v(TAG + " > isDistanceAccountable()", "previousLatitude = "
+ previousLatitude + "previousLongitude = "
+ previousLongitude);
return true;
}
if (distance[0] > Constants.MINIMUM_DISTANCE_ACCOUNTABLE) {
Log.v(TAG + " > isDistanceAccountable()", "Distance = "
+ distance[0] + "return true");
return true;
} else {
Log.v(TAG + " > isDistanceAccountable()", "Distance = "
+ distance[0] + "return false");
return false;
}
}
@Override
public IBinder onBind(Intent intent) {
return mBinder;
}
public String getTime() {
SimpleDateFormat mDateFormat = new SimpleDateFormat(
"yyyy-MM-dd HH:mm:ss");
return mDateFormat.format(new Date());
}
public void appendLog(String text, String filename) {
File logFile = new File(filename);
if (!logFile.exists()) {
try {
logFile.createNewFile();
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
try {
// BufferedWriter for performance, true to set append to file flag
BufferedWriter buf = new BufferedWriter(new FileWriter(logFile,
true));
buf.append(text);
buf.newLine();
buf.close();
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
@Override
public void onDestroy() {
try {
// Turn off the request flag
mInProgress = false;
if (servicesAvailable && mLocationClient != null) {
mLocationClient.removeLocationUpdates(this);
// Destroy the current location client
mLocationClient = null;
}
appendLog(DateFormat.getDateTimeInstance().format(new Date())
+ ": Stopped", Constants.LOG_FILE);
} catch (Exception e) {
Log.e(TAG + " > onDestroy()", e.toString());
}
super.onDestroy();
}
/*
* Called by Location Services when the request to connect the client
* finishes successfully. At this point, you can request the current
* location or start periodic updates
*/
@Override
public void onConnected(Bundle bundle) {
// Request location updates using static settings
mLocationClient.requestLocationUpdates(mLocationRequest, this);
appendLog(DateFormat.getDateTimeInstance().format(new Date())
+ ": Connected", Constants.LOG_FILE);
}
/*
* Called by Location Services if the connection to the location client
* drops because of an error.
*/
@Override
public void onDisconnected() {
// Turn off the request flag
mInProgress = false;
// Destroy the current location client
mLocationClient = null;
appendLog(DateFormat.getDateTimeInstance().format(new Date())
+ ": Disconnected", Constants.LOG_FILE);
}
/*
* Called by Location Services if the attempt to Location Services fails.
*/
@Override
public void onConnectionFailed(ConnectionResult connectionResult) {
mInProgress = false;
/*
* Google Play services can resolve some errors it detects. If the error
* has a resolution, try sending an Intent to start a Google Play
* services activity that can resolve error.
*/
if (connectionResult.hasResolution()) {
// If no resolution is available, display an error dialog
} else {
}
}
这里是支持类。
public final class Constants {
// Milliseconds per second
private static final int MILLISECONDS_PER_SECOND = 100;
// Update frequency in seconds
private static final int UPDATE_INTERVAL_IN_SECONDS = 10;
// Update frequency in milliseconds
public static final long UPDATE_INTERVAL = MILLISECONDS_PER_SECOND
* UPDATE_INTERVAL_IN_SECONDS;
// The fastest update frequency, in seconds
private static final int FASTEST_INTERVAL_IN_SECONDS = 10;
// A fast frequency ceiling in milliseconds
public static final long FASTEST_INTERVAL = MILLISECONDS_PER_SECOND
* FASTEST_INTERVAL_IN_SECONDS;
// Stores the lat / long pairs in a text file
public static final String LOCATION_FILE = "sdcard/location.txt";
// Stores the connect / disconnect data in a text file
public static final String LOG_FILE = "sdcard/log.txt";
// Minimum accountable distance in meters
public static final float MINIMUM_DISTANCE_ACCOUNTABLE = 50;
/**
* Suppress default constructor for noninstantiability
*/
private Constants() {
throw new AssertionError();
}
关于android - 使用 LocationListener 在 Android 中运行 App 后台时获取 GPS 数据,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/20964605/
我有一个 GSM/GPS 单元连接到一个微 Controller ,它们之间的通信工作正常。我能够获取 GPS 并将其发送到微 Controller ,但有时设备在建筑物内,所以我无法真正获取当前的
它显示,错误指出“没有符合条件的应用安装设备” 设备规范如下, 型号:联想A369i Android 操作系统版本:4.2.2 我在 android mainfest 文件中执行以下权限
我有一个 Adafruit FONA 3G/GPS 模块 ( American Version )。我已经可以使用蜂窝功能,但 GPS 功能却遇到了困难。我尝试过无源和有源天线。 这是 SIM5320
今天在将我的应用程序上传到市场时,我发现它仅适用于具有 GPS 的设备,因此不包括某些平板电脑。 我的应用程序中的 GPS 是可选的。是否可以为有和没有 GPS 的设备发布一个应用程序,或者我需要制作
在 Monodroid 中,我正在尝试访问 GPS 服务。我只需要一个位置对象。 这一行报错: _locationManager.RequestLocationUpdates(LocationMana
我是 GPS 世界的新手。我需要知道如何使用 DGPS 进行后处理。我在网上找到了关于 DGPS、后处理等的定义,但是,找不到关于如何实际进行 DGPS 后处理的明确步骤。在搜索提供商时,我发现 CO
我有一系列 gps 值,每个值包含:timestamp, latitude, longitude, n_sats, gps_speed, gps_direction, ... ( NMEA data
抱歉,如果这是错误的“堆栈”。我找不到更合适的。 我为我的狗买了一个 GPS 追踪器,它附带订阅、一张 SIM 卡和一个开发不佳的应用程序。 我已取消订阅并想使用该设备将位置信息发送到我自己的服务器。
有没有一种在线方法可以用来获取 Google map 上两点之间路线上的所有 gps 点?即,如果我给出起点和终点,我需要获取该特定路线上的所有 GPS 点。 最佳答案 除了数据的所有者之外,每个人都
我正在尝试从 GPS 跟踪设备转换 GPS 数据。该公司提供了协议(protocol)手册,但不清楚。我能够从我从设备收到的数据包中解码的大部分数据。通信是通过 TCP/IP 进行的。我在解码经度和纬
我想从 GPS 坐标中获取城市名称。我可以使用 Google API 获取 GPS 点的详细信息 http://maps.googleapis.com/maps/api/geocode/output?
我做了一个 .gpx 文件来模拟 IOS 模拟器上的路线,现在我想模拟水平精度我该怎么做? 以下是我的 .gpx 文件的摘录: //how add horizontal accuracy
我有两个 GPS 坐标 例如(Lat1, Long1) 和 (Lat2,Long2) 谁能帮我找到这两点之间的角度。 值应为 0-360 度。 最佳答案 取自 this以前的SO帖子: float d
我正在为一个小类项目寻找 GPS。我们想要尽可能小的 GPS,我们真正需要它做的就是在我们轮询时为我们提供经度和纬度值。 我尝试查看 sparkfun,但由于我们之前没有真正使用过这种类型的硬件,因此
我正在处理 GPS 数据,每秒获取值并在 map 上显示当前位置。问题在于,有时(特别是当精度较低时)这些值变化很大,使得当前位置在 map 中的远距离点之间“跳跃”。 我想知道一些足够简单的方法来避
我正在创建一个请求用户位置的 BREW 应用程序。 如果手机无法获取位置,我想显示错误。 在确定手机不太可能获得 GPS 定位之前,我应该等待回调多久? 最佳答案 当需要冷启动时,接收器必须下载全套星
我有一辆安装了跟踪器的车辆。该设备具有 GPS 系统、3 轴加速度计、3 轴磁力计和陀螺仪。是否可以通过车辆在斜坡或山坡上向后滚动的程度来确定。使用 gps 角度不是一种选择,因为为短距离向后移动提供
我们计划编写一个软件,每 5 秒左右跟踪一次汽车的 GPS 位置、GPS 信号强度、加速度计(X、Y、Z)和陀螺仪(X、Y、Z)。并将数据发送到服务器进行后期处理。服务器将确定哪些道路上有汽车。所以这
这是我的问题:智能手机会向我的服务器发送一些 gps 坐标(纬度、经度、高度),我必须将这些坐标与存储在数据库中的地址进行比较,以查看智能手机和服务器之间的距离地址。为了进行实际比较,我还需要获取此地
HTML5 浏览器可以检索计算机的 gps 位置。 http://diveintohtml5.ep.io/geolocation.html 我想创建一个伪造 GPS 设备的应用程序,但我无法在任何地方
我是一名优秀的程序员,十分优秀!