I'm writing a client program where I'm running a service in server for communication.
android hardware back button can be controlled through OnKeyDown
method or OnBackPressed
Method from an activity.
But how its done from a service ?
It is not possible to detect hardware "BACK " press from Service.
If you have an activity in the foreground, the activity can detect a BACK press. In this case, your Activity communicate a BACK Press from your activity to your Service.
Why it is so?
Service in principle, is an app component developed to perform long running operations in "Background". See the below quotes from Android docs:
A service does not provide a user interface. For example, a service might play music in the background while the user is in a different app, or it might fetch data over the network without blocking user interaction with an activity
Actions such as "Back" press are user-driven and hence closely tied to User interface which in Android is Activity.
Hence, Android framework offers API Related to handling "Back" press using Activity and not using Services.
Almost all the time your service will not be showing its own windows to the screen. So services won't be able to receive back-button click events.
You may read some Interesting discussion on this LINK.