基本上我想在后台发送纬度和经度,它在奥利奥版本下工作正常,但我被困在那个部分。它工作得很好。我添加了一个后台 JobIntentService,它在 Oreo 和 pie 背景中运行良好,但是当我在 2 分钟后锁定屏幕时,它会禁用或停止向我的服务器发送位置。
public class LocationService extends JobIntentService implements LocationListener {
static final int JOB_ID = 1000; //Unique job ID.
RequestQueue requestQueue;
DBConnection con;
String Lat, Lng;
public static final int notify = 5000; //interval between two services(Here Service run every 5 Minute)
private Handler mHandler = new Handler(); //run on another Thread to avoid crash
private Timer mTimer = null;
protected LocationManager locationManager;
@Override
public void onCreate() {
super.onCreate();
locationManager = (LocationManager) getSystemService(Context.LOCATION_SERVICE);
onGetLocation();
if (mTimer != null) // Cancel if already existed
mTimer.cancel();
else
mTimer = new Timer(); //recreate new
mTimer.scheduleAtFixedRate(new LocationService.TimeDisplay(), 0, notify); //Schedule task
}
public LocationService() {
}
public static void enqueueWork(Context context, Intent work) {
enqueueWork(context, LocationService.class, JOB_ID, work);
}
@Override
protected void onHandleWork(@NonNull Intent intent) {
UpdateLocation();
}
public void UpdateLocation()
{
con = new DBConnection(LocationService.this);
if(requestQueue==null) {
requestQueue = Volley.newRequestQueue(getApplicationContext());
requestQueue = Volley.newRequestQueue(getApplicationContext(), new StethoVolleyHurlStack());
}
StringRequest request = new StringRequest(Request.Method.POST,
"https://example.com/api/" + "updatelocation.php", new Response.Listener<String>() {
@Override
public void onResponse(String response) {
Log.d("Response", response.toString() + " " + Lat.toString()+ " " + Lng.toString());
}
}, new Response.ErrorListener() {
@Override
public void onErrorResponse(VolleyError error) {
Log.d("Response", error.toString());
}
}) {
@Override
protected Map<String, String> getParams() throws AuthFailureError {
Map<String, String> map = new HashMap<String, String>();
map.put("userid", con.getusename());
map.put("lat", Lat);
map.put("lng", Lng);
return map;
}
};
requestQueue.add(request);
}
public void onGetLocation() {
if (ActivityCompat.checkSelfPermission(this, Manifest.permission.ACCESS_FINE_LOCATION) != PackageManager.PERMISSION_GRANTED && ActivityCompat.checkSelfPermission(this, Manifest.permission.ACCESS_COARSE_LOCATION) != PackageManager.PERMISSION_GRANTED) {
return;
}
locationManager.requestLocationUpdates(LocationManager.GPS_PROVIDER, 0, 0, this);
}
@Override
public void onLocationChanged(Location location) {
Lng=String.valueOf(location.getLongitude());
Lat=String.valueOf(location.getLatitude());
}
class TimeDisplay extends TimerTask {
@Override
public void run() {
// run on another thread
mHandler.post(new Runnable() {
@Override
public void run() {
UpdateLocation();
}
});
}
}