How to Override Hardware Button in Android

Sathyapriya S

1 min read

Recently we developed an Android app that controls usage of other apps that already installed on a particular device. Example:, we can block listed apps like YouTube, Facebook in our App’s Dashboard which can eventually prevent kids to use those apps. If the kids tries to open that blocked apps, then it will prompt to them saying “This app is locked by your parents”. Want to know how we achieved it?

Here is the code snippet to block the app and that started creating the issue. Lets see how we fixed it.
[source language=java]
Intent intent = new Intent(BlockService.this, LockScreen.class);
intent.putExtra(“message”, “This app is locked by your parents”);
Later we found an issue that when we try to launch the app that we build, its also prompting with Lock screen instead opening App main screen.
How we want to feature to behave like:

  • While user launching block listed app (that we configured in our app earlier) , it might open with launch screen.
  • Launching our app must be navigate to App main screen.

Why the issue was happening ?
When user launches blocked app(s), we start Lock screen activity from our app to prompt user with warning and then we launch our Main activity. This way same or last activity still remains.
How we fixed it?
While launching our app, we need to kill Lock screen activity if it exists and then start the Main activity, but it’s like killing the app and opening it again. Its not good and we need to do it in a better way.
What we simply did is, we manually forced to select “Home” button to pause current activity and re-open Main activity.
[source language=java]
protected void onUserLeaveHint() {
onUserLeaveHint() is a protected method as other lifecycle methods of the activity and if you are handling onUserLeaveHint this will take care of the following case

  • When User hits home key
  • When User hits back key
  • When User hits menu key

Hope this approach helps you.

Related posts:

Leave a Reply

Your email address will not be published. Required fields are marked *