performance - IntentService is hanging UI in android -
in intentservice using threadpoolexecutor poolsize 8 , maxpoolsize 10. when ever service started effect on ui. in runtask() method add tasks thread pool.
private threadpoolexecutor threadpool = null; private final linkedblockingqueue<runnable> threadsqueue = new linkedblockingqueue<runnable>(); private collection<future<?>> futures = new linkedlist<future<?>>(); public myservice(string name) { super(name); threadpool = new threadpoolexecutor(poolsize, maxpoolsize, keepalivetime, timeunit.seconds, threadsqueue); } public void runtask(runnable task) { futures.add(threadpool.submit(task)); } /** * when ever call method hold main thread untill tasks * in thread pool completed. */ public void waitforthreadpool() { (future<?> future : futures) { try { future.get(); } catch (interruptedexception e) { e.printstacktrace(); } catch (executionexception e) { e.printstacktrace(); } catch (exception e) { e.printstacktrace(); } } }
i suggest creating separate thread in service (service runs in ui thread) wait executors finish. how done it
@override public int onstartcommand(intent intent, int flags, int startid) { // check have here // ... if (state == state.idle) { state = state.in_progress; new thread() { @override public void run() { performandwait(); stopself(); } }.start(); } } private void performandwait() { //add tasks executorservice (string key : this.data.keyset()) { final job pending = new job(this.context, key, this.data.get(key)); try { this.service.submit(pending); } catch (rejectedexecutionexception e) { // rejected stuff go here next attempt when finishes this.rejected.add(pending); } } // wait service.shutdown(); try { service.awaittermination(3600, timeunit.seconds); } catch (interruptedexception e) { e.printstacktrace(); } }
Comments
Post a Comment