Backwards compatibility of onBackPressed

2019-08-02 06:13发布

If I use onBackPressed() on Android 1.5, my application crashes. Is there any possibility to deactivate this function if running on an Android 1.5 device?

The code there is not absolute necessary but a real "nice to have", so I would like to keep it on newer devices and just drop it on older ones.

Is this possible?

edit: I think I found it, just the old way:

@Override
public boolean onKeyDown(int keyCode, KeyEvent event)  {
   if (keyCode == KeyEvent.KEYCODE_BACK && event.getRepeatCount() == 0) {
       // do something on back.
       return true;
   }

return super.onKeyDown(keyCode, event);
}

1条回答
一纸荒年 Trace。
2楼-- · 2019-08-02 06:55

You can try to detect runtime which version of SDK using your application and depending on that prepare different branches. Like:

@Override 
public boolean onKeyDown(int keyCode, KeyEvent event)  
{ 
    if(Build.VERSION.SDK_INT==Build.VERSION_CODES.CUPCAKE) //if it's 1.5
    {
       if (keyCode == KeyEvent.KEYCODE_BACK && event.getRepeatCount() == 0) 
       {        // do something on back.        
          return true;    
       }  
    }
    return super.onKeyDown(keyCode, event); 
} 
查看更多
登录 后发表回答