#java #php #android #mysql #android-studio
#java #php #android #mysql #android-studio
Вопрос:
Я использую строковый запрос для извлечения API, который я создал в базе данных PHP и mysql.
Я хочу, чтобы мое приложение уведомляло, когда в данных, которые я получаю с сервера, произошли некоторые изменения. Я использую JobSevice
и JobScheduler
запускаю сервис, даже если приложение близко. Я также использую ExecutorService
для запуска вызова API в отдельном потоке.
Это мой фактический код(java) для фоновой службы. На самом деле, этот код предназначен только для тестирования. Но я буду реализовывать тот же код в своем официальном проекте, если это сработает нормально.
public class AppService extends JobService { private static final String TAG = "AppService"; private boolean isBackgroundRunning; private ExecutorService executor; @Override public boolean onStartJob(JobParameters jobParameters) { Log.d(TAG, "onStartJob: Job Starting"); isBackgroundRunning = true; backgroundWork(jobParameters); return true; } private void backgroundWork(JobParameters jobParameters){ executor = Executors.newSingleThreadExecutor(); Executors.newSingleThreadExecutor().execute(() -gt; { while(isBackgroundRunning){ Volley.newRequestQueue(this).add( new StringRequest( Request.Method.GET, "http://" Statics.IP "/projects/codeplayground/GetTest.php", res -gt; { try{ JSONObject obj = new JSONObject(res); String status = obj.getString("Status"); NotificationManager manager = (NotificationManager)getSystemService(NOTIFICATION_SERVICE); StatusBarNotification[] activeNotifs = manager.getActiveNotifications(); if(status.equals("to ship") amp;amp; activeNotifs.length == 0){ NotificationHelper.displayNotification(this, 1, R.drawable.ic_launcher_foreground, Notification.PRIORITY_HIGH, "Updates", "Status updated!"); } }catch(Exception ex){ Log.d(TAG, "backgroundWork: " ex.getMessage()); } }, err -gt; { Log.d(TAG, "backgroundWork: " err.getMessage()); } ) ); SystemClock.sleep(3000); } }); } @Override public boolean onStopJob(JobParameters jobParameters) { isBackgroundRunning = false; if(!executor.isShutdown()){ executor.shutdown(); executor.shutdownNow(); } Log.d(TAG, "onStopJob: Job Stopped"); return true; } }
Это код(java) для запуска службы
ComponentName componentName = new ComponentName(this, AppService.class); JobInfo.Builder jobInfoBuilder = new JobInfo.Builder(101, componentName); jobInfoBuilder.setRequiredNetworkType(JobInfo.NETWORK_TYPE_ANY); jobInfoBuilder.setRequiresDeviceIdle(false); jobInfoBuilder.setRequiresCharging(false); jobInfoBuilder.setPeriodic(15 * 60 * 1000); jobInfoBuilder.setPersisted(true); JobScheduler jobScheduler = (JobScheduler) getSystemService(JOB_SCHEDULER_SERVICE); jobScheduler.schedule(jobInfoBuilder.build());
Это те данные, которые изменятся
//from this { "StatusID":"1", "Status":"pending" } //to this { "StatusID":"1", "Status":"to ship" }
To be specific, I want to notify my application when the status updates from pending to to ship.
This code works fine but the problem is the notification will pop up every three seconds because of the SystemClock.sleep(3000);
. And if I do the jobFinished(param, true)
the service will stop and restarts after some long time thats why I decided to run the API infinitely using while
loop.
My question is… Is there any way to set the stop time of the service before the service restarts when I use jobFinished(param, true)
so that I will not run the API call infinitely? or is there any better way to notify the android application when something changed in the data?