Android Window 9问9答
1.简述一下window是什么?在android体系里 扮演什么角色?
答:window就是一个抽象类,他的实现类是phoneWindow。我们一般通过windowManager 来访问window。就是windowmanager 和windowmanagerservice的交互。
此外 android中 你所有能看到的视图,activity,dialog,toast等 都是附加在window上的。window就是view的直接管理者。
2.如何使用windowmanager添加一个view?
答:
Button bt = new Button(this);
bt.setText("button here");
WindowManager.LayoutParams layoutParams = new WindowManager.LayoutParams(WindowManager.LayoutParams.WRAP_CONTENT, WindowManager.LayoutParams.WRAP_CONTENT,
0, 0, PixelFormat.TRANSPARENT);
layoutParams.flags = WindowManager.LayoutParams.FLAG_NOT_TOUCH_MODAL | WindowManager.LayoutParams.FLAG_NOT_FOCUSABLE | WindowManager.LayoutParams.FLAG_SHOW_WHEN_LOCKED;
layoutParams.x = 300;
layoutParams.y = 300;
layoutParams.gravity = Gravity.RIGHT | Gravity.TOP;
getWindowManager().addView(bt, layoutParams);
3.总共有几种window类型?
答:三种。应用window,就是activity这种类型。子window,就是dialog这种,系统类,toast,状态栏就是系统类型window。
每种对对应着层级范围,应用1-99 子1000-1999 系统 2000-2999.层级最大的,就是显示在最顶层的window了。
4.使用系统window需要注意什么?
答:注意system_alert_window这个权限。否则要出错
5.尝试简单分析window的添加过程?
答:即window.addView()函数的执行过程:
//首先我们要知道 windwmanger本身就是一个接口,他的实现是交给WindowManagerImpl 来做的。
public final class WindowManagerImpl implements WindowManager { //他的view方法 一看,发现也是基本没做实际的addview操作 是交给mGlobal来做的
@Override
public void addView(@NonNull View view, @NonNull ViewGroup.LayoutParams params) {
applyDefaultToken(params);
mGlobal.addView(view, params, mDisplay, mParentWindow);
} //发现这是一个工厂吗,到这里一看就明白了,WindowManagerImpl的实际操作 都桥接给了WindowManagerGlobal来处理
private final WindowManagerGlobal mGlobal = WindowManagerGlobal.getInstance(); //先看一下WindowManagerGlobal的 重要变量,注意上面已经分析过了,WindowManagerGlobal本身自己是一个单例,全局唯一,
//所以下面这些参数list ,全局也是唯一的,mViews 就是所有window对应的view,mRoots就是所有viewRootImpl,mParams就是这些
//view的参数,dyingviews 就是正在删除的对象,就是那种你调用了remove操作 但是remove还没有操作完毕的那些view
private final ArrayList<View> mViews = new ArrayList<View>();
private final ArrayList<ViewRootImpl> mRoots = new ArrayList<ViewRootImpl>();
private final ArrayList<WindowManager.LayoutParams> mParams =
new ArrayList<WindowManager.LayoutParams>();
private final ArraySet<View> mDyingViews = new ArraySet<View>(); //所以 我们就看看WindowManagerGlobal源码里的addView是如何实现的
public void addView(View view, ViewGroup.LayoutParams params,
Display display, Window parentWindow) {
if (view == null) {
throw new IllegalArgumentException("view must not be null");
}
if (display == null) {
throw new IllegalArgumentException("display must not be null");
}
if (!(params instanceof WindowManager.LayoutParams)) {
throw new IllegalArgumentException("Params must be WindowManager.LayoutParams");
} final WindowManager.LayoutParams wparams = (WindowManager.LayoutParams)params;
//如果是子window 就调整一下参数
if (parentWindow != null) {
parentWindow.adjustLayoutParamsForSubWindow(wparams);
} else {
// If there's no parent and we're running on L or above (or in the
// system context), assume we want hardware acceleration.
final Context context = view.getContext();
if (context != null
&& context.getApplicationInfo().targetSdkVersion >= Build.VERSION_CODES.LOLLIPOP) {
wparams.flags |= WindowManager.LayoutParams.FLAG_HARDWARE_ACCELERATED;
}
} ViewRootImpl root;
View panelParentView = null; synchronized (mLock) {
// Start watching for system property changes.
if (mSystemPropertyUpdater == null) {
mSystemPropertyUpdater = new Runnable() {
@Override public void run() {
synchronized (mLock) {
for (int i = mRoots.size() - 1; i >= 0; --i) {
mRoots.get(i).loadSystemProperties();
}
}
}
};
SystemProperties.addChangeCallback(mSystemPropertyUpdater);
} int index = findViewLocked(view, false);
if (index >= 0) {
if (mDyingViews.contains(view)) {
// Don't wait for MSG_DIE to make it's way through root's queue.
mRoots.get(index).doDie();
} else {
throw new IllegalStateException("View " + view
+ " has already been added to the window manager.");
}
// The previous removeView() had not completed executing. Now it has.
} // If this is a panel window, then find the window it is being
// attached to for future reference.
if (wparams.type >= WindowManager.LayoutParams.FIRST_SUB_WINDOW &&
wparams.type <= WindowManager.LayoutParams.LAST_SUB_WINDOW) {
final int count = mViews.size();
for (int i = 0; i < count; i++) {
if (mRoots.get(i).mWindow.asBinder() == wparams.token) {
panelParentView = mViews.get(i);
}
}
} //这个代码充分说明了每一个window都对应着一个view 和一个viewrootIMPL,window本身自己不存在,
//他的意义就在于管理view,而管理view 就要通过windowmanager 最终走到windwmanagerglobal这里来完成管理
root = new ViewRootImpl(view.getContext(), display); view.setLayoutParams(wparams); mViews.add(view);
mRoots.add(root);
mParams.add(wparams);
} // do this last because it fires off messages to start doing things
try {
//view的最终绘制 是在viewrootimpl里完成的,所以这里view的绘制也是在这个里面完成的
//我们在viewrootimpl里能找到setview的源码 他在这个函数里调用了requetlayout
root.setView(view, wparams, panelParentView);
} catch (RuntimeException e) {
// BadTokenException or InvalidDisplayException, clean up.
synchronized (mLock) {
final int index = findViewLocked(view, false);
if (index >= 0) {
removeViewLocked(index, true);
}
}
throw e;
}
} //而requestLayout里有scheduleTraversals方法 这个就是view绘制的入口处
public void requestLayout() {
if (!mHandlingLayoutInLayoutRequest) {
checkThread();
mLayoutRequested = true;
scheduleTraversals();
}
} //回到前面提到的setView那个函数
//我们可以看到requestLayout 结束以后 mWindowSession.addToDisplay 就有了这个方法的调用
//实际上这个方法 完成的就是一个window的添加。
requestLayout();
if ((mWindowAttributes.inputFeatures
& WindowManager.LayoutParams.INPUT_FEATURE_NO_INPUT_CHANNEL) == 0) {
mInputChannel = new InputChannel();
}
try {
mOrigWindowType = mWindowAttributes.type;
mAttachInfo.mRecomputeGlobalAttributes = true;
collectViewAttributes();
res = mWindowSession.addToDisplay(mWindow, mSeq, mWindowAttributes,
getHostVisibility(), mDisplay.getDisplayId(),
mAttachInfo.mContentInsets, mAttachInfo.mStableInsets, mInputChannel); //然后我们很容易就发现这是一个接口 并且代码一看就知道 还是一个binder
//所以实际上添加window的功能 就是通过BInder 是调用windwmangerservice的方法 来完成的
public interface IWindowSession extends android.os.IInterface
{
/** Local-side IPC implementation stub class. */
public static abstract class Stub extends android.os.Binder implements android.view.IWindowSession
{
private static final java.lang.String DESCRIPTOR = "android.view.IWindowSession";
/** Construct the stub at attach it to the interface. */
public Stub()
{
this.attachInterface(this, DESCRIPTOR);
}
6.activity的window是如何创建的?
答:应用类的window创建过程:
//activity的window创建 由activityThread的performLaunchActivity 方法开始
private Activity performLaunchActivity(ActivityClientRecord r, Intent customIntent) {
......
if (activity != null) {
Context appContext = createBaseContextForActivity(r, activity);
CharSequence title = r.activityInfo.loadLabel(appContext.getPackageManager());
Configuration config = new Configuration(mCompatConfiguration);
if (DEBUG_CONFIGURATION) Slog.v(TAG, "Launching activity "
+ r.activityInfo.name + " with config " + config);
//其中最主要的就是attach方法 注意是调用的activity的attach方法 不是activitytherad的
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); ...... return activity;
} 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) {
attachBaseContext(context); mFragments.attachActivity(this, mContainer, null);
//这里一下就能看出来 Acitity的window对象 是由PolicyManager的makeNewWindow方法构造出来
//有兴趣的还可以看一下 这里set了很多接口 都是我们熟悉的那些方法
mWindow = PolicyManager.makeNewWindow(this);
mWindow.setCallback(this);
mWindow.setOnWindowDismissedCallback(this);
mWindow.getLayoutInflater().setPrivateFactory(this);
if (info.softInputMode != WindowManager.LayoutParams.SOFT_INPUT_STATE_UNSPECIFIED) {
mWindow.setSoftInputMode(info.softInputMode);
}
if (info.uiOptions != 0) {
mWindow.setUiOptions(info.uiOptions);
}
mUiThread = Thread.currentThread(); mMainThread = aThread;
mInstrumentation = instr;
mToken = token;
mIdent = ident;
mApplication = application;
mIntent = intent;
mReferrer = referrer;
mComponent = intent.getComponent();
mActivityInfo = info;
mTitle = title;
mParent = parent;
mEmbeddedID = id;
mLastNonConfigurationInstances = lastNonConfigurationInstances;
if (voiceInteractor != null) {
if (lastNonConfigurationInstances != null) {
mVoiceInteractor = lastNonConfigurationInstances.voiceInteractor;
} else {
mVoiceInteractor = new VoiceInteractor(voiceInteractor, this, this,
Looper.myLooper());
}
} 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;
} //makenewWindow就是在这里被调用的,可以看出来 makenewWindow返回的 正是phoneWindow对象
//到这里我们的window对象就生成了,
public class Policy implements IPolicy {
private static final String TAG = "PhonePolicy"; private static final String[] preload_classes = {
"com.android.internal.policy.impl.PhoneLayoutInflater",
"com.android.internal.policy.impl.PhoneWindow",
"com.android.internal.policy.impl.PhoneWindow$1",
"com.android.internal.policy.impl.PhoneWindow$DialogMenuCallback",
"com.android.internal.policy.impl.PhoneWindow$DecorView",
"com.android.internal.policy.impl.PhoneWindow$PanelFeatureState",
"com.android.internal.policy.impl.PhoneWindow$PanelFeatureState$SavedState",
}; static {
// For performance reasons, preload some policy specific classes when
// the policy gets loaded.
for (String s : preload_classes) {
try {
Class.forName(s);
} catch (ClassNotFoundException ex) {
Log.e(TAG, "Could not preload class for phone policy: " + s);
}
}
} public Window makeNewWindow(Context context) {
return new PhoneWindow(context);
} public LayoutInflater makeNewLayoutInflater(Context context) {
return new PhoneLayoutInflater(context);
} public WindowManagerPolicy makeNewWindowManager() {
return new PhoneWindowManager();
} public FallbackEventHandler makeNewFallbackEventHandler(Context context) {
return new PhoneFallbackEventHandler(context);
}
} //再看activity的方法 就是在这里把我们的布局文件和window给关联了起来
//我们上面已经知道window对象就是phonewindow 所以这里就要看看phonewindow的setContentView方法
public void setContentView(@LayoutRes int layoutResID) {
getWindow().setContentView(layoutResID);
initWindowDecorActionBar();
} //phoneWindow的setContentView方法 //要注意的是 这个方法执行完毕 我们也只是 通过decorView创建好了 我们自己的view对象而已。
//但是这个对象还没有被显示出来,只是存在于内存之中。decorview真正被显示 要在makevisible方法里了
@Override
public void setContentView(int layoutResID) {
// Note: FEATURE_CONTENT_TRANSITIONS may be set in the process of installing the window
// decor, when theme attributes and the like are crystalized. Do not check the feature
// before this happens.
if (mContentParent == null) {
//这个就是创建decorview的 decorView就是那个framelayout我们的根布局 有一个标题栏和内容栏
//其中内容兰 就是android.R.id.content
installDecor();
} else if (!hasFeature(FEATURE_CONTENT_TRANSITIONS)) {
mContentParent.removeAllViews();
} if (hasFeature(FEATURE_CONTENT_TRANSITIONS)) {
final Scene newScene = Scene.getSceneForLayout(mContentParent, layoutResID,
getContext());
transitionTo(newScene);
} else {
//这里就是我们自己写的布局 layout 给关联到deorview的content布局里面
mLayoutInflater.inflate(layoutResID, mContentParent);
}
final Callback cb = getCallback();
if (cb != null && !isDestroyed()) {
//添加完毕以后调用回调
cb.onContentChanged();
}
}
7.dialog的window创建过程?
答:子window的创建过程如下:其实和activity的过程差不多 无非是acitivity对于decorView的显示是自动控制,交给actitytherad 按照流程来走 最后makevISIABLE函数来完成最终显示的,而dialog就是需要你手动来完成这个过程也就是show函数
//看Dialog的构造函数 ,和acitivity差不多 也是PhoneWindow 对象。
Dialog(@NonNull Context context, @StyleRes int themeResId, boolean createContextThemeWrapper) {
if (createContextThemeWrapper) {
if (themeResId == 0) {
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); final Window w = new PhoneWindow(mContext);
mWindow = w;
w.setCallback(this);
w.setOnWindowDismissedCallback(this);
w.setWindowManager(mWindowManager, null, null);
w.setGravity(Gravity.CENTER); mListenersHandler = new ListenersHandler(this);
} //Dialog的setContentView方法 也是调用的phonewindow的方法 和acitivity流程也是一样的
public void setContentView(@LayoutRes int layoutResID) {
mWindow.setContentView(layoutResID);
} //我们都知道dialog必须要show才能显示出来, public void show() {
if (mShowing) {
if (mDecor != null) {
if (mWindow.hasFeature(Window.FEATURE_ACTION_BAR)) {
mWindow.invalidatePanelMenu(Window.FEATURE_ACTION_BAR);
}
mDecor.setVisibility(View.VISIBLE);
}
return;
} mCanceled = false; if (!mCreated) {
dispatchOnCreate(null);
} onStart();
mDecor = mWindow.getDecorView(); if (mActionBar == null && mWindow.hasFeature(Window.FEATURE_ACTION_BAR)) {
final ApplicationInfo info = mContext.getApplicationInfo();
mWindow.setDefaultIcon(info.icon);
mWindow.setDefaultLogo(info.logo);
mActionBar = new WindowDecorActionBar(this);
} WindowManager.LayoutParams l = mWindow.getAttributes();
if ((l.softInputMode
& WindowManager.LayoutParams.SOFT_INPUT_IS_FORWARD_NAVIGATION) == 0) {
WindowManager.LayoutParams nl = new WindowManager.LayoutParams();
nl.copyFrom(l);
nl.softInputMode |=
WindowManager.LayoutParams.SOFT_INPUT_IS_FORWARD_NAVIGATION;
l = nl;
} try {
//在这里 把decorview给add到这个window中了 与activity流程也是一样的
mWindowManager.addView(mDecor, l);
mShowing = true; sendShowMessage();
} finally {
}
}
8.Dialog的创建是不是必须要有activity的引用?
答:不需要,只要你更改为系统window就可以了。系统window是不需要activity作为引用的。注意别遗漏了权限
Dialog dialog=new Dialog(MainActivity.this.getApplicationContext());
dialog.getWindow().setType(WindowManager.LayoutParams.TYPE_SYSTEM_ERROR);
TextView textView=new TextView(MainActivity.this);
textView.setText("this is dialog not use activity this");
dialog.setContentView(textView);
dialog.show();
9.toast的window创建过程?
答:这属于系统级别的window创建了,和前面的两种window创建过程稍微不一样。其实主要就是notificationmanagerservice和toast本身之间两者的相互调用而已。
就是简单的ipc过程。前面binder的教程有讲到,如何利用binder来进行双向通信。toast的源码 就是利用了binder的双向通信来完成toast的功能。
源码就不分析了,ipc的东西讲过太多了,有兴趣的可以自己看。
Android Window 9问9答的更多相关文章
- Android 动画 6问6答
1.view 动画有哪些需要注意的? 答:view动画 本身比较简单.http://www.cnblogs.com/punkisnotdead/p/5179115.html 看这篇文章的第五问就可以了 ...
- Android RemoteViews 11问11答
1.什么是RemoteView? 答:其实就是一种特殊的view结构,这种view 能够跨进程传输.并且这种remoteview 还提供了一些方法 可以跨进程更新界面.具体在android里面 一个是 ...
- OpenGL快问快答
OpenGL快问快答 本文内容主要来自对(http://www.opengl.org/wiki/FAQ)的翻译,随机加入了本人的观点.与原文相比,章节未必完整,含义未必雷同,顺序未必一致.仅供参考. ...
- Oracle百问百答(四)
Oracle百问百答(四) 31.怎样查看某用户下的表? select table_name from all_tables where owner=upper('jhemr'); 32.怎样查看某用 ...
- Oracle百问百答(二)
Oracle百问百答(二) 11. nvl函数有什么用? NVL( string1, replace_with) 功能:如果string1为NULL,则NVL函数返回replace_with的值,否则 ...
- Oracle百问百答(一)
Oracle百问百答(一) 01.如何查看oracle的版本信息? 02.如何查看系统被锁的事务信息? 03.怎么获取有哪些用户在使用数据库? 04. 数据表中的字段最大数是多少? 表或视图中的最大列 ...
- 微信小程序参数二维码6问6答
微信小程序参数二维码[基础知识篇],从6个常见问题了解小程序参数二维码的入门知识. 1.什么是小程序参数码? 微信小程序参数二维码:针对小程序特定页面,设定相应参数值,用户扫描后进入相应的页面. 2. ...
- k3 Bos开发百问百答
K/3 BOS开发百问百答 (版本:V1.1) K3产品市场部 目录 一.基础资料篇__ 1 [摘要]bos基础资料的显示问题_ 1 [摘要]单 ...
- Java 面试题问与答:编译时与运行时
Java 面试题问与答:编译时与运行时 2012/12/17 | 分类: 基础技术, 职业生涯 | 5 条评论 | 标签: RUNTIME, 面试 分享到:58 本文作者: ImportNew - 朱 ...
随机推荐
- java对象群体的组织:Enumeration及Iterator类
在一般情况下,遍历集合类会使用一下方式: for(int i=0;i<v.size();i++)< p=""> Customer c=(Custormer)v.g ...
- 【XJOI-NOIP16提高模拟训练9】题解。
http://www.hzxjhs.com:83/contest/55 说实话这次比赛真的很水..然而我只拿了140分,面壁反思. 第一题: 发现数位和sum最大就是9*18,k最大1000,那么su ...
- win7 64 + Ubuntu 14.04.1 64双系统安装,详解UEFI ~ GPT和legacy ~ MBR区别
win7 64 + Ubuntu 14.04.1 64双系统安装 背景:我的笔记本之前的系统是window 7 64 + Ubuntu 14.04.1,用UEFI引导系统.安装过程是先装的win7,再 ...
- 浅析c语言中的变量(局部变量,外部变量,静态变量,寄存器变量)[转]
c语言中变量分为四类,分别是 1.auto 自动变量 2.static 静态存贮分配变量(又分为内部静态和外部静态) 3.extern 全程变量(用于外部变量说明) 4.register ...
- Android 实现Path2.0中绚丽的的旋转菜单
上图先: 那么下面开始吧~ 首先,将整个菜单动画分解开来. 1. 一级菜单按钮的旋转动画2个,十字和叉叉状态的转换. 2. 二级菜单按钮的平移动画2个,弹簧效果的in和out ...
- JBoss 性能优化(解决Jboss内存紧张的问题)
修改$JBOSS_HOME/bin/run.conf文件 JAVA_OPTS="-Xms 520m -Xmx 1220m -Xss 15120k +XX:AggressiveHeap&q ...
- Data Flow ->> Multicast
Multicast的中文意思是组播或者多播.那自然这个组件干的事情就是可以把一份数据库输入给多少接收组件作为输入.这里有篇别人的博文讲到了Multicast的主要作用和应用场景:http://www. ...
- QT 实现彩色图亮度均衡,RGB和HSI空间互相转换
从昨天折腾到今天.再折腾下去我都要上主楼了 大致和灰度图均衡是一样的,主要是不能像平滑什么的直接对R,G,B三个分量进行.这样出来的图像时没法看的.因此我们要对亮度进行均衡.而HSI彩色空间中的分量 ...
- 局域网聊天软件(winsocket)
LANChat工作整理 2013/8/22 程序实现功能: 局域网聊天软件,启动即可找到在线设备,并能够进行简单的文字聊天. 其实下面这个框图已经说明了程序的绝大部分功能原理. 核心类的程序框图 我觉 ...
- Eclipse项目内存溢出解决方案
方法一: 打开eclipse,选择Window--Preferences...在对话框左边的树上双击Java,再双击Installed JREs,在右边选择前面有对勾的JRE,再单击右边的“Edit” ...