【发布时间】:2019-01-25 23:36:11
【问题描述】:
我有一个小问题: 我从服务中收到 LocationListener 给出的速度值。但是当我关闭我的应用程序的用户界面时,位置监听器会停止发送更新。有谁知道该怎么做?我需要它来继续更新,即使应用程序未在使用中...
这是我的代码:
public class BackroundService extends Service {
//initializing the Location Manager and Listener
LocationManager locationManager;
LocationListener locationListener;
@Nullable
@Override
public IBinder onBind(Intent intent) {
return null;
}
@SuppressLint("MissingPermission")
@Override
public void onCreate() {
}
@SuppressLint("MissingPermission")
@Override
public int onStartCommand(Intent intent, int flags, int startId) {
//Instantiating the device manager an listener
locationManager = (LocationManager) getSystemService(LOCATION_SERVICE);
locationListener = new MyLocationListener();
locationManager.requestLocationUpdates("gps", 500, 0, locationListener);
return START_STICKY;
}
}
class MyLocationListener extends Service implements LocationListener
{
public float speed;
public void onLocationChanged(final Location location)
{
//when the location changed
Log.d("Location", ""+location);
Log.d("Float Location", ""+ location.getLongitude() + " " + location.getLatitude());
Log.d("Speed", " "+location.getSpeed());
//initializing the variable speed with the speed number given by the LocationListener
speed = location.getSpeed();
//creating a broadcast reciever
Intent intent = new Intent("speed_update");
intent.putExtra("speed", speed);
//sending speed to main activity
sendBroadcast(intent);
//checking if speed is in walking range
if (speed < 4.0 && speed > 0.4){
Log.d("######Checker######", "++++++++++turn off+++++++++++");
//Toast.makeText(MyLocationListener.this, "turn off", Toast.LENGTH_SHORT).show();
}
}
public void onProviderDisabled(String provider)
{
}
public void onProviderEnabled(String provider)
{
}
public void onStatusChanged(String provider, int status, Bundle extras)
{
}
@Nullable
@Override
public IBinder onBind(Intent intent) {
return null;
}
}
【问题讨论】:
标签: android service android-gps