android 我想创建一个后台服务与获取数据从API在每一秒,所以如何创建它?

ppcbkaq5  于 2023-01-19  发布在  Android
关注(0)|答案(1)|浏览(120)

我需要创建一个后台服务,它可以每秒从API获取数据,因为我想监控一些数据并将这些数据添加到数据库中。
我尝试创建一个服务,如下所示,它的工作很好,也在后台工作时,应用程序被用户杀死,但问题是,当我使用我的应用程序长时间的应用程序UI完全挂起和卡住

  • 我的服务类编码
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);
 }
}

与此服务的问题是,应用程序被连续使用,然后应用程序没有响应,并由Android操作系统终止
那么,如何解决这个问题,以及如何创建一个适当的后台服务,以获得数据的每一秒,并将其添加到数据库?

wfveoks0

wfveoks01#

试试这个:

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

如果使用返回START_STICKY:如果后台服务被终止,系统会尝试重新启动它,这有时会导致问题,当您使用START_NOT_STICKY时,系统不会尝试重新启动它。我认为您的应用冻结的原因是因为系统正在尝试重新启动一个终止的服务。

相关问题