Android 我应该为GPS跟踪应用程序创建服务吗?
我正在编写一个位置服务应用程序,它记录用户每分钟去过的地方。 我应该为GPS流程创建服务吗?或者只是在活动中创建LocationManager?哪一个更好 此外,我还试图通过按下硬件主页按钮并在设置->位置关闭GPS来隐藏应用程序。我发现应用程序在一小时内自动关闭。Android 我应该为GPS跟踪应用程序创建服务吗?,android,gps,Android,Gps,我正在编写一个位置服务应用程序,它记录用户每分钟去过的地方。 我应该为GPS流程创建服务吗?或者只是在活动中创建LocationManager?哪一个更好 此外,我还试图通过按下硬件主页按钮并在设置->位置关闭GPS来隐藏应用程序。我发现应用程序在一小时内自动关闭。 是否可以使应用程序始终处于活动状态?我强烈建议至少将gps创建为活动中的一个线程,如果您希望更流畅,请将其设置为服务,并从异步任务内部广播意图。如果您想将其用于其他应用程序或其他活动,将其设置为服务会使其有点模块化。这就是我实现它的
是否可以使应用程序始终处于活动状态?我强烈建议至少将gps创建为活动中的一个线程,如果您希望更流畅,请将其设置为服务,并从异步任务内部广播意图。如果您想将其用于其他应用程序或其他活动,将其设置为服务会使其有点模块化。这就是我实现它的方式 如果你从服务而不是活动中运行gps读数,它也更容易控制gps读数的寿命,因此如果你切换活动等,服务不会中断。。下面是异步任务部分的示例:
/** Begin async task section ----------------------------------------------------------------------------------------------------*/
private class PollTask extends AsyncTask<Void, Void, Void> { //AsyncTask that listens for locationupdates then broadcasts via "LOCATION_UPDATE"
// Classwide variables
private boolean trueVal = true;
Location locationVal;
//Setup locationListener
LocationListener locationListener = new LocationListener(){ //overridden abstract class LocationListener
@Override
public void onLocationChanged(Location location) {
handleLocationUpdate(location);
}
@Override
public void onProviderDisabled(String provider) {
}
@Override
public void onProviderEnabled(String provider) {
}
@Override
public void onStatusChanged(String provider, int status,
Bundle extras) {
}
};
/** Overriden methods */
@Override
protected Void doInBackground(Void... params) {
//This is where the magic happens, load your stuff into here
while(!isCancelled()){ // trueVal Thread will run until you tell it to stop by changing trueVal to 0 by calling method cancelVal(); Will also remove locationListeners from locationManager
Log.i("service","made it to do in background");
try {
Thread.sleep(100);
} catch (InterruptedException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
return null;
}
@Override
protected void onCancelled(){
super.onCancelled();
stopSelf();
}
@Override
protected void onPreExecute(){ // Performed prior to execution, setup location manager
locationManager = (LocationManager)getSystemService(Context.LOCATION_SERVICE);
if(gpsProvider==true){
locationManager.requestLocationUpdates(LocationManager.GPS_PROVIDER, 0, 0, locationListener);
}
if(networkProvider==true){
locationManager.requestLocationUpdates(LocationManager.NETWORK_PROVIDER, 0, 0, locationListener);
}
}
@Override
protected void onPostExecute(Void result) { //Performed after execution, stopSelf() kills the thread
stopSelf();
}
@Override
protected void onProgressUpdate(Void... v){ //called when publishProgress() is invoked within asynctask
//On main ui thread, perform desired updates, potentially broadcast the service use notificationmanager
/** NEED TO BROADCAST INTENT VIA sendBroadCast(intent); */
Intent intent = new Intent(LOCATION_UPDATE);
//Put extras here if desired
intent.putExtra(ACCURACY, locationVal.getAccuracy()); // float double double long int
intent.putExtra(LATITUDE, locationVal.getLatitude());
intent.putExtra(LONGITUDE, locationVal.getLongitude());
intent.putExtra(TIMESTAMP, locationVal.getTime());
intent.putExtra(ALTITUDE,locationVal.getAltitude());
intent.putExtra(NUM_SATELLITES,0);/////////////****TEMP
sendBroadcast(intent); //broadcasting update. need to create a broadcast receiver and subscribe to LOCATION_UPDATE
Log.i("service","made it through onprogress update");
}
/** Custom methods */
private void cancelVal(){ //Called from activity by stopService(intent) --(which calls in service)--> onDestroy() --(which calls in asynctask)--> cancelVal()
trueVal = false;
locationManager.removeUpdates(locationListener);
}
private void handleLocationUpdate(Location location){ // Called by locationListener override.
locationVal = location;
publishProgress();
}
}
/**开始异步任务部分----------------------------------------------------------------------------------------------------*/
私有类PollTask扩展了AsyncTask{//AsyncTask,它侦听LocationUpdate,然后通过“LOCATION\u UPDATE”进行广播
//类范围变量
私有布尔值trueVal=true;
位置val;
//设置位置侦听器
LocationListener LocationListener=新LocationListener(){//重写的抽象类LocationListener
@凌驾
已更改位置上的公共无效(位置){
handleLocationUpdate(位置);
}
@凌驾
公共无效onProviderDisabled(字符串提供程序){
}
@凌驾
公共无效onProviderEnabled(字符串提供程序){
}
@凌驾
public void onStatusChanged(字符串提供程序,int状态,
捆绑(附加){
}
};
/**重写方法*/
@凌驾
受保护的Void doInBackground(Void…params){
//这就是魔法发生的地方,把你的东西放到这里
虽然(!isCancelled()){//trueVal线程将一直运行,直到您通过调用方法cancelVal()将trueVal更改为0来告诉它停止为止;它还将从locationManager中删除locationListeners
Log.i(“服务”,“在后台完成”);
试一试{
睡眠(100);
}捕捉(中断异常e){
//TODO自动生成的捕捉块
e、 printStackTrace();
}
}
返回null;
}
@凌驾
受保护的void onCancelled(){
super.onCancelled();
stopSelf();
}
@凌驾
受保护的void onPreExecute(){//在执行前执行,安装位置管理器
locationManager=(locationManager)getSystemService(Context.LOCATION\u服务);
如果(gpsProvider==true){
locationManager.RequestLocationUpdate(locationManager.GPS\提供程序,0,0,locationListener);
}
if(networkProvider==true){
locationManager.RequestLocationUpdate(locationManager.NETWORK\u提供程序,0,0,locationListener);
}
}
@凌驾
受保护的void onPostExecute(void result){//执行后,stopSelf()会终止线程
stopSelf();
}
@凌驾
受保护的void onProgressUpdate(void…v){//在asynctask中调用publishProgress()时调用
//在主ui线程上,执行所需的更新,可能会广播服务use notificationmanager
/**需要通过sendBroadCast(意图)广播意图*/
意向意向=新意向(位置更新);
//如果需要,请在此处添加额外内容
intent.putExtra(accurity,locationVal.getaccurity());//float double long int
intent.putExtra(纬度,位置val.getLatitude());
intent.putExtra(经度,locationVal.getLongitude());
intent.putExtra(TIMESTAMP,locationVal.getTime());
intent.putExtra(高度,位置val.getAltitude());
intent.putExtra(NUM_卫星,0);////**TEMP
sendBroadcast(intent);//广播更新。需要创建广播接收器并订阅位置更新
Log.i(“服务”,“通过onprogress更新实现”);
}
/**自定义方法*/
私有void cancelVal(){//stopService(intent)从活动调用--(在服务中调用)-->onDestroy()--(在异步任务中调用)-->cancelVal()
真值=假;
locationManager.RemoveUpdate(locationListener);
}
私有void handleLocationUpdate(位置){//由locationListener重写调用。
locationVal=位置;
出版进度();
}
}
我强烈建议您至少将gps创建为活动中的一个线程,如果您希望更流畅,请将其设置为服务,并从异步任务内部广播意图。如果您想将其用于其他应用程序或其他活动,将其设置为服务会使其有点模块化。这就是我实现它的方式
如果你从服务而不是活动中运行gps读数,它也更容易控制gps读数的寿命,因此如果你切换活动等,服务不会中断。。下面是异步任务部分的示例:
/** Begin async task section ----------------------------------------------------------------------------------------------------*/
private class PollTask extends AsyncTask<Void, Void, Void> { //AsyncTask that listens for locationupdates then broadcasts via "LOCATION_UPDATE"
// Classwide variables
private boolean trueVal = true;
Location locationVal;
//Setup locationListener
LocationListener locationListener = new LocationListener(){ //overridden abstract class LocationListener
@Override
public void onLocationChanged(Location location) {
handleLocationUpdate(location);
}
@Override
public void onProviderDisabled(String provider) {
}
@Override
public void onProviderEnabled(String provider) {
}
@Override
public void onStatusChanged(String provider, int status,
Bundle extras) {
}
};
/** Overriden methods */
@Override
protected Void doInBackground(Void... params) {
//This is where the magic happens, load your stuff into here
while(!isCancelled()){ // trueVal Thread will run until you tell it to stop by changing trueVal to 0 by calling method cancelVal(); Will also remove locationListeners from locationManager
Log.i("service","made it to do in background");
try {
Thread.sleep(100);
} catch (InterruptedException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
return null;
}
@Override
protected void onCancelled(){
super.onCancelled();
stopSelf();
}
@Override
protected void onPreExecute(){ // Performed prior to execution, setup location manager
locationManager = (LocationManager)getSystemService(Context.LOCATION_SERVICE);
if(gpsProvider==true){
locationManager.requestLocationUpdates(LocationManager.GPS_PROVIDER, 0, 0, locationListener);
}
if(networkProvider==true){
locationManager.requestLocationUpdates(LocationManager.NETWORK_PROVIDER, 0, 0, locationListener);
}
}
@Override
protected void onPostExecute(Void result) { //Performed after execution, stopSelf() kills the thread
stopSelf();
}
@Override
protected void onProgressUpdate(Void... v){ //called when publishProgress() is invoked within asynctask
//On main ui thread, perform desired updates, potentially broadcast the service use notificationmanager
/** NEED TO BROADCAST INTENT VIA sendBroadCast(intent); */
Intent intent = new Intent(LOCATION_UPDATE);
//Put extras here if desired
intent.putExtra(ACCURACY, locationVal.getAccuracy()); // float double double long int
intent.putExtra(LATITUDE, locationVal.getLatitude());
intent.putExtra(LONGITUDE, locationVal.getLongitude());
intent.putExtra(TIMESTAMP, locationVal.getTime());
intent.putExtra(ALTITUDE,locationVal.getAltitude());
intent.putExtra(NUM_SATELLITES,0);/////////////****TEMP
sendBroadcast(intent); //broadcasting update. need to create a broadcast receiver and subscribe to LOCATION_UPDATE
Log.i("service","made it through onprogress update");
}
/** Custom methods */
private void cancelVal(){ //Called from activity by stopService(intent) --(which calls in service)--> onDestroy() --(which calls in asynctask)--> cancelVal()
trueVal = false;
locationManager.removeUpdates(locationListener);
}
private void handleLocationUpdate(Location location){ // Called by locationListener override.
locationVal = location;
publishProgress();
}
}
/**开始异步任务部分----------------------------------------------------------------------------------------------------*/
私有类PollTask扩展了侦听loc的AsyncTask{//AsyncTask