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答的更多相关文章

  1. Android 动画 6问6答

    1.view 动画有哪些需要注意的? 答:view动画 本身比较简单.http://www.cnblogs.com/punkisnotdead/p/5179115.html 看这篇文章的第五问就可以了 ...

  2. Android RemoteViews 11问11答

    1.什么是RemoteView? 答:其实就是一种特殊的view结构,这种view 能够跨进程传输.并且这种remoteview 还提供了一些方法 可以跨进程更新界面.具体在android里面 一个是 ...

  3. OpenGL快问快答

    OpenGL快问快答 本文内容主要来自对(http://www.opengl.org/wiki/FAQ)的翻译,随机加入了本人的观点.与原文相比,章节未必完整,含义未必雷同,顺序未必一致.仅供参考. ...

  4. Oracle百问百答(四)

    Oracle百问百答(四) 31.怎样查看某用户下的表? select table_name from all_tables where owner=upper('jhemr'); 32.怎样查看某用 ...

  5. Oracle百问百答(二)

    Oracle百问百答(二) 11. nvl函数有什么用? NVL( string1, replace_with) 功能:如果string1为NULL,则NVL函数返回replace_with的值,否则 ...

  6. Oracle百问百答(一)

    Oracle百问百答(一) 01.如何查看oracle的版本信息? 02.如何查看系统被锁的事务信息? 03.怎么获取有哪些用户在使用数据库? 04. 数据表中的字段最大数是多少? 表或视图中的最大列 ...

  7. 微信小程序参数二维码6问6答

    微信小程序参数二维码[基础知识篇],从6个常见问题了解小程序参数二维码的入门知识. 1.什么是小程序参数码? 微信小程序参数二维码:针对小程序特定页面,设定相应参数值,用户扫描后进入相应的页面. 2. ...

  8. k3 Bos开发百问百答

              K/3 BOS开发百问百答   (版本:V1.1)           K3产品市场部       目录 一.基础资料篇__ 1 [摘要]bos基础资料的显示问题_ 1 [摘要]单 ...

  9. Java 面试题问与答:编译时与运行时

    Java 面试题问与答:编译时与运行时 2012/12/17 | 分类: 基础技术, 职业生涯 | 5 条评论 | 标签: RUNTIME, 面试 分享到:58 本文作者: ImportNew - 朱 ...

随机推荐

  1. js:字符串(string)转json

    第一种方式: 使用js函数eval(); testJson=eval(testJson);是错误的转换方式. 正确的转换方式需要加(): testJson = eval("(" + ...

  2. poj 3522(最小生成树应用)

    题目链接:http://poj.org/problem?id=3522思路:题目要求最小生成树中最大边与最小边的最小差值,由于数据不是很大,我们可以枚举最小生成树的最小边,然后kruskal求最小生成 ...

  3. ScriptManager.RegisterStartupScript方法和Page.ClientScript.RegisterStartupScript() 区别

    ScriptManager.RegisterStartupScript方法 如果页面中不用Ajax,cs中运行某段js代码方式可以是: Page.ClientScript.RegisterStartu ...

  4. C语言关键字

    No. 关键字 意义 备注 1 auto 声明自动变量 2 break 跳出当前循环 3 case switch语句的分支 4 char 声明字符型变量 5 const 声明只读变量 C90新增 6 ...

  5. linux rpm命令

    1.rpm 是红帽(RedHat)软件包管理工具,实现类似于 Windows 中的添加/删除程序功能. 2.rpm -ivh 软件包名 安装软件包并显示安装进度.这个是用得最多的了. 3. rpm - ...

  6. Linux服务器 scp 不需要密码配置与密钥转换(id_rsa->ppk)

    案例:▲服务器A对服务器B.C进行ssh连接,免输入密码    或▲服务器A向服务器B.C复制文件(源文件在服务器A上),免输入密码 主机A:192.168.0.221主机B:192.168.0.22 ...

  7. Delphi对象变成Windows控件的前世今生(关键是设置句柄和回调函数)goodx

    ----------------------------------------------------------------------第一步,准备工作:预定义一个全局Win控件变量,以及一个精简 ...

  8. MySql存储引擎特性对比

    下表显示了各种存储引擎的特性: 其中最常见的两种存储引擎是MyISAM和InnoDB 刚接触MySQL的时候可能会有些惊讶,竟然有不支持事务的存储引擎,学过关系型数据库理论的人都知道,事务是关系型数据 ...

  9. php数据库操作常用相关函数

    MySQL访问函数都需要有相应的权限才能运行.常用的相关函数介绍如下: (1)integer mysql_connect(主机,用户名,口令); 此函数开始一个对指定主机上的MySQL数据库的连接.若 ...

  10. C#基础(二)

    变量的命名规则: 1.变量名由字母,数字 ,下划线组成.@ 中文 2.首字母,不能是数字 3.不能与关键字重名 变量的定义 语法: 数据类型 变量名[=值]; int a;      //只定义变量 ...