Android service with repeating thread in background with partial trail blocking

I have a thread running in an application service that reads data from a page on which a web view was previously registered. This thread is working fine.

Now I would like to periodically repeat this thread, say, once a minute, even when the phone is sleeping / off. I know that I will probably have to get around this with wake_lock, but I have no idea.

I have 3 problems here. I tried to repeat the stream with (true) sleep (60000) .... but this will stop the stream after the phone screen goes blank. Is there a better way?

Then I would also like to compare the number of rows with zero. The value, if the number of rows is greater than zero, does xxx.

Any help is much appreciated!

Thread downloadThread = new Thread() { public void run() { Document doc; doc = null; try { final String url = "https://xxx.xxx.xx"; // -- Android Cookie part here -- CookieSyncManager.getInstance().sync(); CookieManager cm = CookieManager.getInstance(); String cookie = cm.getCookie(url); // Jsoup uses cookies as "name/value pairs" doc = Jsoup.connect("https://xxx.xxx.xx").cookie(url, cookie).get(); Elements elements = doc.select("span.tabCount"); String count = elements.first().text(); Log.d(TAG, "wart"+(count)); Log.d(TAG, "wartcookiedate:"+(cookie)); } catch (IOException e) { e.printStackTrace(); } } }; downloadThread.start(); 

Here is my second attempt with the code below. When the user is already logged in, it works great. My problem is that when the application starts, the string "count" will be returned null, since the user has not logged in yet. Therefore, an exception will be thrown that stops the entire scheduled Task Executor. Is there a way to just restart it if "count" is null?

 scheduleTaskExecutor= Executors.newScheduledThreadPool(5); // This schedule a task to run every 10 seconds: scheduleTaskExecutor.scheduleAtFixedRate(new Runnable() { public void run() { Document doc; doc = null; try { final String url = "https://xxx.xxx.xx"; // -- Android Cookie part here -- CookieSyncManager.getInstance().sync(); CookieManager cm = CookieManager.getInstance(); String cookie = cm.getCookie(url); // returns cookie for url // Jsoup uses cookies as "name/value pairs" doc = Jsoup.connect("https://xxx.xxx.xx").cookie(url, cookie).get(); Elements elements = doc.select("span.tabCount"); String count = elements.first().text(); Log.d(TAG, "wart"+(count)); Log.d(TAG, "wartcookiedate:"+(cookie)); } catch (IOException e) { e.printStackTrace(); } } }, 0, 10, TimeUnit.SECONDS); 
+4
source share
1 answer

Do not use an explicit thread with while + sleep to simulate a timer. It is ugly and unnecessary. There are more elegant ways to automatically schedule tasks every x time units, such as ScheduledThreadPoolExecutor .

+4
source

Source: https://habr.com/ru/post/1435343/


All Articles