Note that there are some explanatory texts on larger screens.

plurals
  1. POMain UI freezes even when tasks are handled by AsyncTask
    text
    copied!<p>I made <code>Service</code> that runs on the background collecting data from internet using <code>AsyncTask</code> and storing them in <code>Shared Preferences</code>. Even though the work is done in <code>AsyncTask</code> it still freezes my main activity.</p> <p>Here is the code for Service:</p> <pre><code>public class GetterService extends Service { SharedPreferences.Editor editor; HashMap&lt;Integer,String&gt; links = new HashMap&lt;Integer,String&gt;(); @Override public void onCreate() { editor = PreferenceManager.getDefaultSharedPreferences(this).edit(); populateLinks(); } private void populateLinks(){ // Here I add links to HashMap } @Override public IBinder onBind(Intent intent) { Toast.makeText(this, "GetterService ON BIND", Toast.LENGTH_LONG).show(); return null; } @Override public void onDestroy() { super.onDestroy(); Toast.makeText(this, "GetterService ON DESTROY", Toast.LENGTH_LONG).show(); } @Override public int onStartCommand(Intent intent, int flags, int startId) { doTasks(); return super.onStartCommand(intent, flags, startId); } @Override public boolean onUnbind(Intent intent) { Toast.makeText(this, "GetterService ON UNBIND", Toast.LENGTH_LONG).show(); return super.onUnbind(intent); } private void doTasks(){ for (Integer in : links.keySet()) { Document doc = null; try { doc = new NetTask().execute(links.get(in)).get(); } catch (InterruptedException e) { // TODO Auto-generated catch block e.printStackTrace(); } catch (ExecutionException e) { // TODO Auto-generated catch block e.printStackTrace(); } if (doc != null) { Elements names = doc.select("strong, li"); if(names != null &amp;&amp; names.size() &gt; 0) { for (int j = 0; j &lt; names.size(); j++) { editor.putString("header"+j, names.get(j).text().toString()); } } editor.commit(); } } } public class NetTask extends AsyncTask&lt;String, Integer, Document&gt; { @Override protected Document doInBackground(String... params) { Document doc = null; try { doc = Jsoup.connect(params[0]).timeout(5000).get(); } catch (IOException e) { // TODO Auto-generated catch block e.printStackTrace(); } return doc; } } } </code></pre> <p>and here is how I start the service from main activity:</p> <pre><code>Intent startServiceIntent = new Intent(this, GetterService.class); this.startService(startServiceIntent); </code></pre>
 

Querying!

 
Guidance

SQuiL has stopped working due to an internal error.

If you are curious you may find further information in the browser console, which is accessible through the devtools (F12).

Reload