最近項目中有個需求,就是判斷我們的應用是否被置於後台,以前只是簡單的以為在activty中判斷onUserLeaveHint()是否被執行即可,這個是被該方法的說明給騙了,說明如下:
Called as part of the activity lifecycle when an activity is about to go into the background as the result of user choice. For example,
when the user presses the Home key, onUserLeaveHint
will be called, but when an incoming phone call causes the in-call Activity to be automatically brought to the foreground,
onUserLeaveHint
will not be called on the activity being interrupted. In cases when it is invoked, this method is called right before the activity's
onPause
callback.
This callback and onUserInteraction
are intended to help activities manage status bar notifications intelligently; specifically, for helping activities determine the proper time to cancel a notfication.
紅色部分。後來經驗證該方法在activity之間跳轉時也被執行,這樣就明顯達不到要求啦。
還有就是API中雖然後KeyEvent.KEYCODE_HOME,但是根本就監聽不到。
目前網上常用的做法是,構造一個ArrayList<Activity> list = new ArrayList<Activity>();然後再onresume()中添加到該list中,在onstop()中判斷list中所有activity的onstop()是否被執行,哇。。。很是繁瑣。
下面是我發現的一種做法,簡單方便:
重點還是在onUserLeaveHint()上,再加上Intent.FLAG_ACTIVITY_NO_USER_ACTION,
If set, this flag will prevent the normal android.app.Activity.onUserLeaveHint
callback from occurring on the current frontmost activity before it is paused as the newly-started activity is brought to the front.
Typically, an activity can rely on that callback to indicate that an explicit user action has caused their activity to be moved out of the foreground. The callback marks an appropriate point in the activity's lifecycle for it to dismiss any notifications
that it intends to display "until the user has seen them," such as a blinking LED.
If an activity is ever started via any non-user-driven events such as phone-call receipt or an alarm handler, this flag should be passed to
Context.startActivity
, ensuring that the pausing activity does not think the user has acknowledged its notification.
OK,剩下的我就不多說了。。。