【Android开发艺术探索】理解Window和WindowManager
个人博客:
理解window和windowmanager
window表示一个窗口的概念,是一个抽象类,具体实现是phonewindow,可以通过windowmanager创建一个window。windowmanager是外界访问window的入口,window具体实现位于windowmanagerservice中,windowmanager和windowmanagerservice的交互是一个ipc过程。
window和windowmanager
windowmanager.layoutparams
关注flags和type两个参数:
flags参数表示window的属性,可以控制window的显示特性。
** flag_not_focusable **
表示window不需要获取焦点,也不需要接收各种输入事件,此标记会同时启用flag_not_touch_modal,最终事件会直接传递给下层的具有焦点的window。
** flag_not_touch_modal **
系统会将当前window区域以外的单击事件传递给底层的window,当前window区域以内的单击事件自己处理。
** flag_show_when_locked **
让window显示在锁屏的界面上。
type参数表示window类型
window有三种类型:应用window、子window、系统window。应用window对应一个activity。子window不能单独存在,需要附属在特定的父window中,如dialog就是子window。系统window需要声明权限才能创建,如toast和系统状态栏就是系统window。
window是分层的,每个window都有对应的z-ordered,层级大的覆盖在层级小的window上。应用window的层级范围是1-99,子window的层级范围是1000-1999,系统window层级范围是2000-2999。
windowmanager常用的三个方法:添加view、更新view和删除view。这是从viewmanager实现过来的。
public interface viewmanager { public void addview(view view, viewgroup.layoutparams params); public void updateviewlayout(view view, viewgroup.layoutparams params); public void removeview(view view); }
window的内部机制
window是一个抽象概念,每一个window都对应一个view和一个viewrootimpl,window和view通过viewrootimpl来建立联系。
window的添加过程
window的添加过程需要通过windowmanager的addview来实现。windowmanager是一个接口,它的实现类是windowmanagerimpl。
public void addview(view view, layoutparams params) { this.applydefaulttoken(params); this.mglobal.addview(view, params, this.mcontext.getdisplay(), this.mparentwindow); }
windowmanagerimpl并没有直接实现addview,而是通过内部的windowmanagerglobal实现的。
public void addview(view view, android.view.viewgroup.layoutparams params, display display, window parentwindow) { if (view == null) { //检查view throw new illegalargumentexception("view must not be null"); } else if (display == null) { //检查display throw new illegalargumentexception("display must not be null"); } else if (!(params instanceof layoutparams)) { //检查params throw new illegalargumentexception("params must be windowmanager.layoutparams"); } else { layoutparams wparams = (layoutparams)params; if (parentwindow != null) { //调整子窗口的布局参数 parentwindow.adjustlayoutparamsforsubwindow(wparams); } else { context context = view.getcontext(); if (context != null && (context.getapplicationinfo().flags & 536870912) != 0) { wparams.flags |= 16777216; } } view panelparentview = null; int index; viewrootimpl root; synchronized(this.mlock) { if (this.msystempropertyupdater == null) { this.msystempropertyupdater = new runnable() { public void run() { synchronized(windowmanagerglobal.this.mlock) { for(int i = windowmanagerglobal.this.mroots.size() - 1; i >= 0; --i) { ((viewrootimpl)windowmanagerglobal.this.mroots.get(i)).loadsystemproperties(); } } } }; systemproperties.addchangecallback(this.msystempropertyupdater); } int index = this.findviewlocked(view, false); if (index >= 0) { if (!this.mdyingviews.contains(view)) { //不允许重复添加窗口 throw new illegalstateexception("view " + view + " has already been added to the window manager."); } ((viewrootimpl)this.mroots.get(index)).dodie(); } if (wparams.type >= 1000 && wparams.type <= 1999) { index = this.mviews.size(); for(int i = 0; i < index; ++i) { if (((viewrootimpl)this.mroots.get(i)).mwindow.asbinder() == wparams.token) { panelparentview = (view)this.mviews.get(i); } } } //创建viewrootimpl root = new viewrootimpl(view.getcontext(), display); //设置layoutparams view.setlayoutparams(wparams); this.mviews.add(view); this.mroots.add(root); this.mparams.add(wparams); } try { //viewrootimpl添加view root.setview(view, wparams, panelparentview); } catch (runtimeexception var15) { synchronized(this.mlock) { index = this.findviewlocked(view, false); if (index >= 0) { this.removeviewlocked(index, true); } } throw var15; } } }
viewrootimpl调用setview方法
public void setview(view view, layoutparams attrs, view panelparentview) { synchronized(this) { if (this.mview == null) { //... this.madded = true; //1、调用requestlayout方法 this.requestlayout(); //... int res; try { this.morigwindowtype = this.mwindowattributes.type; this.mattachinfo.mrecomputeglobalattributes = true; this.collectviewattributes(); //2、通过session添加window res = this.mwindowsession.addtodisplay(this.mwindow, this.mseq, this.mwindowattributes, this.gethostvisibility(), this.mdisplay.getdisplayid(), this.mattachinfo.mcontentinsets, this.mattachinfo.mstableinsets, this.mattachinfo.moutsets, this.minputchannel); } catch (remoteexception var20) { this.madded = false; this.mview = null; this.mattachinfo.mrootview = null; this.minputchannel = null; this.mfallbackeventhandler.setview((view)null); this.unscheduletraversals(); this.setaccessibilityfocus((view)null, (accessibilitynodeinfo)null); throw new runtimeexception("adding window failed", var20); } finally { if (restore) { attrs.restore(); } } //... if (res < 0) { //添加window失败 this.mattachinfo.mrootview = null; this.madded = false; this.mfallbackeventhandler.setview((view)null); this.unscheduletraversals(); this.setaccessibilityfocus((view)null, (accessibilitynodeinfo)null); switch(res) { case -10: throw new invaliddisplayexception("unable to add window " + this.mwindow + " -- the specified window type " + this.mwindowattributes.type + " is not valid"); case -9: throw new invaliddisplayexception("unable to add window " + this.mwindow + " -- the specified display can not be found"); case -8: throw new badtokenexception("unable to add window " + this.mwindow + " -- permission denied for window type " + this.mwindowattributes.type); case -7: throw new badtokenexception("unable to add window " + this.mwindow + " -- another window of type " + this.mwindowattributes.type + " already exists"); case -6: return; case -5: throw new badtokenexception("unable to add window -- window " + this.mwindow + " has already been added"); case -4: throw new badtokenexception("unable to add window -- app for token " + attrs.token + " is exiting"); case -3: throw new badtokenexception("unable to add window -- token " + attrs.token + " is not for an application"); case -2: case -1: if (view.getcontext().getpackagename().startswith("com.google.android.gms")) { try { if (appglobals.getpackagemanager().isfirstboot()) { log.d(this.mtag, "firstboot crash return"); return; } } catch (remoteexception var22) { var22.printstacktrace(); return; } } throw new badtokenexception("unable to add window -- token " + attrs.token + " is not valid; is your activity running?"); default: throw new runtimeexception("unable to add window -- unknown error code " + res); } } //... //将view和viewrootimpl关联起来 view.assignparent(this); //... } } }
1、requestlayout方法
public void requestlayout() { if (!this.mhandlinglayoutinlayoutrequest) { //a检测线程 this.checkthread(); this.mlayoutrequested = true; //b开始view的绘制 this.scheduletraversals(); } }
a:检测线程,如果不是主线程,则报错。
void checkthread() { if (this.mthread != thread.currentthread()) { throw new viewrootimpl.calledfromwrongthreadexception("only the original thread that created a view hierarchy can touch its views."); } }
b:开始view的绘制
void scheduletraversals() { if (!this.mtraversalscheduled) { this.mtraversalscheduled = true; this.mtraversalbarrier = this.mhandler.getlooper().getqueue().postsyncbarrier(); //回调mtraversalrunnable this.mchoreographer.postcallback(2, this.mtraversalrunnable, (object)null); if (!this.munbufferedinputdispatch) { this.scheduleconsumebatchedinput(); } this.notifyrendererofframepending(); this.pokedrawlockifneeded(); } }
回调mtraversalrunnable
final class traversalrunnable implements runnable { traversalrunnable() { } public void run() { //调用dotraversal viewrootimpl.this.dotraversal(); } }
调用dotraversal
void dotraversal() { if (this.mtraversalscheduled) { this.mtraversalscheduled = false; this.mhandler.getlooper().getqueue().removesyncbarrier(this.mtraversalbarrier); if (this.mprofile) { debug.startmethodtracing("viewancestor"); } //调用performtraversals this.performtraversals(); if (this.mprofile) { debug.stopmethodtracing(); this.mprofile = false; } } }
调用performtraversals方法,在performtraversals方法内会调用performmeasure()、performlayout()、performdraw(),并最终会调用view的measure()、layout()、draw()方法
回到viewrootimpl的setview方法,在2处通过windowsession调用addtodisplay()方法,windowsession是一个binder对象,最终的实现为session类。session中的addtodisplay方法:
@override public int addtodisplay(iwindow window, int seq, windowmanager.layoutparams attrs, int viewvisibility, int displayid, rect outcontentinsets, rect outstableinsets, rect outoutsets, inputchannel outinputchannel) { return mservice.addwindow(this, window, seq, attrs, viewvisibility, displayid, outcontentinsets, outstableinsets, outoutsets, outinputchannel); }
addtodisplay方法通过调用windowmanagerservice的addwindow方法。具体的addwindow方法,此处不再分析。
window的删除过程
window的删除过程和添加过程基本一样,都是先通过windowmanagerimpl,再通过windowmanagerglobal来实现的。
public void removeview(view view, boolean immediate) { if (view == null) { throw new illegalargumentexception("view must not be null"); } else { synchronized(this.mlock) { int index = this.findviewlocked(view, true); view curview = ((viewrootimpl)this.mroots.get(index)).getview(); this.removeviewlocked(index, immediate); if (curview != view) { throw new illegalstateexception("calling with view " + view + " but the viewancestor is attached to " + curview); } } } }
removeview方法中又调用removeviewlocked方法
private void removeviewlocked(int index, boolean immediate) { viewrootimpl root = (viewrootimpl)this.mroots.get(index); view view = root.getview(); if (view != null) { inputmethodmanager imm = inputmethodmanager.getinstance(); if (imm != null) { imm.windowdismissed(((view)this.mviews.get(index)).getwindowtoken()); } } boolean deferred = root.die(immediate); if (view != null) { view.assignparent((viewparent)null); if (deferred) { this.mdyingviews.add(view); } } }
在removeviewlocked方法里调用viewrootimpl的die方法
boolean die(boolean immediate) { if (immediate && !this.misintraversal) { this.dodie(); return false; } else { if (!this.misdrawing) { this.destroyhardwarerenderer(); } else { log.e(this.mtag, "attempting to destroy the window while drawing!\n window=" + this + ", title=" + this.mwindowattributes.gettitle()); } this.mhandler.sendemptymessage(3); return true; } }
die方法中,如果不是立即移除,则通过handler发送一个移除消息,如果是立即移除,则调用dodie方法
void dodie() { //检查线程 this.checkthread(); synchronized(this) { if (this.mremoved) { return; } this.mremoved = true; if (this.madded) { this.dispatchdetachedfromwindow(); } if (this.madded && !this.mfirst) { this.destroyhardwarerenderer(); if (this.mview != null) { int viewvisibility = this.mview.getvisibility(); boolean viewvisibilitychanged = this.mviewvisibility != viewvisibility; if (this.mwindowattributeschanged || viewvisibilitychanged) { try { if ((this.relayoutwindow(this.mwindowattributes, viewvisibility, false) & 2) != 0) { this.mwindowsession.finishdrawing(this.mwindow); } } catch (remoteexception var6) { } } this.msurface.release(); } } this.madded = false; } windowmanagerglobal.getinstance().doremoveview(this); }
真正移除window是在dispatchdetachedfromwindow方法中实现的
void dispatchdetachedfromwindow() { if (this.mview != null && this.mview.mattachinfo != null) { this.mattachinfo.mtreeobserver.dispatchonwindowattachedchange(false); this.mview.dispatchdetachedfromwindow(); } this.maccessibilityinteractionconnectionmanager.ensurenoconnection(); this.maccessibilitymanager.removeaccessibilitystatechangelistener(this.maccessibilityinteractionconnectionmanager); this.maccessibilitymanager.removehightextcontraststatechangelistener(this.mhighcontrasttextmanager); this.removesendwindowcontentchangedcallback(); this.destroyhardwarerenderer(); this.setaccessibilityfocus((view)null, (accessibilitynodeinfo)null); this.mview.assignparent((viewparent)null); this.mview = null; this.mattachinfo.mrootview = null; this.msurface.release(); if (this.minputqueuecallback != null && this.minputqueue != null) { this.minputqueuecallback.oninputqueuedestroyed(this.minputqueue); this.minputqueue.dispose(); this.minputqueuecallback = null; this.minputqueue = null; } if (this.minputeventreceiver != null) { this.minputeventreceiver.dispose(); this.minputeventreceiver = null; } try { this.mwindowsession.remove(this.mwindow); } catch (remoteexception var2) { } if (this.minputchannel != null) { this.minputchannel.dispose(); this.minputchannel = null; } this.mdisplaymanager.unregisterdisplaylistener(this.mdisplaylistener); this.unscheduletraversals(); }
在dispatchdetachedfromwindow中,最终通过session来移除window。
移除window后,调用windowmanagerglobal的doremoveview方法将之前列表中的记录清除
void doremoveview(viewrootimpl root) { synchronized(this.mlock) { int index = this.mroots.indexof(root); if (index >= 0) { this.mroots.remove(index); this.mparams.remove(index); view view = (view)this.mviews.remove(index); this.mdyingviews.remove(view); } } if (threadedrenderer.strimforeground && threadedrenderer.isavailable()) { this.dotrimforeground(); } }
window的更新过程
window的更新是通过windowmanagerglobal的updateviewlayout方法来实现的
public void updateviewlayout(view view, android.view.viewgroup.layoutparams params) { if (view == null) { throw new illegalargumentexception("view must not be null"); } else if (!(params instanceof layoutparams)) { throw new illegalargumentexception("params must be windowmanager.layoutparams"); } else { layoutparams wparams = (layoutparams)params; view.setlayoutparams(wparams); synchronized(this.mlock) { int index = this.findviewlocked(view, true); viewrootimpl root = (viewrootimpl)this.mroots.get(index); this.mparams.remove(index); this.mparams.add(index, wparams); root.setlayoutparams(wparams, false); } } }
window创建过程
activity的window创建过程
先说明activity的创建过程。activity是在activitythread的performlaunchactivity方法中创建的。
private activity performlaunchactivity(activityclientrecord r, intent customintent) { //... contextimpl appcontext = createbasecontextforactivity(r); activity activity = null; try { java.lang.classloader cl = appcontext.getclassloader(); //创建activity activity = minstrumentation.newactivity( cl, component.getclassname(), r.intent); strictmode.incrementexpectedactivitycount(activity.getclass()); r.intent.setextrasclassloader(cl); r.intent.preparetoenterprocess(); if (r.state != null) { r.state.setclassloader(cl); } } catch (exception e) { if (!minstrumentation.onexception(activity, e)) { throw new runtimeexception( "unable to instantiate activity " + component + ": " + e.tostring(), e); } } try { application app = r.packageinfo.makeapplication(false, minstrumentation); if (locallogv) slog.v(tag, "performing launch of " + r); if (locallogv) slog.v( tag, r + ": app=" + app + ", appname=" + app.getpackagename() + ", pkg=" + r.packageinfo.getpackagename() + ", comp=" + r.intent.getcomponent().toshortstring() + ", dir=" + r.packageinfo.getappdir()); if (activity != null) { charsequence title = r.activityinfo.loadlabel(appcontext.getpackagemanager()); configuration config = new configuration(mcompatconfiguration); if (r.overrideconfig != null) { config.updatefrom(r.overrideconfig); } if (debug_configuration) slog.v(tag, "launching activity " + r.activityinfo.name + " with config " + config); window window = null; //创建window if (r.mpendingremovewindow != null && r.mpreservewindow) { window = r.mpendingremovewindow; r.mpendingremovewindow = null; r.mpendingremovewindowmanager = null; } appcontext.setoutercontext(activity); //将activity和window关联起来 activity.attach(appcontext, this, getinstrumentation(), r.token, r.ident, app, r.intent, r.activityinfo, title, r.parent, r.embeddedid, r.lastnonconfigurationinstances, config, r.referrer, r.voiceinteractor, window, r.configcallback); //... } catch (supernotcalledexception e) { throw e; } catch (exception e) { if (!minstrumentation.onexception(activity, e)) { throw new runtimeexception( "unable to start activity " + component + ": " + e.tostring(), e); } } return activity; }
activity的attach方法
final void attach(context context, activitythread athread, instrumentation instr, ibinder token, int ident, application application, intent intent, activityinfo info, charsequence title, activity parent, string id, nonconfigurationinstances lastnonconfigurationinstances, configuration config, string referrer, ivoiceinteractor voiceinteractor, window window, activityconfigcallback activityconfigcallback) { attachbasecontext(context); mfragments.attachhost(null /*parent*/); //创建window mwindow = new phonewindow(this, window, activityconfigcallback); mwindow.setwindowcontrollercallback(this); mwindow.setcallback(this); mwindow.setonwindowdismissedcallback(this); mwindow.getlayoutinflater().setprivatefactory(this); //... //设置windowmanager mwindow.setwindowmanager( (windowmanager)context.getsystemservice(context.window_service), mtoken, mcomponent.flattentostring(), (info.flags & activityinfo.flag_hardware_accelerated) != 0); if (mparent != null) { mwindow.setcontainer(mparent.getwindow()); } mwindowmanager = mwindow.getwindowmanager(); mcurrentconfig = config; mwindow.setcolormode(info.colormode); setautofillcompatibilityenabled(application.isautofillcompatibilityenabled()); enableautofillcompatibilityifneeded(); }
window创建完成后,在activity的setcontentview方法中,将view附加到window中的decorview上。
public void setcontentview(@layoutres int layoutresid) { getwindow().setcontentview(layoutresid); initwindowdecoractionbar(); }
window的唯一实现类为phonewindow,因此查看phonewindow的setcontentview方法
public void setcontentview(int layoutresid) { if (this.mcontentparent == null) { //如果没有decorview,则创建 this.installdecor(); } else if (!this.hasfeature(12)) { this.mcontentparent.removeallviews(); } if (this.hasfeature(12)) { scene newscene = scene.getsceneforlayout(this.mcontentparent, layoutresid, this.getcontext()); this.transitionto(newscene); } else { this.mlayoutinflater.inflate(layoutresid, this.mcontentparent); } this.mcontentparent.requestapplyinsets(); android.view.window.callback cb = this.getcallback(); if (cb != null && !this.isdestroyed()) { cb.oncontentchanged(); } this.mcontentparentexplicitlyset = true; }
view被添加到window中的decorview后,window并没有马上被添加。在activity的onresume方法中,通过调用makevisible方法才被添加。
void makevisible() { if (!mwindowadded) { viewmanager wm = getwindowmanager(); wm.addview(mdecor, getwindow().getattributes()); mwindowadded = true; } mdecor.setvisibility(view.visible); }
dialog的window创建过程
1、创建window
dialog(@nonnull context context, @styleres int themeresid, boolean createcontextthemewrapper) { if (createcontextthemewrapper) { if (themeresid == resourceid.id_null) { final typedvalue outvalue = new typedvalue(); context.gettheme().resolveattribute(r.attr.dialogtheme, outvalue, true); themeresid = outvalue.resourceid; } mcontext = new contextthemewrapper(context, themeresid); } else { mcontext = context; } mwindowmanager = (windowmanager) context.getsystemservice(context.window_service); //创建window final window w = new phonewindow(mcontext); mwindow = w; w.setcallback(this); w.setonwindowdismissedcallback(this); w.setonwindowswipedismissedcallback(() -> { if (mcancelable) { cancel(); } }); w.setwindowmanager(mwindowmanager, null, null); w.setgravity(gravity.center); mlistenershandler = new listenershandler(this); }
2、初始化decorview并将dialog的视图添加到decorview中
public void setcontentview(@layoutres int layoutresid) { mwindow.setcontentview(layoutresid); }
3、将decorview添加到window
public void show() { //... mwindowmanager.addview(mdecor, l); mshowing = true; sendshowmessage(); }
普通dialog必须采用activity的context。
toast的window创建过程
toast也是基于window来实现,但由于toast具有定时取消功能,所以系统采用了handler。
toast的显示
public void show() { if (mnextview == null) { throw new runtimeexception("setview must have been called"); } inotificationmanager service = getservice(); string pkg = mcontext.getoppackagename(); tn tn = mtn; tn.mnextview = mnextview; try { service.enqueuetoast(pkg, tn, mduration); } catch (remoteexception e) { // empty } }
在show方法中,通过ipc调用notificationmanager的enqueuetoast方法
@override public void enqueuetoast(string pkg, itransientnotification callback, int duration) { if (dbg) { slog.i(tag, "enqueuetoast pkg=" + pkg + " callback=" + callback + " duration=" + duration); } if (pkg == null || callback == null) { slog.e(tag, "not doing toast. pkg=" + pkg + " callback=" + callback); return ; } final boolean issystemtoast = iscallersystemorphone() || ("android".equals(pkg)); final boolean ispackagesuspended = ispackagesuspendedforuser(pkg, binder.getcallinguid()); if (enable_blocked_toasts && !issystemtoast && (!arenotificationsenabledforpackage(pkg, binder.getcallinguid()) || ispackagesuspended)) { slog.e(tag, "suppressing toast from package " + pkg + (ispackagesuspended ? " due to package suspended by administrator." : " by user request.")); return; } synchronized (mtoastqueue) { int callingpid = binder.getcallingpid(); long callingid = binder.clearcallingidentity(); try { toastrecord record; int index; // all packages aside from the android package can enqueue one toast at a time if (!issystemtoast) { index = indexoftoastpackagelocked(pkg); } else { index = indexoftoastlocked(pkg, callback); } // if the package already has a toast, we update its toast // in the queue, we don't move it to the end of the queue. if (index >= 0) { record = mtoastqueue.get(index); record.update(duration); record.update(callback); } else { binder token = new binder(); mwindowmanagerinternal.addwindowtoken(token, type_toast, default_display); record = new toastrecord(callingpid, pkg, callback, duration, token); mtoastqueue.add(record); index = mtoastqueue.size() - 1; } keepprocessaliveifneededlocked(callingpid); // if it's at index 0, it's the current toast. it doesn't matter if it's // new or just been updated. call back and tell it to show itself. // if the callback fails, this will remove it from the list, so don't // assume that it's valid after this. if (index == 0) { shownexttoastlocked(); } } finally { binder.restorecallingidentity(callingid); } } }
shownexttoastlocked方法
@guardedby("mtoastqueue") void shownexttoastlocked() { toastrecord record = mtoastqueue.get(0); while (record != null) { if (dbg) slog.d(tag, "show pkg=" + record.pkg + " callback=" + record.callback); try { record.callback.show(record.token); scheduletimeoutlocked(record); return; } catch (remoteexception e) { slog.w(tag, "object died trying to show notification " + record.callback + " in package " + record.pkg); // remove it from the list and let the process die int index = mtoastqueue.indexof(record); if (index >= 0) { mtoastqueue.remove(index); } keepprocessaliveifneededlocked(record.pid); if (mtoastqueue.size() > 0) { record = mtoastqueue.get(0); } else { record = null; } } } }
通过record.callback,即toast中的tn对象,调用show方法
@override public void show(ibinder windowtoken) { if (locallogv) log.v(tag, "show: " + this); mhandler.obtainmessage(show, windowtoken).sendtotarget(); }
通过handler发送消息,然后在处理消息的逻辑中调用了handleshow
public void handleshow(ibinder windowtoken) { if (locallogv) log.v(tag, "handle show: " + this + " mview=" + mview + " mnextview=" + mnextview); // if a cancel/hide is pending - no need to show - at this point // the window token is already invalid and no need to do any work. if (mhandler.hasmessages(cancel) || mhandler.hasmessages(hide)) { return; } if (mview != mnextview) { // remove the old view if necessary handlehide(); mview = mnextview; context context = mview.getcontext().getapplicationcontext(); string packagename = mview.getcontext().getoppackagename(); if (context == null) { context = mview.getcontext(); } mwm = (windowmanager)context.getsystemservice(context.window_service); // we can resolve the gravity here by using the locale for getting // the layout direction final configuration config = mview.getcontext().getresources().getconfiguration(); final int gravity = gravity.getabsolutegravity(mgravity, config.getlayoutdirection()); mparams.gravity = gravity; if ((gravity & gravity.horizontal_gravity_mask) == gravity.fill_horizontal) { mparams.horizontalweight = 1.0f; } if ((gravity & gravity.vertical_gravity_mask) == gravity.fill_vertical) { mparams.verticalweight = 1.0f; } mparams.x = mx; mparams.y = my; mparams.verticalmargin = mverticalmargin; mparams.horizontalmargin = mhorizontalmargin; mparams.packagename = packagename; mparams.hidetimeoutmilliseconds = mduration == toast.length_long ? long_duration_timeout : short_duration_timeout; mparams.token = windowtoken; if (mview.getparent() != null) { if (locallogv) log.v(tag, "remove! " + mview + " in " + this); mwm.removeview(mview); } if (locallogv) log.v(tag, "add! " + mview + " in " + this); // since the notification manager service cancels the token right // after it notifies us to cancel the toast there is an inherent // race and we may attempt to add a window after the token has been // invalidated. let us hedge against that. try { mwm.addview(mview, mparams); trysendaccessibilityevent(); } catch (windowmanager.badtokenexception e) { /* ignore */ } } }
在handleshow方法中,将view添加到了window。
上一篇: Modbus协议和应用开发介绍