android 弹窗 onpause,Android 下拉通知栏时Activity的生命周期——重新理解onPause()
下拉通知欄時發生了什么
在某個APP中,發現下拉通知欄的時候,正在播放的視頻會暫停,于是有點好奇這段操作是不是在生命周期中實現的。在網上眾多關于Activity生命周期的討論中,很多人認為onPause()和onStop()的區別就是“部分遮擋”和“全部遮擋”,那按照這個猜測來分析一下這個過程:
首先,通知欄下拉一點點,符合一般描述中“Activity被部分遮擋”——onPause()
然后,通知欄完全落下之后,“Activity被全部遮擋”——onStop()
于是自己寫了一個實例來驗證:
public class MainActivity extends AppCompatActivity {
private static final String TAG = "MainActivity";
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
Log.i(TAG, "onCreate");
}
@Override
protected void onStart() {
super.onStart();
Log.i(TAG, "onStart");
}
@Override
protected void onResume() {
super.onResume();
Log.i(TAG, "onResume");
}
@Override
protected void onPause() {
super.onPause();
Log.i(TAG, "onPause");
}
@Override
protected void onStop() {
super.onStop();
Log.i(TAG, "onStop");
}
@Override
protected void onDestroy() {
super.onDestroy();
Log.i(TAG, "onDestroy");
}
}
啟動APP時,毫無疑問,調用了onCreate()→onStart()→onResume();
完全下拉通知欄,然后上拉通知欄,發現沒有日志打印,說明下拉通知欄對Activity的生命周期沒有影響。
其他的“部分遮擋”——AlertDialog、Toast
經過測試不難發現,在Activity中彈出AlertDialog、Toast時,Activity的onPause()并沒有調用;筆者還嘗試在MIUI系統中喚醒小愛同學,發現onPause()仍然沒有被調用。
但是在以下特殊的情況下,onPause()會被調用:
自定義dialog繼承自Activity
新啟動的Activity主題設置為 android:theme=@android:style/Theme.Dialog
重新理解onPause()
跑去看文檔發現了如下信息:
Method
Description
onPause()
Called when the system is about to start resuming a previous activity. This is typically used to commit unsaved changes to persistent data, stop animations and other things that may be consuming CPU, etc. Implementations of this method must be very quick because the next activity will not be resumed until this method returns.
Followed by either onResume() if the activity returns back to the front, or onStop() if it becomes invisible to the user.
發現了onPause()和Activity的奇妙聯系,就不難理解之前為什么沒有被調用的問題了。
查看AlertDialog和Toast的源碼,可以發現它們顯示的原理,都是通過WindowManager.addView()來顯示的。也就是說,AlertDialog和Toast可以看做是當前Activity的一部分View,當然也不會對Activity的生命周期構成影響。
因此,onPause()是否調用的關鍵就是,是否有另一個Activity參與進來了。
而網上流傳甚廣的onPause()和onStop()調用中提到的“遮擋”,應該修正為“被Activity遮擋”
至于官方文檔中提到的,onPause()之后會調用onStop()或者onResume(),前者很好理解,一般的退出、新啟動一個全屏Activity、鎖屏、返回HOME等操作都是這種情況;至于后者,筆者能想到的情況就是,彈出部分遮擋的Activity類型的對話框,然后按返回鍵。
創作挑戰賽新人創作獎勵來咯,堅持創作打卡瓜分現金大獎總結
以上是生活随笔為你收集整理的android 弹窗 onpause,Android 下拉通知栏时Activity的生命周期——重新理解onPause()的全部內容,希望文章能夠幫你解決所遇到的問題。
- 上一篇: FMDB简介
- 下一篇: 经典逻辑编程题(本文用python实现)