[英]Android - Log fused location updates to a file in a background service
我正在尝试将融合位置更新从其自身的进程':locationProcess'中运行的未绑定服务记录到文件中。
AndroidManifest.xm l
<service
android:name=".LocationUpdate"
android:process=":locationProcess"
android:enabled="true"
android:exported="true" />
LocationUpdate.java
public class LocationUpdate extends Service implements GoogleApiClient.ConnectionCallbacks,
GoogleApiClient.OnConnectionFailedListener {...
onBind设置为返回null
@Override
public IBinder onBind(Intent arg0) {
return null;
}
并且onStartCommand返回START_STICKY。
我正在LocationUpdate服务的Google Play服务onConnected回调方法中创建文件...
@Override
public void onConnected(Bundle arg0) {
try {
pwFile = new PrintStream(new File(Environment.getExternalStoragePublicDirectory(Environment.DIRECTORY_DOCUMENTS), "gps.csv"));
pwFile.println("date,latitude,longtitude,altitude,bearing,accuracy");
} catch (IOException e) {
// TODO: Handle the exception
}
mLocationRequest = LocationRequest.create();
mLocationRequest.setPriority(LocationRequest.PRIORITY_BALANCED_POWER_ACCURACY);
mLocationRequest.setInterval(10000);
mLocationRequest.setFastestInterval(5000);
startLocationUpates();
}
并从LocationListener的onLocationChange回调中写出 GPS详细信息...
@Override
public void onLocationChanged(Location location) {
currentLat = location.getLatitude();
currentLng = location.getLongitude();
// Get current date time
Date newDate = new Date(System.currentTimeMillis());
// Write lat and long out to a file
pwFile.println(newDate.toString() + "," + String.format("%.6f", currentLat) + "," +
String.format("%.6f", currentLng) + "," + String.format("%.4f", location.getAltitude()) + "," +
String.format("%.4f", location.getBearing()) + "," + String.format("%.4f", location.getAccuracy()));
}
我在我的Application类的onCreate覆盖上启动服务...
public class App extends Application {
Intent LocationService;
@Override
public void onCreate() {
super.onCreate();
LocationService = new Intent(this, LocationUpdate.class);
startService(LocationService);
}
}
一切正常, App在Manifest.xml的<application>
标记android:name =“ mypackage.app”中声明。
这是没有的部分
我希望服务继续将位置记录到文件中,即使前台中有另一个应用程序也是如此。
如果用户故意关闭应用程序,它将停止记录。 阅读Android文档后,我认为我的代码可以正常工作。
据我所知,当App不在前台时,该服务确实会继续运行。 它继续运行,如果用户明确关闭应用程序,我不想出于某种原因,我不明白自己被破坏并重新创建而应用程序正在运行,以便onConnected在服务被再次调用这样的服务日志文件实际上已被覆盖。
我猜这更多是架构问题。
基本上,我希望我的位置服务能够在应用程序启动后不在前台时可靠地登录到文件,并在用户终止应用程序时停止运行。
希望是有道理的。 我在Github上查看了许多示例,但它们似乎仅在应用程序位于前台时才记录下来。
任何帮助我都非常感激,这一切都让我有些疯狂。
谢谢。
您将服务作为启动服务(而不是意图服务)提供。 然后在服务的onStartCommand上返回START_STICKY
。 这将告诉操作系统,如果出于任何原因需要关闭服务,请在有足够资源时再次运行它。 在您的情况下,当用户关闭活动/终止应用程序时,无论如何该服务进程都将被终止,但是通常将其重新打开。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.