Immediately service code:

public class PushService extends Service { LocationManager locationManager; LocationListener locationListener; Intent intent; public PushService() { intent = new Intent("ru.jorik.konGor_taxi.new_order"); intent.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK); } @Override public void onCreate() { locationManager = (LocationManager) getSystemService(LOCATION_SERVICE); locationListener = new LocationListener() { @Override public void onLocationChanged(Location location) { String lon = Double.toString(location.getLongitude()); String lat = Double.toString(location.getLatitude()); new GeoTask().execute(lon, lat); String serverAnswer = ""; try { serverAnswer = new OrdersTask().execute().get(); } catch (InterruptedException | ExecutionException e) { e.printStackTrace(); } Orders orders = new Gson().fromJson(serverAnswer, Orders.class); if (!orders.data.isEmpty()) { Order comeOrder = orders.getLastOrder(); Order existOrder = Driver.orders.getLastOrder(); intent.putExtra("numberOrder", comeOrder.number); intent.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK); startActivity(intent); } Driver.orders = orders; WorkActivity.refresList(); } @Override public void onProviderDisabled(String provider) { } @Override public void onProviderEnabled(String provider) { } @Override public void onStatusChanged(String provider, int status, Bundle extras) { } }; super.onCreate(); } @Override public int onStartCommand(Intent intent, int flags, int startId) { checkPermission(); locationManager.requestLocationUpdates(LocationManager.NETWORK_PROVIDER, 10*1000, 0, locationListener); return super.onStartCommand(intent, flags, startId); } @Override public void onDestroy() { super.onDestroy(); } @Override public IBinder onBind(Intent intent) { // TODO: Return the communication channel to the service. throw new UnsupportedOperationException("Not yet implemented"); } public void checkPermission (){ int pmC = ContextCompat.checkSelfPermission(this, Manifest.permission.ACCESS_FINE_LOCATION); if (hasSelfPermission(this, Manifest.permission.ACCESS_FINE_LOCATION));// разрешение есть else // разрешения нету // проверка версии api if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.M){ } } //проверка полученного разрешения public boolean hasSelfPermission (Context cont, String perm){ if(ContextCompat.checkSelfPermission(cont,perm)==0) return true; return false; } //класс отправки координат на сервер. Ничего не возвращает и не читает ответ сервера public class GeoTask extends AsyncTask <String, Void, Void> { @Override protected Void doInBackground(String... coords) { Locale locale = new Locale ("ru","RU"); DateFormat df = DateFormat.getDateTimeInstance(DateFormat.DEFAULT, DateFormat.DEFAULT, locale); String date = df.format(new Date()); String sendData = "action=addtomap&UserName=" + Driver.name + "&lat=" + coords[1] + "&lon=" + coords[0] + "&Date=" + date; try{ URL url = new URL("http://kongor.arenda-awto.ru/modules/order/server_side.php"); HttpURLConnection connection = (HttpURLConnection) url.openConnection(); connection.setDoOutput(true); connection.setRequestMethod("POST"); connection.setRequestProperty("Cookie", Driver.session); //отправка запроса DataOutputStream dataOutputStream = new DataOutputStream(connection.getOutputStream()); dataOutputStream.writeBytes(sendData); dataOutputStream.flush(); dataOutputStream.close(); connection.disconnect(); }catch (IOException e){ System.err.println(e); } return null; } } //класс, который принимает JSON строку от сервера с содеражанием заказов public class OrdersTask extends AsyncTask <Void, Void, String> { @Override protected String doInBackground(Void... params) { String answer = "empty"; try{ URL url = new URL("http://server_side.php"); HttpURLConnection connection = (HttpURLConnection) url.openConnection(); connection.setDoOutput(true); connection.setDoInput(true); connection.setRequestMethod("POST"); connection.setRequestProperty("Cookie", Driver.session); DataOutputStream dataOutputStream = new DataOutputStream(connection.getOutputStream()); dataOutputStream.writeBytes("anyRequest"); dataOutputStream.flush(); dataOutputStream.close(); BufferedReader bufferedReader; try{ bufferedReader = new BufferedReader(new InputStreamReader( new GZIPInputStream(new DataInputStream(connection.getInputStream())))); } catch (IOException e){ bufferedReader = new BufferedReader(new InputStreamReader(new DataInputStream(connection.getInputStream()))); } StringBuilder buffer = new StringBuilder(); String temp; while ((temp = bufferedReader.readLine()) != null){ buffer.append(temp); } answer = buffer.toString(); connection.disconnect(); ///* Костыль для исправления ответа сервера if (!answer.substring(0, 10).equals("{\"draw\":nu")) { answer = "{\"draw\":nu" + answer; } ///* конец костыля -- }catch (IOException e){ System.err.println(e); } return answer; } } 

The service works fine as long as the application is active. It is necessary to minimize the application - the service closes (stops checking GPS and gives an error). What is the problem? and how to catch errors in the service on Android Studio? I work with services for the first time.

  • 2
    The only option to ensure the operation of the service regardless of the life cycle. Activity - use Foreground Service - Vladyslav Matviienko
  • The meaning is not quite the same. The bottom line is that the service works in the background, with the application minimized. and closed when the application is closed - Jorik

2 answers 2

onStartCommand should look like this if you want the service to work in the background and at least restart

  @Override public int onStartCommand(Intent intent, int flags, int startId) { //твой код return Service.START_STICKY; } 

START_STICKY indicates that the service should restart if it was closed.

In general, this is how the service and the application have already noticed here work in the same thread. If you specify the START_STICKY flag when the application is closed, the service will die and restart, which is not so bad.

By default, the services run in the background, which means that in the event of a shortage of memory, the operating system begins to look askance first of all at them, which leads to the killing of the service by the system. In this case, the only option is to make the service non-background, that is, instead of Background run it in Foreground . In this case, its priority will be like that of a normal application, that is, the system will not try to kill it even in case of insufficient memory.

Android has a startForeground method for this .

There is a good example of foreground service.

  • Implemented with startForeground - Jorik

The problem is that the service runs on the same Thread as the application. Try to make PushService inherit from the IntentService class (it creates its Thread) or run its own Thread in its Service.

  • one
    it will not help. - Vladyslav Matviienko