Trying to make something similar to facebook chat head. When we click on the chat head it opens up the chat. Now when we press back button it closes the popup of chat. How to capture onBackPressed event in a service?
Asked
Active
Viewed 1,697 times
0
-
3service not made for get backpress. you cant get any event on backpress – Shabbir Dhangot Nov 30 '15 at 09:12
-
dear, service is faceless activity, how can you detect onBackPressed(); – Androider Nov 30 '15 at 09:16
-
Yes, I get that. But how facebook messenger gets backbutton click event. – Pranav Agrawal Nov 30 '15 at 09:18
-
@Mohit how to receive broadcast for back pressed event? – Pranav Agrawal Nov 30 '15 at 09:40
-
you have to create custom for that – Iamat8 Nov 30 '15 at 09:44
-
@Mohit can u please provide some sample receiver for bacpressed event. Unable to find one! – Pranav Agrawal Nov 30 '15 at 09:45
-
check my [this sample app](https://github.com/mohit008/Android-BroadCast-Tutorial) – Iamat8 Nov 30 '15 at 09:58
-
You can't get backpressed event in a service because it's running on the background – Context Nov 30 '15 at 10:01
-
@Mohit service is not attached to an activity how it will send a broadcast for back press event! – Pranav Agrawal Nov 30 '15 at 10:03
-
you dont have to send event , just broadcast an intent (with string) to your service – Iamat8 Nov 30 '15 at 10:16
-
@Mohit From where will i send the broadcast? – Pranav Agrawal Nov 30 '15 at 10:24
2 Answers
1
This might work :
make the window or view you show via service as focusable, add a onKeylistener(for e.g. on rootview or other) and listen for KEYCODE_BACK.

jay shah
- 903
- 6
- 21
-
made sure your view is focusable? only focusable views can recieve key events via keylistener. – jay shah Nov 30 '15 at 12:00
-
Activity.java in framework also does something similar, search for backpress, http://androidxref.com/6.0.0_r1/xref/frameworks/base/core/java/android/app/Activity.java, You must get key events on focused view to track Back. – jay shah Nov 30 '15 at 12:05