java - What is the way to run a new thread and a UI thread in Android? -
as far can understand in android when running processes start off in main thread. when doing heavier work use new thread. if modify ui appearance use run on ui.
can explain me these threads , how used?
the ui thread , main thread different names same thread.
all of ui inflation application done on main thread. reason delegate "heavier" work other threads because not want operations slow responsiveness , inflation time of ui.
you want run operations change ui or modify objects used ui on main thread.
an example asynctask
package com.wolfdev.warriormail; import android.app.activity; import android.content.intent; import android.os.bundle; import android.view.view; import android.view.view.onclicklistener; import android.view.animation.animation; import android.view.animation.animationutils; import android.widget.button; import android.widget.checkbox; import android.widget.edittext; public class loginactivity extends activity implements onclicklistener{ private button loginbutton; private edittext etext; private edittext ptext; private checkbox box; private string user; private string pass; @override public void oncreate(bundle savedinstancestate){ super.oncreate(savedinstancestate); setcontentview(r.layout.login); //initialize ui objects on main thread loginbutton = (button) findviewbyid(r.id.button1); loginbutton.setonclicklistener(this); etext = (edittext) findviewbyid(r.id.edittext1); ptext = (edittext) findviewbyid(r.id.edittext2); etext.clearfocus(); ptext.clearfocus(); animation fadein = animationutils.loadanimation(this,r.anim.fadeanimation); animation slidein = animationutils.loadanimation(this, r.anim.slideanimation); etext.startanimation(slidein); ptext.startanimation(slidein); box = (checkbox)findviewbyid(r.id.checkbox1); box.startanimation(fadein); login.startanimation(fadein); } @override public void onclick(view v) { user = email.gettext().tostring(); password = pass.gettext().tostring(); } class logintask extends asynctask<void,void,void>{ @override protected void doinbackground(void... args){ /* here heavy operation * in case, want validate users * credentials. if on main * thread, freeze ui. since * networking, forced on * different thread. */ return null; } @override protected void onpostexecute(void result){ /* function runs on main * thread, here notify user if * login successful or if failed. if * want update ui while in background * or thread completely, need * use handler. */ } } }
Comments
Post a Comment