android應用中監聽按下HOME鍵

來源:互聯網
上載者:User

最近項目中有個需求,就是判斷我們的應用是否被置於後台,以前只是簡單的以為在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,剩下的我就不多說了。。。

 

相關文章

聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在5個工作日內處理。

如果您發現本社區中有涉嫌抄襲的內容,歡迎發送郵件至: info-contact@alibabacloud.com 進行舉報並提供相關證據,工作人員會在 5 個工作天內聯絡您,一經查實,本站將立刻刪除涉嫌侵權內容。

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.