how to press back button programmatically in android

8.3k views Asked by At

A SERVICE I HAVE NOT ANY ACTIVITY is running in forebackground and when user click on app button i want do function of hardware back button onBackPressed is not working inside service!!
enter image description here

4

There are 4 answers

5
AskNilesh On

Is it not possible to programmatically press the back button on android through a service

onBackPressed() Called when the activity has detected the user's press of the back key.

you need to just call onBackPressed() method don't forgot override onBackPressed() in your activity

@Override
    public void onBackPressed() {
        super.onBackPressed();   
        // perform your action here

    }
1
Vishal Vaishnav On

You can handle back button operation like this;

@Override
public void onBackPressed() {
// your code.
}

otherwise try below code;

@Override
 public boolean onKeyDown(int keyCode, KeyEvent event) {
if (keyCode == KeyEvent.KEYCODE_BACK) {
    // your code
    return true;
}

return super.onKeyDown(keyCode, event);
}
1
Muhammad Rayyan Siddiqui On

You can handle back button operation like this;

 @Override
public boolean onOptionsItemSelected(MenuItem item) {
    // Handle item selection
    switch (item.getItemId()) {
        //Home Button!
        case android.R.id.home:
            finish();
            return true;
        default:
            return super.onOptionsItemSelected(item);
    }
}
1
Android and Security Guru On

Currently, it's not possible to press "BACK" from service. Since you don't have an activity in the foreground, you don't have the ability to programmatic to press a BACK press, due the fact the service not provide any user interface. What is the option - If you have a rooted device with an access to shell you can try to use the following command in the service Process process = Runtime.getRuntime().exec("adb shell input keyevent 4");