finish() not working while using android monkey tool

497 Views Asked by At

I have an activity that overrides onBackPressed(), and within this function, I explicitly call finish(), since I need to do some clean up before the app exits.

When I do run the app normally, and click on the BACK key, the app exits normally.

When I run the monkey tool with the following command,

adb shell monkey -v --pct-syskeys 100 -p com.my.app 100

according to the logs, the onBackPressed() function is called, but the finish() does not close the activity/app. I've been trying to figure out what the problem is for sometime, but could not so far. Any help is appreciated.

EDIT: As per the comment, I'm posting the onBackPressed() code:

@Override
public void onBackPressed() {
if (bIsBackKeyPressed)
    return;

    // do some clean up

    bIsBackKeyPressed = true;
    finish();
}

The reason I'm using the bIsBackKeyPressed flag, is because the monkey tool sends the BACK key multiple times.

It is possible that this happens in conjunction with other key presses, along with the BACK key, but I'm not sure about that.

Thanks,
Rajath

2

There are 2 best solutions below

0
On BEST ANSWER

I was able to find out what the problem was. There is some additional information that I should have mentioned in my question. This was the logs for the monkey tool:

// Allowing start of Intent { act=android.intent.action.MAIN cat=[android.intent.category.LAUNCHER] flg=0x10200000 cmp=com.my.app/.main.MainActivity } in package com.my.app
// Rejecting start of Intent { act=android.intent.action.MAIN cat=[android.intent.category.HOME] flg=0x10200000 cmp=com.htc.launcher/.Launcher } in package com.htc.launcher

From the monkey docs, if I used the following command for running monkey

adb shell monkey -v --pct-syskeys 100 -p com.my.app -p com.htc.launcher 100

then it is ok. Notice that I have added the following: -p com.htc.launcher

So, what happens is that by not giving the additional parameters, when the BACK is sent to the app, the clean up takes place in onBackPressed(), but finish() is not called as the com.htc.launcher app is not given permission to run.

2
On

Try this...

@Override
public boolean onKeyDown(int keyCode, KeyEvent event) {
    if (keyCode == KeyEvent.KEYCODE_BACK) 
    {
        if (!bIsBackKeyPressed)
        {
            bIsBackKeyPressed = true;
            finish();
        }
        return true;
    } 
    else 
    {
       return super.onKeyDown(keyCode, event);
    }