背景
给一个Activity A,盖上一个透明主题的ActivtiyB,在B中的点击事件怎么传递给A?同学面试问到了这个问题。
我们普通的思考方式都是接口啊,或者EventBus或者Livedata。
这样的方式都可以!但是稍显麻烦。有没有更简单,不需要增加额外类的方法?
简单方案
不需要额外引入类?意味着只能使用Activity B中的内容,这时候我们就需要去思考Activity创建过程了。
首先我们都知道一个Activity启动之后,会执行onCreate 和onResmume()。
我们来从源码的角度来看看这里做了些啥。(源码并不多,多看看就了解了)
- Activity的创建
如果是App的主Activity,它肯定是launch程序通过startActivty开始的,到AMS进程中去解析需要启动的Activity信息,然后判断需要启动的应用进程是否创建,如果没有创建会通过socket的方式去和Zygote进程建立连接,然后进入Zygote中,它会forke一个子进程,在子进程中反射调用ActivtiyThread的main方法,在main方法里面我们会创建Looper 以及一个mH的handler,mH它能帮我们完成许多事情,比如帮我们创建Application的回调,以及Activity这种组件的生命周期的回调,到此一个应用程序的进程就创建成功了!接下来就是执行关于oncreate的内容了。
//----------------------------ActivityThread.java---------------------------
@Override
public Activity handleLaunchActivity(ActivityClientRecord r,
PendingTransactionActions pendingActions, Intent customIntent) {
//................................
// Hint the GraphicsEnvironment that an activity is launching on the process.
GraphicsEnvironment.hintActivityLaunch();
final Activity a = performLaunchActivity(r, customIntent);
//................................
return a;
}
private Activity performLaunchActivity(ActivityClientRecord r, Intent customIntent) {
//----------------------------------
ContextImpl appContext = createBaseContextForActivity(r);
Activity activity = null;
try {
java.lang.ClassLoader cl = appContext.getClassLoader();
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) {
//----------------------------------
}
try {
Application app = r.packageInfo.makeApplication(false, mInstrumentation);
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,
r.assistToken);
} 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, IBinder assistToken) {
attachBaseContext(context);
mFragments.attachHost(null /*parent*/);
mWindow = new PhoneWindow(this, window, activityConfigCallback);
mWindow.setWindowControllerCallback(mWindowControllerCallback);
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);
}
//==================================
}
attach方法也没有做其他的内容就是创建了一个PhoneWindo而已,到目前我们知道了Activity里面有一个mWindow它的类型是PhoneWindow。马上就是解析布局创建DecorView(这里不展开了),onCreate方法就走完了。
继续往下走就是onResmume的声明周期了
public void handleResumeActivity(IBinder token, boolean finalStateRequest, boolean isForward,
String reason) {
final ActivityClientRecord r = performResumeActivity(token, finalStateRequest, reason);
/-----------------------------
final Activity a = r.activity;
/----------------------------
if (r.window == null && !a.mFinished && willBeVisible) {
r.window = r.activity.getWindow();
ViewManager wm = a.getWindowManager();
/-----------------------
if (a.mVisibleFromClient) {
if (!a.mWindowAdded) {
a.mWindowAdded = true;
wm.addView(decor, l);
} else {
// The activity will get a callback for this {@link LayoutParams} change
// earlier. However, at that time the decor will not be set (this is set
// in this method), so no action will be taken. This call ensures the
// callback occurs with the decor set.
a.onWindowAttributesChanged(l);
}
}
// If the window has already been added, but during resume
// we started another activity, then don't yet make the
// window visible.
} else if (!willBeVisible) {
if (localLOGV) Slog.v(TAG, "Launch " + r + " mStartedActivity set");
r.hideForNow = true;
}
Looper.myQueue().addIdleHandler(new Idler());
}
handleResmue的方法也很简单,里面的内容就是先去执行onResmue的方法,然后会去获取一个windowManager,这个变量是Activity在执行attach()方法的时候创建的。
//---------------------Activtity.java
mWindow.setWindowManager(
(WindowManager)context.getSystemService(Context.WINDOW_SERVICE),
mToken, mComponent.flattenToString(),
(info.flags & ActivityInfo.FLAG_HARDWARE_ACCELERATED) != 0);
这时候我们可以清楚的看到Activity和Window的关系了。
接下来就就是重点环节了重点
windowManger怎么添加View的呢?
//windowManager是一个接口,它的实现是WindowManagerImp
//------------------WindowManagerImpl.java
@Override
public void addView(@NonNull View view, @NonNull ViewGroup.LayoutParams params) {
applyDefaultToken(params);
mGlobal.addView(view, params, mContext.getDisplayNoVerify(), mParentWindow,
mContext.getUserId());
}
//Global的变量
private final WindowManagerGlobal mGlobal = WindowManagerGlobal.getInstance();
//------------------WindowManagerGlobal.java
public void addView(View view, ViewGroup.LayoutParams params,
Display display, Window parentWindow, int userId) {
//----------------------------
mViews.add(view);
//------------------------
}
private final ArrayList mViews = new ArrayList();
这里我们看到了mGlobal的变量,它是通过WindowManagerGlobal单例获取的!到这里我们发现了一个关键的地方了,我们这个应用程序所有的Acitivty(同进程的)都会执行addView的操作,将DecorView添加到WindowManagerGlobal中。我们如果拿到WindowManagerGlobal 的单例自然就可以拿到上一个Activity的DecorView了。
说整就整
public class BottomActivity extends Activity {
private static final String TAG = "BottomActivity";
@Override
protected void onCreate(@Nullable Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_bottom);
TextView textView = findViewById(R.id.tv_test);
textView.setOnClickListener(v -> {
Log.v(TAG,"底层的botton接收到了事件");
});
TextView start = findViewById(R.id.start);
start.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
Intent intent = new Intent(BottomActivity.this,TopActivity.class);
startActivity(intent);
}
});
}
}
接下来就是透明的Activity
public class TopActivity extends Activity {
private static final String TAG = "BottomActivity";
private View mBoottomView;
@Override
protected void onCreate(@Nullable Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_top);
}
@Override
public boolean dispatchTouchEvent(MotionEvent ev) {
if (mBoottomView!=null){
Log.v(TAG,"当前事件是" + this.getClass().getName() + "传递");
mBoottomView.dispatchTouchEvent(ev);
}
return super.dispatchTouchEvent(ev);
}
@Override
protected void onResume() {
super.onResume();
//这里我们去响应底层Acitviti的事件
//我们知道是在handleResume 中 创建ViewRootImpl 并且给windowManager添加View的
//WindoManager又会把整个View加入到单例WindowManagerGlobal
//我们在这里反射肯定获取得到的
//直接反射
try {
Class clzz = Class.forName("android.view.WindowManagerGlobal");
//它里面有一个单例方法
Method method = clzz.getDeclaredMethod("getInstance");
Object object = method.invoke(null);
Field field = clzz.getDeclaredField("mViews");
field.setAccessible(true);
ArrayList views = (ArrayList) field.get(object);
//我们知道先执行的onResume,在执行的addView,所以上一个Activity的末尾这个
if (views!= null && views.size() >=1){
mBoottomView = views.get(views.size()-1);
}
} catch (ClassNotFoundException e) {
e.printStackTrace();
} catch (NoSuchMethodException e) {
e.printStackTrace();
} catch (IllegalAccessException e) {
e.printStackTrace();
} catch (InvocationTargetException e) {
e.printStackTrace();
} catch (NoSuchFieldException e) {
e.printStackTrace();
}
}
}
总结
其实内容并不复杂,只是需要你去多翻翻源码而已。星光不问赶路人,时光不负有心人哦。