can we restrict backbutton functionality to given levels? - android

i am fighting with android hardware backbutton
now my question to you is can i restrict its functionality upto 3 or 4 levels?
right now for example, i have 1,2,3,4,5,6,7,8,9,10 activities
i go to 1 then 2 then 3 .... upto 10 and start pressing backbutton
it takes me to 9 then 8 then 7 upto end
i want to keep track of only last three levels is this possible or not?
any help would be appreciated.

i want to keep track of only last three levels is this possible or not?
You are welcome to keep count, perhaps using an integer. Use onBackPressed() (Android 2.x) and onKeyDown() (Android 1.x) to detect BACK button presses. If you chain to the superclass, normal BACK processing will occur. If you do not chain to the superclass, normal BACK processing will not occur.
Now, bear in mind that the user can press other keys, like HOME, or the user might respond to a notification (e.g., incoming text message). In those cases, it is possible that your counts may get out of sync with the actual user navigation. Hence, I encourage you to find some other UI pattern that does not involve artificially restricting the BACK button between activities in the fashion that you have outlined here.

This is the example code to CommonsWare's answer "onKeyDown() (Android 1.x)"
public boolean onKeyDown( int keyCode, KeyEvent event ) {
if (keyCode == KeyEvent.KEYCODE_BACK ) {
//do some stuff
return false;
}
return super.onKeyDown(keyCode, event);
}

Related

Detecting Long Key Press on Samsung Galaxy Watch 4 (Android Wear OS)

I have written a sailing app for watches running Wear OS. Sailing watches often get wet so I disabled the screen and navigate the menu using physical key presses (single and multiple presses). So far so good
I am now trying to detect a Long Press of the physical key (for an emergency Man-Over-Board function) but so far I have been unable to find any event which is triggered when a physical key is held down on the Samsung Galaxy Watch 4.
Can anyone suggest how to detect a long key press on the Samsung Galaxy Watch 4?
Most of the key press detection can be done by overriding onKeyDown()
override fun onKeyDown(keyCode: Int, event: KeyEvent): Boolean {
return if (keyCode == bottomKeyCode) {
// process bottomKeyPress
writeToLog("onKeyDown()")
event.startTracking() // required to enable LongPress (works on TicWatch NOT Samsung)
true
} else
super.onKeyDown(keyCode, event)
}
On the Samsung Galaxy Watch 4 a short press will trigger the onKeyDown() event
The problem is no events are triggered when the key is held down. Holding down the key does not trigger onKeyDown or onKeyLongPress. It does not even trigger onKeyUp when the key is released!
Further testing
I have also looked at dispatchKeyEvent()
override fun dispatchKeyEvent(event: KeyEvent): Boolean {
writeToLog("dispatchKeyEvent() keyCode ${event.keyCode} keyAction ${event.action}")
return super.dispatchKeyEvent(event)
}
This was also unsuccessful
I have run the code on a Ticwatch Pro 3 GPS (Wear OS 2) and the behaviour is 'closer' to what is described in the Android documentation. When the key is first pressed onKeyDown() is triggered. Continuing to hold the key down results in a second onKeyDown() 350msec later. This is followed by more onKeyDown() events sent every 50msec after that (along with an onLongKeyPress()). Hence the easiest way to implement Long Key Press detection on the TicWatch is to simply count the number of onKeyDown() events (to avoid the unneeded onLongKeyPress() event simply remove event.startTracking()).
Note the Samsung Galaxy Watch 4 uses keyCode == KeyEvent.KEYCODE_BACK for the bottom physical key rather than the Ticwatch which uses KeyEvent.KEYCODE_STEM_1. For completeness I investigated onBackPressed() but this is also not being triggered
override fun onBackPressed() {
writeToLog("onBackPressed()")
super.onBackPressed()
}
Samsung finally responded and the formal answer is Long Press is not supported
Unfortunately, it is not possible to get dispatched long-press keyEvent from the Samsung Galaxy watch 4.
Both Hardware buttons (named Home key and Back key) of watch 4 are system keys.
According to Samsung's policy, in the case of system keys, 3rd party can not get the KeyEvent of the watch 4 devices.
Factually it is possible for 3rd party apps to get access to the onKeyDown() event (as shown in the original question) PROVIDED it is only a short press
If the back key is held down then the watch does not trigger the onKeyDown() event (meaning any attempt to use a timer to simulate an onLongKeyPress() event will also be unsuccessful)

Method before home button [duplicate]

This question already has answers here:
Run code when Android app is closed/sent to background
(8 answers)
Closed 3 years ago.
My android application is a client, and when someone click the home button, I want to send a message to the server, and when the user changes back to the application, I also want to send a message to the server. If I could overwrite the HOME button keyEvent, or any method which will be called only when the application will be put into background, I could send message and set a static variable in a singleton which will be checked every onStart(), so basically I just need to somehow "override" the HOME button.
I tried the followings:
#Override
public boolean onKeyDown(int keyCode, KeyEvent event) {
if (keyCode == KeyEvent.KEYCODE_HOME) {
//...
return true;
}
return super.onKeyDown(keyCode, event);
}
It does simply not work. I put a breakpoint in it, but HOME button doesn't trigger this method at all. (Samsung Galaxy Ace, android 2.2.1).
I also tried to overrite the onUserLeaveHint() like this:
#Override
protected void onUserLeaveHint() {
//...
super.onUserLeaveHint();
}
But the problem is, this method will be called not only when I press HOME button or the application is interrupted, but when I just navigate to an other activity (and finish the current one).
Are there any solution to this problem?
Might want to take a look at this Android Docs
You are looking for onPause / onResume, based on the line
or any method which will be called only when the application will be
put into background
That doc should explain how the stack works, which will allow you to accomplish this problem.
There is not an day solution to this problem, because android does not let you override the home button. The easiest way around this is to pur your code in onPause, but of course this can be called without the home button being pressed.
The second (not accepted) answer here has an interesting solution, but I have not tried it so I am not sure if it works

Is it possible to listen for touches on the physical Android back button?

I couldn't find it in the docs, is there a module, or some other way to catch events from the android back button? If not it would be a nice and probably quick module to add.
No: the back button just pops you one item back in the history stack. You do something like change the hash fragment to track navigation through your app (frameworks like Backbone.js can do this for you automatically).
The reason we've taken that approach is there's no hardware back button on iOS so we're wary of setting people up to rely on it in their app, only for the app to be fundamentally broken on that platform: we're aiming for consistency of completeness at the moment.
Update: due to popular demand, we've added support for controlling the back button behaviour on Android: http://docs.trigger.io/en/v1.4/modules/event.html#backpressed-addlistener - note backPressed.preventDefault too.
The event handler is passed a function which, when invoked, closes the app, so you could have code like:
forge.event.backPressed.addListener(function (close) {
if (atHomeScreen) {
close();
}
}

How-to Keep an Android Activity Running when hitting the back key

I have an activity that essentially launches a CountDownTimer. I need this to continue running while using other Android apps, such as Gmail, and media players etc.
When I hit the back button, my Activity seems to quit. What do I need to do to keep it running when the user clicks the back/home keys etc.
You have to use a Service, you can read the documentation here.
Activities are not supposed to be doing anything when they are not visible. They are basically UI components.
You should be looking into services. These can run as a background process nd contain no UI.
It's been referred to as a serious "hack" by a few developers, but I've successfully checked for the back button being pressed so as to successfully clean my project up. I've recently moved most of this code to onPause() event because it's called right before the app goes down after back button is pressed. However, if it's really what you desire, it's your program and here's the code I used:
if (keyCode == KeyEvent.KEYCODE_BACK && event.getRepeatCount() == 0) {
killAndReturnParams(0);
}
Again, this method has been talked down before, but I'm pretty sure it's because you're not supposed to override the back button for any reason. The user is supposed to be able to use the back button to return at any point, in any app.
#Override
public void onBackPressed() {
mActivity.moveTaskToBack(true);
}

Is there anything I need to take into account when repeatedly calling the same activity?

I am developing an app where a single activity is instantiated multiple times by itself. I guess you could think of it like a book where each activity is a page. At the end of the page (activity) the user presses a button to go to a new page. I fire off an Intent for the same Activity, but I push different data into the Bundle so that a different page is loaded.
This works fine, and I like the fact that the user can back up to a previous point, but my question is whether this will eventually be a problem? What happens if this activity is instantiated 10 times, or 50, or 100? Will the device run out of memory, will GC come along and clean up old activities, or what?
If GC does clean them up, what happens when the user presses Back and the previous Activity is no longer on the stack?
Is it better to keep track of the user's path, finish() the activity, and override the Back button so that whether the user is moving forward or backwards, I only load a single Activity? Another approach I could take is to refresh all the data on the page so that it's still the same activity, but with new data. The Back button would not work as expected in this case.
Thoughts?
have you considered perhaps using the same Activity and just changing the content that it renders.
So in the book example. You would have a book Activity which would have a Page ViewGroup somewhere in its view hierarchy that renders the contents of the page. Then when a user goes to the next page or the previous page, the Page ViewGroup simply renders the contents of the desired Page. You could then use a data-structure to manage your stack of pages and the users current position.
Not sure what your app is trying to do, so I understand this might not work for your particular use. However, I would expect this to have a better run-time performance than instantiating entire Activities.
Old Activities that are no longer visible will get destroyed if their memory is needed. However, Android has a state persistence mechanism in place so that when an Activity is restarted (navigating back to page that was destroyed in your case) it can be reconstructed properly. This can be done through the shared preferences mechanism or the bundle object passed into Activity.onCreate. However, you will have to explicitly save off the state in Activity.onStop(...) and Activity.onSaveInstanceState(...), and then restore the state in Activity.onCreate(...) and Activity.onRestoreInstanceState
More on the lifecycle of Activies can be read here (Not sure what your level of understanding is)
http://developer.android.com/reference/android/app/Activity.html#ActivityLifecycle:
Now I'm not sure what happens at the extremes of this, whether you can create so many Activities that Android will no longer be able to bring back ones it killed. I would expect that there's some sort of protection mechanism in place to prevent that but I don't know what it is.
Found this article which might provide some more info, not sure if this is the info you were looking for though:
http://zerocredibility.wordpress.com/2009/08/24/why-android-swap-doesnt-make-sense/
Cheers & Happy Hunting!
I would rather override the back button behaviour and using for instance a ViewFlipper to do the animation job. That's pretty simple to do:
// You could do simpler by overriding onBackPressed() if you
// don't need 1.6 compatibility
//--
#Override
public boolean onKeyDown(int keyCode, KeyEvent event) {
if (keyCode == KeyEvent.KEYCODE_BACK && event.getRepeatCount() == 0) {
if (currentPage>0) {
return super.onKeyDown(keyCode, event);
} else {
currentPage--;
showPage(currentPage);
return true;
}
}
return super.onKeyDown(keyCode, event);
}

Categories

Resources