How to make my flutter app return the user to the OS home screen? - flutter

I'm working on an app that will have a lock screen, but I'm having some issues getting it to behave correctly. Right now I'm using the didChangeAppLifecycleState to navigate to the lock screen when the user suspends/resumes the app. I'm also using the WillPopScope to intercept and deny the back button. The problem with this approach is that pressing the back button and having nothing happen doesn't feel super intuitive. Ideally, I'd like the back button to take the user out of the app and back to their OS home screen when they're on the lock screen. I also want to do this in a way that the user's route history is maintained for when they successfully unlock the app.
Is there any way to accomplish what I'm trying to do, or should I just accept that the back button won't do anything on the lock screen?

You can create an identifier in your LockScreen state and check for the identifier in onWillPop and if the user is pressing the back button from the lock screen, exit the app.
String identifier = "lockscreen";
bool onWillPop() {
if (identifier == "lockscreen") {
SystemNavigator.pop();
SystemChannels.platform.invokeMethod('SystemNavigator.pop'); //preferred.*
return true;
}
}
SystemNavigator.pop(): On iOS, calls to this method are ignored because Apple's human interface guidelines state that applications should not exit themselves.

Related

GWT Forward Button

I'm having an issue handling the forward button.
Basically, when a user is on a page and has made changes without saving then presses the backwards or forwards button they are presented with a prompt and two options: Leave or Stay.
I have implemented the backwards button fine, and choosing to stay on the page works well using History.newItem(currentToken) - the back button is still clickable.
However with the forwards button, if I use History.newItem(currentToken), it brings this to the front of the history stack and the forward button can no longer be clicked.
History.replaceItem(currentToken) causes the same issue.
How do I handle the cancelling of a forwards action so that I stay on my current page, but the forwards button is still enabled?
#Override
public void onValueChange(ValueChangeEvent<String> event) {
logger.info("back button pressed: " + event.getValue());
String evenVal = event.getValue();
String token = History.getToken();
AbstractPresenter presenter = sessionKiosk.getCurrentlyShowingPresenter();
if (presenter instanceof NSRCommonWorksheetPresenter && sessionKiosk.isDirty()) {
((NSRCommonWorksheetPresenter)presenter).setHistoryToken(event.getValue());
((NSRCommonWorksheetPresenter)presenter).showUnsavedChangesLeavingPageDialog();
}
else {
handleHistoryEvent(event.getValue());
}
}
The dialog is shown and when I click on stay on page the following is called.
public void stayOnCurrentPage() {
if (eventMap.get(prevPage) != null) {
History.newItem(prevPage, false);
}
}
Update: Basically history.newItem(value) removes the use of the forward button. Is there another way to cancel the event? If I just do nothing, th page stays where i want but the url still updates
None of the 3 options in the else statement seem to work.
Thanks.
You can simply cancel the event without touching History or tokens.
UPDATE:
It appears from your code that you are not intercepting the event (back/forward button), but let it go through, get the new token, and then force a return to the previous state under certain circumstances.
I suggest using Activities and Places pattern where every "place" within your app has a corresponding "activity". Each activity in your app will implement GWT Activity interface which includes mayStop() method. This method is called before a user navigates away from a specific place in your app, giving you an opportunity to warn a user and cancel the navigation if necessary.
In general, this pattern offers a very robust support for the History mechanism, covering many use cases.
If you want to support History mechanism yourself, take a look at PlaceChangeRequestEvent - it allows you to warn a user who tries to navigate away from a place in your app.

Back and volume buttons not working when app is resumed in certain conditions

I'm starting a new activity to display a leaderboard in my Android App.
When the leaderboard activity is displayed, and the user presses the home key and then resumes the app (so the leaderboard activity comes up again), and then navigates back to the main activity by pressing the back key, the back key and volume keys stop working).
I've attempted to override onBackPressed in my activity class. I can confirm that when this problem occurs, onBackPressed is not called (When back / volume is working, pressing back does trigger onBackPressed).
Normally I get a message in LogCat when I press the back key 'Unimplemented WebView method onKeyDown called from android.webkit.WebView,onKeyDown(WebView.java.2178)' - Again I can confirm that this message doesn't come up when the back key isn't working
Armed with the above information, I can only assume that it's something to do with the View not having focus or something along those lines. I would point out that touch input on the screen itself does work. It just seems to be the back and volume keys/buttons that have no effect.
It's an openGL ES 2.0 app so in my onPause() I'm calling view.onPause(); and in onResume, I'm calling view.onResume();
I really have no idea what's going on and I've been on this for 3 days straight so if anyone can point me in the right direction, that would be great.
If the user comes out of the leaderboard and back into the main app before they press the home key, then everything is OK, it's just if the home key is pressed while the leaderboard activity is displayed as described above.
So when I'm at the point where the back / volume keys aren't working, if I click my scores button and fire up the leaderboard activity again, they work. On returning to my activity, they stop working again.
Not sure if this is relevant at all but the following shows how I'm starting my leaderboard activity:
if (scoresButtonPresses){
displayLeaderBoard();
}
void displayLeaderBoard(){
//Display the leaderboard if already signed in
if (checkSignedIn()){
startActivityForResult(Games.Leaderboards.getLeaderboardIntent(getApiClient(), leaderboardID), 1);
}
//if not already connected, then set flag and connect to play services before displaying leaderbaord
else{
signInAction=SHOW_LEADERBOARD;
getGameHelper().beginUserInitiatedSignIn();
}
}
#Override
public void onSignInSucceeded() {
//If the flag is set, then display the leaderboard
if (signInAction==DISPLAY_LEADERBOARD){
startActivityForResult(Games.Leaderboards.getLeaderboardIntent(getApiClient(), leaderboardID), 1);
}
//Otherwise, reset the flag and take no action
else {signInAction=NO_ACTION;}
}
This is driving me crazy so any help or even a nudge in the right direction would be very much appreciated!!
Edit
After much testing I have learned a couple of things:
If I remove the view.onPause() && view.onResume() the problem seems to go away. So this appears to be something to do with the way key events are captured by the view. Pausing and resuming seems to mess something up.
I have also tried removing the view.onPause() and view.onResume() as above, but instead, putting in View.setVisibility(View.GONE); and then making it visible again in public void onWindowFocusChanged(boolean hasFocus). Again, I get the same problem. Interestingly, when I open the leaderboard, as expected the view's staus is 'gone' then hitting the home key and running the app again, it's set back to 'visible' - I don't understand this behaviour but I'll ask another question for that.
Lastly, and this I find really odd. If I put my app back to as I had it, then after hitting the home key and relaunching the app via Eclipse (and I can do this multiple times) the problem doesn't seem to occur. So in that respect, it appears to be something to do with touching the screen.
Edit
It appears as though this isn't limited to my app. I've tested this on a couple of other apps from the Play store and get the same result.
One app clearly uses a single activity model like mine and the back and volume stop working throughout the app.
The other may use a different activity for it menu and game. When I test on this app, the back/volume breaks but if you start a game (therefore a second activity), the back key starts working again, even when you return to the first activity (recreated this activity?!)
So maybe I can get around this by ensuring the activity is recreated? I thought i was already but maybe I'm not getting something. Maybe it's something to do with the stack.........
I have no solution to your problem but some additional insights since I'm facing the same bug/problem with the leaderboards and the back button (and it's driving me crazy).
I'm using a single activity with fragments from which I login to Google Play, open Leaderboards and Achievements in the exact way you are doing it (startActivityForResult). Always when I come back from any Google Play Service activity my back button is broken. Sometimes it's even enough if I try to login to Google Play for it to break, meaning the login popup sometimes breaks the back button (but not always).
Some more insights which might help to solve the problem:
I'm not using OpenGL, so it's not related to this - I'm just using a single activity and fragments
It's also breaking for me when I just use the back button for going back from any Google Play Activity (I don't even need to go via the home key, just normal back is enough).
When the back button is broken the Activity is not receiving any Key Events (OnKeyDown, OnKeyUp, dispatchKeyEvent) are all not working, although using the activity and touching it fully works. My guess is that some view is catching the events...
Edit:
I also tried checking activity.getCurrentFocus() and activity.hasWindowFocus() as well as the parent and context classes of activity.getCurrentFocus() to see if there is any difference between when it's working and when it's not - and there isn't any difference...
Edit:
It seems that a simple call to View.requestFocus() is fixing the problem. For my single activity (using fragments implementation) I have now added:
#Override
public void onResume(){
super.onResume();
Fragment fragment = getFragmentManager().findFragmentById(R.id.fragmentContainer);
fragment.getView().requestFocus();
}
and this seems to be fixing the problem. Sill have to do long term checking if it's always fixed. In your OpenGL implementation I guess you will have to get the main view of the activity in some other way since you are not using fragments.
I know it's pretty old question, but for clarification: accepted answer is correct, but incomplete. Focus requesting should be done in onResume, onActivityResult, onSignInSucceeded and onSignInFailed. In first two you have! to call super. Some code:
private void requestFocusAfterGooglePlay(){
if(gimmeFocus==null)
return;
View currFocus=getCurrentFocus();
gimmeFocus.setFocusableInTouchMode(true);
gimmeFocus.setFocusable(true);
gimmeFocus.requestFocus();
gimmeFocus.setFocusableInTouchMode(false);
gimmeFocus.setFocusable(false);
if(currFocus!=null)
currFocus.requestFocus();
}
#Override
public void onSignInFailed() {
requestFocusAfterGooglePlay();
}
#Override
public void onSignInSucceeded() {
requestFocusAfterGooglePlay();
}
#Override
public void onActivityResult(int requestCode, int resultCode, Intent data) {
requestFocusAfterGooglePlay();
super.onActivityResult(requestCode, resultCode, data);
}
#Override
public void onResume(){
super.onResume();
requestFocusAfterGooglePlay();
}
in my case gimmeFocus is a dummy View created as below:
<View
android:id="#+id/gimme_focus"
android:layout_width="0px"
android:layout_height="0px"
android:focusable="false"
android:focusableInTouchMode="false"/>
I have dynamic layout so I can't never be sure that any view exists in my layout, so I've created this dummy View, it might be also added programmatically. You might choose your fixed View for gaining focus, but rembember that changing focus might change view's look (drawable state).

Detect button press from CLLocationManager Authorization alert

I am detecting whether the user has accepted the request to use location services in my app, I have a toggle switch in the UI that is dependent on this acceptance. The first time they toggle the switch (on) the request to use location is triggered. I want to know which button they press in that alert. (accept or decline) Right now I'm just toggling it off and making the user press it again (then detect which option they picked).
It is kind of sloppy that way, so I'd like to know if there is a way to detect this specific alert or can't that be done since it is triggered by the OS, not the application? I haven't tried it yet, but was thinking I could use the UIAlertView delegate methods for just generic button presses, but was hoping for something more specific.
UPDATE
I was able to get this working by just registering a notification when I trigger the location request (and the authorization prompt is shown). The application is placed in an inactive state (much like pulling down the notification bar). I just trigger a notification when the application becomes active and I'm able to just query the authorization status there and update my UI. I hope this helps anyone else down the line if they want to handle the authorization status on the fly.
There is no way to intercept the alert. There is, however, a method on CLLocationManagerDelegate method called didChangeAuthorizationStatus. That's probably the closest you can get to intercepting the alert.
There is no way to know explicitly which button the user selects since, as you've said, this alert comes from the OS. You can however, find out if location services has been enabled for your app, and know that way. Use a method such as this:
-(BOOL)locationServicesIsEnabled
{
if (![CLLocationManager locationServicesEnabled] || ![CLLocationManager authorizationStatus])
return NO;
return YES;
}

how to load aplication from start up page each time in iphone

I have application for iphone i want to open it from start up page always but when i load first time app on ipad it loads from startup page but when i close app and second time run on ipad then it opens from the same screen from where i left i want that again it should open from startup page also.I have start up page with enter button when i click to button i move to calulations screen where i perform calculations .If i close on calculation screen the app when i again open it it opens from calculation screens not from the startup screen
In plist file add one more field
Application does not run in background : make it true
This is your perfect ans.
Second time app will be in Background thats why it is not starting with start app page. Dont allow application to run in background. Set Key "" in info.plist file
You should add in your plist that property :
UIApplicationExitsOnSuspend
This will allow your application to "restart" instead of saving its state. This will allow you to load the start up page each time.
(documentation)
Well it is discouraged by apple , according to it's documentation:-
There is no API provided for gracefully terminating an iOS application.
In iOS,user presses the Home button to close applications. Should your application have conditions in which it cannot provide its intended function, the recommended approach is to display an alert for the user that indicates the nature of the problem and possible actions the user could take — turning on WiFi, enabling Location Services, etc. Allow the user to terminate the application at their own discretion.
Warning Do not call the exit function. Applications calling exit will appear to the user to have crashed, rather than performing a graceful termination and animating back to the Home screen.
Here's the link to it.Anyway nobody stops you from using
exit(0) , but is discouraged.
Another way to do is is simply change your application's pList property "Application does not run in background" to true.

Prevent cached iPhone webapp from reloading (scrolling to top)

I have an iPhone webapp that uses a cache manifest to work offline. I add the webapp to my home screen, use it (say scroll to a certain location on a page), then go back to homescreen.
When I open the app again, for a brief moment I see where I used to be (at that scrolled location on that page), but then the app "reloads" and I get scrolled to the top of the mainpage. Is there a way to prevent this "reloading"? This happens even in airplane mode (ie everything is working off the cache).
You're just seeing the default startup image, which is just a screenshot of the last place you were at. It's not "reloading"; the app wasn't loaded to begin with.
Search for "apple-touch-startup-image" to set a real loading image.
What I'm struggling with here is that the app actually seems to stay "in memory" longer if I use regular Safari as opposed to running in "apple-mobile-web-app-capable" mode. In the later case something as simple as pressing the home button, then task-switching back to the app causes a reload. Doing the same thing just in Safari often does not reload. So I'm worse off by using "apple-mobile-web-app-capable".
I don't believe there is a real 'reload' event. onload and onunload are all we get.
the onload handler starts up as if it is your first time coming to the page.
the onunload handler is the key to clearing out old content.
I like to provide alternate content for people who are coming back to my web app.
window.onunload=function(){
document.getElementsByTagName('body')[0].className+=' unloading'
}
And let the CSS do the dirty work to hide most of the body and show alternate content.
(this answer does not rely on jQuery or other frameworks)
// on load
window.scroll(0,0);
To ensure no old content is displayed while launching I use this in my page:
window.addEventListener('unload', function() { $('body').hide(); } );
Thus the last state of the page is empty and is what is shown to the user when the page is opened again.