I Want to create a background service with get data from api in every second so how to create it?

382 Views Asked by At

I need to create a background service that can get data from API every second because I want to monitor some data and add that data to the database.

I try to create a service like below it's working fine and also works in the background when the app kill by the user but the problem is when I used my application longly the application UI totally hangs and stuck

  • My Service Class Code

     public class MonitoringService extends Service {
     private static final int NOTIF_ID = 1;
     private static final String NOTIF_CHANNEL_ID = "Channel_Id";
    
     @Nullable
     @Override
     public IBinder onBind(Intent intent) {
         return null;
     }
    
    
     @Override
     public int onStartCommand(Intent intent, int flags, int startId) {
    
         startForeground();
         getLiveUpdate();
         AlramHendaler alramHendaler = new AlramHendaler(this);
         alramHendaler.setAlram();
    
         return START_STICKY;
    
     }
    
    
     private void getLiveUpdate() {
    
         //I use TimerTask for execute thread in background 
    
         ScheduledExecutorService scheduler = Executors.newScheduledThreadPool(2);
         MyTimerTask myTimerTask = new MyTimerTask(() -> {
    
             //Here I get data every second from API
             Call<ArrayList<TempModel>> call = RetrofitClient.getInstance(ResponceData.BASE_URL_1).getMyApi().getData(url);
             call.enqueue(new Callback<ArrayList<TempModel>>() {
                 @Override
                 public void onResponse(Call<ArrayList<TempModel>> call, Response<ArrayList<TempModel>> response) {
                    //get Response
                 }
    
                 @Override
                 public void onFailure(Call<ArrayList<TempModel>> call, Throwable t) {
    
                 }
             });
    
         });
         scheduler.scheduleAtFixedRate(myTimerTask, 0, 1, TimeUnit.SECONDS);
     }
    
    
     @SuppressLint("NewApi")
     private void startForeground() {
         Intent notificationIntent = new Intent(this, MainProcedureActivity.class);
         PendingIntent pendingIntent = PendingIntent.getActivity(this, 0, notificationIntent, PendingIntent.FLAG_IMMUTABLE);
         NotificationChannel chan = new NotificationChannel(NOTIF_CHANNEL_ID, "InOT", NotificationManager.IMPORTANCE_LOW);
         NotificationManager manager = (NotificationManager) getSystemService(Context.NOTIFICATION_SERVICE);
         Utills.addErrorInDatabase(this, "Service Is Connected");
         assert manager != null;
         manager.createNotificationChannel(chan);
         startForeground(NOTIF_ID, new NotificationCompat.Builder(this, NOTIF_CHANNEL_ID)
                 .setOngoing(true).setSmallIcon(R.drawable.ic_launcher_foreground)
                 .setContentTitle(getString(R.string.app_name)).setContentText("Service is running background").setContentIntent(pendingIntent).build());
     }
    
     @Override
     public void onDestroy() {
         super.onDestroy();
         Log.i("EXIT", "ondestroy!");
         Utills.addErrorInDatabase(this, "Service Is Disconnected");
         Intent broadcastIntent = new Intent(this, CheckServiceBrodcast.class);
         sendBroadcast(broadcastIntent);
     }
    }
    

The problem with this service is that the application is used continuously then the application not responding and is terminated by Android OS

So, How to solve this issue, and how to create a proper background service to get data every second and add it to the database?

1

There are 1 best solutions below

11
Jim Ross On

Try this :

@Override
 public int onStartCommand(Intent intent, int flags, int startId) {
     //your code
     return START_NOT_STICKY;
 }

if you use return START_STICKY: The System will try to restart the background service if it's kiled, this can cause issues sometimes, when you use START_NOT_STICKY, the System won't try to restart it. I think the reason why your app is freezing is because the system is trying to restart a dead service.