- 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/
SQLite、Content provider 和 Shared Preference 之间的所有已知区别。 但我想知道什么时候需要根据情况使用 SQLite 或 Content Provider 或
警告:我正在使用一个我无法完全控制的后端,所以我正在努力解决 Backbone 中的一些注意事项,这些注意事项可能在其他地方更好地解决......不幸的是,我别无选择,只能在这里处理它们! 所以,我的
我一整天都在挣扎。我的预输入搜索表达式与远程 json 数据完美配合。但是当我尝试使用相同的 json 数据作为预取数据时,建议为空。点击第一个标志后,我收到预定义消息“无法找到任何内容...”,结果
我正在制作一个模拟 NHL 选秀彩票的程序,其中屏幕右侧应该有一个 JTextField,并且在左侧绘制弹跳的选秀球。我创建了一个名为 Ball 的类,它实现了 Runnable,并在我的主 Draf
这个问题已经有答案了: How can I calculate a time span in Java and format the output? (18 个回答) 已关闭 9 年前。 这是我的代码
我有一个 ASP.NET Web API 应用程序在我的本地 IIS 实例上运行。 Web 应用程序配置有 CORS。我调用的 Web API 方法类似于: [POST("/API/{foo}/{ba
我将用户输入的时间和日期作为: DatePicker dp = (DatePicker) findViewById(R.id.datePicker); TimePicker tp = (TimePic
放宽“邻居”的标准是否足够,或者是否有其他标准行动可以采取? 最佳答案 如果所有相邻解决方案都是 Tabu,则听起来您的 Tabu 列表的大小太长或您的释放策略太严格。一个好的 Tabu 列表长度是
我正在阅读来自 cppreference 的代码示例: #include #include #include #include template void print_queue(T& q)
我快疯了,我试图理解工具提示的行为,但没有成功。 1. 第一个问题是当我尝试通过插件(按钮 1)在点击事件中使用它时 -> 如果您转到 Fiddle,您会在“内容”内看到该函数' 每次点击都会调用该属
我在功能组件中有以下代码: const [ folder, setFolder ] = useState([]); const folderData = useContext(FolderContex
我在使用预签名网址和 AFNetworking 3.0 从 S3 获取图像时遇到问题。我可以使用 NSMutableURLRequest 和 NSURLSession 获取图像,但是当我使用 AFHT
我正在使用 Oracle ojdbc 12 和 Java 8 处理 Oracle UCP 管理器的问题。当 UCP 池启动失败时,我希望关闭它创建的连接。 当池初始化期间遇到 ORA-02391:超过
关闭。此题需要details or clarity 。目前不接受答案。 想要改进这个问题吗?通过 editing this post 添加详细信息并澄清问题. 已关闭 9 年前。 Improve
引用这个plunker: https://plnkr.co/edit/GWsbdDWVvBYNMqyxzlLY?p=preview 我在 styles.css 文件和 src/app.ts 文件中指定
为什么我的条形这么细?我尝试将宽度设置为 1,它们变得非常厚。我不知道还能尝试什么。默认厚度为 0.8,这是应该的样子吗? import matplotlib.pyplot as plt import
当我编写时,查询按预期执行: SELECT id, day2.count - day1.count AS diff FROM day1 NATURAL JOIN day2; 但我真正想要的是右连接。当
我有以下时间数据: 0 08/01/16 13:07:46,335437 1 18/02/16 08:40:40,565575 2 14/01/16 22:2
一些背景知识 -我的 NodeJS 服务器在端口 3001 上运行,我的 React 应用程序在端口 3000 上运行。我在 React 应用程序 package.json 中设置了一个代理来代理对端
我面临着一个愚蠢的问题。我试图在我的 Angular 应用程序中延迟加载我的图像,我已经尝试过这个2: 但是他们都设置了 src attr 而不是 data-src,我在这里遗漏了什么吗?保留 d
我是一名优秀的程序员,十分优秀!