Exiting application in android

Finding the reason for the exit in Android Application

When working with an Android application, we might have to keep an eye on crashes or unwanted ways that the user exits the app. We use many third-party libraries to log exits in android.

Now, with Android R, we can log the exits in our app which can help us fix any issue that might exist in our app.

In this blog, we are going to talk, how we can log the exits of the user from our application.

Let’ s first discuss the type of crashes and exits we might see in our application. There can be a crash for an exception or maybe there might be an ANR that might lead your app to crash and drop users out of the application. The users might also exit the app intentionally when they have completed using the app.

Consider an example, let us say we are using WhatsApp and we want to log all the actions when a user exits the app. It can be a crash or an exception, or maybe a user action to close the app.

So, to get all the information we are going to use the ActivityManager .

But before that,

What is ActivityManager?

ActivityManager gives information about and interacts with, activities, services, and the containing process. Methods in this class give us certain information that we can use to debug our application.

So, first, I will create a project with MainActivity like,

Now, we will initialize the ActivityManager like,

Now, we will use ActivityManager to get the list of historic exit reasons for the app. To get the list, we will use,

Here, getHistoricalProcessExitReasons takes three parameters,

  • Package name: Here, we passed the package name of our application
  • PID: We passed 0 as default to get all the reasons
  • Size: The size of the list of exit reasons. So, we will get a list of type ApplicationExitInfo with only one item.

Here the exitList returns the history of exit, not the exit information in real-time as it provides the historical data.

Now, let’s first set up the exitList to return us the cause and reason of our crashes.

In our onCreate(), I will add,

Since we have only one item in the list lastExitInformation will get the value from the list using .first()

Now, we will Log the exit reasons, time and description using,

  • lastExitInformation will return an integer which corresponds to the reason of the crash
  • Timestamp returns Time in Epoch and,
  • The description returns the descriptive version of the crash.

Now, let’s add a TextView in XML file like,

and set the reason of crash to the textView using,

We are done setting up everything to get the historic exit reasons. Now, let’s start logging the reasons.

Case 1:

When we close the app from the recent app’s tray and then reopen the app again we would see the following log,

  • Reason code is 10 which means, REASON_USER_REQUESTED.
  • We got timestamp as well in our log and,
  • We got the description as remove a task, as we removed the app from the recent app’s tray.

We can also see the reason code in the textView .

The reason code and its meaning are,

So, for example, if we get a crash the reason code would be 4 according to the above table.

Case 2:

When we get a crash in our application. So, first, let’s introduce a crash in our application. We will create a button using,

and on click of textView, we will invoke the button’s click listener like,

This would lead to a crash of our application because the button is not mapped to any widget in XML.

When we reopen the app again, the app will generate a log,

Here, the reason code is 4, which maps to REASON_CRASH from the above table and the description also specifies crash.

If any exception occurs as well, the reason code would be REASON_CRASH

Case 3:

Let us terminate the JVM using System.exit().

So, In on the click of textView, we will add System.exit() like,

This will terminate the app. When we reopen the app, it will generate a log like,

Here, we won’t see any description but the reason code is 1 which maps to REASON_EXIT_SELF. This means it terminated itself.

Case 4:

When our application gets ANR.

So, to generate an ANR we will run an infinite loop on click of textView using,

So, when App gets an ANR the Log generated would be,

Here, the reason code is 6, which means REASON_ANR.

These are a few cases where we can log our exits form our application.

In this blog, we are using the maximum size as 1. If we change it to any number more then 1, let’s say maybe 10. It will return the list of last 10 exit reasons information. To set max size to 10, we update the code,

Читайте также:  Как прошить андроид тв бокс h96 max

This is how we can use getHistoricalProcessExitReasons to get the reasons for the exit of the app which might be very useful for developers to understand the user’s behavior of using the app or maybe checking for crashes.

Источник

How to detect Android application open and close: Background and Foreground events.

Dec 17, 2017 · 4 min read

This question seems to come up a lot. Especially if you are just starting out with Android developme n t. It’s simply because there is nothing obvious built into the Android SDK enabling developers to hook into application lifecycle events. Activities and Fragments have all the callbacks under the sun to detect lifecycle change, but there is nothing for the whole application. So how do you detect when a user backgrounds and foregrounds your app. This is an example of how your could detect Application lifecycle events. Feel free to adjust and enhance it to suit your needs, but this idea should be enough to work for most applications with one caveat, it will only work for Android API level 14+(IceCreamSandwich 🍦🥪).

Detecting App Lifecycle Evnts

Backgrounding

ComponentCallbacks2 — Looking at the documentation is not 100% clear on how you would use this. However, take a closer look and you will noticed the onTrimMemory method passes in a flag. These flags are typically to do with the memory availability but the one we care about is TRIM_MEMORY_UI_HIDDEN. By checking if the UI is hidden we can potentially make an assumption that the app is now in the background. Not exactly obvious but it should work.

Foregrounding

ActivityLifecycleCallbacks — We can use this to detect foreground by overriding onActivityResumed and keeping track of the current application state (Foreground/Background).

Implementing a Foreground and Background Handler

First, lets create our interface that will be implemented by a custom Application class. Something as simple as this:

Next, we need a class that is going to implement the ActivityLifecycleCallbacks and ComponentCallbacks2 we discussed earlier. So lets create an AppLifecycleHandler and implement those interfaces and override the methods required. And lets take an instance of the LifecycleDelegate as a constructor parameter so we can call the functions we defined on the interface when we detect a foreground or background event.

We outlined earlier that we could use onTrimMemory and the TRIM_MEMORY_UI_HIDDEN flag to detect background events. So lets do that now.

Add this into the onTrimMemory method callback body

So now we have the background event covered lets handle the foreground event. To do this we are going to use the onActivityResumed. This method gets called every time any Activity in your app is resumed, so this could be called multiple times if you have multiple Activities. What we will do is use a flag to mark it as resumed so subsequent calls are ignored, and then reset the flag when the the app is backgrounded. Lets do that now.

So here we create a Boolean to flag the application is in the foreground. Now, when the application onActivityResumed method is called we check if it is currently in the foreground. If not, we set the appInForeground to true and call back to our lifecycle delegate ( onAppForegrounded()). We just need to make one simple tweak to our onTrimMemory method to make sure that sets appInForeground to false.

Now we are ready to use our AppLifecycleHandler class.

AppLifecycleHandler

Now all we need to do is have our custom Application class implement our LifecycleDelegate interface and register.

And there you go. You now have a way of listening to your app going into the background and foreground.

This is only supposed to be used as an idea to adapt from. The core concept using onTrimMemory and onActivityResumed with some app state should be enough for most applications, but take the concept, expand it and break things out it to fit your requirements. For the sake of brevity I won’t go into how we might do multiple listeners in this post, but with a few tweaks you should easily be able to add a list of handlers or use some kind of observer pattern to dispatch lifecycle events to any number of observers. If anyone would like me to expand on this and provide a multi listener solution let me know in the comments and I can set something up in the example project on GitHub.

Update: Using Android Architecture Components

Thanks to Yurii Hladyshev for the comment.

If you are using the Android Architecture Components library you can use the ProcessLifecycleOwner to set up a listener to the whole application process for onStart and onStop events. To do this, make your application class implement the LifecycleObserver interface and add some annotations for onStop and onStart to your foreground and background methods. Like so:

Источник

Android Application Class

W hile Starting App development, we tend to miss out simple basic stuffs either by ignorance or by curiosity to build million dollar app. But, Hey! Why so serious !. Building a App is bit of Art ,bit of Engineering and frequently both.

Activity Life Cycle is stages of activity in run time, knowing these would save you from headaches while you dive deeper in development.

I have written a post that will help you to understand activity lifecycle in a practical approach. Check it out

Android Activity Lifecycle

Android activity lifecycle is first thing to be known as android developer. Here I’m sharing with you some facts and…

Application class is a base class of Android app containing components like Activities and Services. Application or its sub classes are instantiated before all the activities or any other application objects have been created in Android app.

Читайте также:  Htc u ultra android 9

You Don’t have to import or extend application class, they are predefined. We cannot change application class but we could give additional instruction to it by extending it. Refer here for more info.

Create a java class named SubApplication and Application as Superclass

By extending Application class you could get boilerplate code like this

Check in AndroidManifest.xml and set Application name to SubApplication that you created

Lets take a situation where we should know which activity is currently running and we have to use register network receiver in all our activities. To this we used to write same code in all the activities or write a base class and extend that class instead of extending AppCompactActivity.

We have Activity Life cycle in one hand and Application class in another, what sense they make? Well actually they do? Let’s look into it.

  1. In application class create static Activity variable it is accessible from whole project.

2. Register Activity Life Cycle callback in onCreate method in application class. By this step we can get currently running activity in our app from mActivity.

3.Moving on to next, Create a Broadcast Receiver and write a method to check the internet connection. you can get the code here .

4. Register your broadcast receiver in Manifest File

But for SDK Above Nougat we need to register receiver and unregister in every activity we use programmatically or We can just register and unregister Commonly in Application class.

5. Create a Object for Broadcast Receiver in application class and Register it in onResume method and Unregister in onPause method.

Bit confused! Don’t Worry, Here is the Link to the files.

Thanks for reading out the article. Let me know if I have missed out something interesting so that I can be added. Be sure to clap/recommend as much as you can and also share with your friends.

Источник

Build an Android Application with Authentication

With mobile apps becoming ever-present in users’ lives, following best security practices has become essential in protecting your users and your apps. Implementing security alone and from the ground up can be costly for your development team, create a less-than-ideal user experience, and be susceptible to design/implementation errors. The easiest path to strong security, and a positive user experience, is to turn to the experts.

The Okta OIDC SDK can help with this in many ways: — Our security experts take the development effort of creating a secure authentication method off your plate — OAuth 2.0 and OpenID Connect allows your users to easily authenticate on your app with social login, using industry-standard secure protocols

This post will show you a simple example of how you can use Okta OIDC SDK to create a (Kotlin) Android app with authentication.

(TLDR) Download the Finished App with Android Authentication

If you want to follow along using a completed version of the app, clone this repository from GitHub:

Create Your First Android App

First, you’ll need to download and install Android Studio. Next, launch the app and navigate to FileNew…​New Project…​. Then, create an «Empty Activity» for «Phone and Tablet». You should now see a screen similar to this:

Choose a «Package name» related to a domain you own (I own akaita.com, therefore I used com.akaita.myapplication in the example), a Save location you can remember, «Kotlin», and a «Minimum API level» of 23 . Finally, click Finish.

Get Your Okta OIDC Configuration Settings

Before you begin, you’ll need a free Okta developer account. Install the Okta CLI and run okta register to sign up for a new account. If you already have an account, run okta login . Then, run okta apps create . Select the default app name, or change it as you see fit. Choose Native and press Enter.

Use com.okta.dev-133337:/callback for the Redirect URI and set the Logout Redirect URI to com.okta.dev-133337:/logout (where dev-133337.okta.com is your Okta domain name). Your domain name is reversed to provide a unique scheme to open your app on a device.

The Okta CLI will create an OIDC Native App in your Okta Org. It will add the redirect URIs you specified and grant access to the Everyone group. You will see output like the following when it’s finished:

NOTE: You can also use the Okta Admin Console to create your app. See Create a Native App for more information.

Add a Sign-in Button to Your Android App

Now that you’ve finished up in Okta’s Admin Panel, head back to Android Studio and add a button to your res/layout/activity_main.xml . Replace the contents of this file with the XML below.

This button will be used to authenticate using OAuth 2.0 + OpenID Connect, thanks to the Okta OIDC SDK.

Give Your Android App Permission to Use the Internet

In your app/src/main/AndroidManifest.xml add the following XML just before the opening tag:

Add Okta OIDC SDK to Your Android App

Modify your app/build.gradle to add the Kotlin Android Plugins to make it easy to bind XML views to your code.

You’ll also need to add a manifestPlaceholder for appAuthRedirectScheme in app/build.gradle . Make sure it is consistent with your Redirect URIs. For instance, my redirect URIs look like com.okta.dev-123456:/callback , therefore my appAuthRedirectScheme is com.okta.dev-123456

12345
Add the Kotlin Android Extension plugin
Keep you applicationId here.
The redirect URI for the application you created in your Okta Developer Console.
Okta OIDC libraries require Java 1.8 compatibility.
Add the dependency required for the Okta OIDC library.
Читайте также:  Андроид как блютуз для компа

Configure Okta OIDC in Your Android App

In your MainActivity class, add a couple of class properties and a couple of new methods, calling them from onCreate() :

1234
private lateinit var webAuth: WebAuthClient is a reference to the web client you will invoke to log in
private lateinit var sessionClient: SessionClient is a reference to the session you can use to conduct multiple operations after logging in, such as getting the user’s profile, revoking the authentication token, refreshing the authentication token, etc…​
setRequireHardwareBackedKeyStore(true) forces the app to require a device with encryption capabilities. This is the default configuration for Okta OIDC and it’s considered the best practice. Since you might to run this code in a emulator, you can temporarily set it to false .
private fun setupWebAuthCallback() is the place where you can define the action to take when authentication succeeds, fails or is canceled…​
You can create a utility method to automatically detect if your application is running in an emulator.

Make sure to use the values you wrote down during the Get your Okta OIDC configuration settings step to create val oidcConfig in private fun setupWebAuth() .

Log in Using Okta OIDC

Now that you have a minimal configuration of Okta OIDC, it’s time to add a listener for the signIn button you added previously.

Create a payload using AuthenticationPayload and call webAuth.signIn() in MainActivity.kt .

This will instruct Okta OIDC SDK to launch a web browser in which your users can authenticate using their Okta credentials.

Once they successfully authenticate, you will be able to use sessionClient to do things like check their authentication status:

You can even download their profile:

That’s it! You now have an Android app with robust OIDC authentication!

When you launch your app and click on the SIGN IN button, you will be greeted with Okta’s authentication portal, which you can use to authenticate users into your app:

(Optional) Add Social login

It should be easy for users to authenticate into your app. Okta OIDC SDK helps you accomplish this by allowing users to use their social accounts to validate their identity.

With Okta, you can add an external Identity Provider—such as Google, Facebook, LinkedIn or Microsoft. To achieve this, connect to the external identity providers and ask them to trust Okta for your application. This is done in three simple steps:

Lastly, use the identity providers in your app:

Now, when a user clicks your SIGN IN button, they’ll be greeted with the login page of the IDP of your choice, which will be used to authenticate users into your app.

(Optional) Biometric Login

Additionally, biometrics can be used to access sessions created by Okta OIDC. The BiometricPrompt recently published by the Android team makes it a very feasible option, taking a lot of the complexity off your hands and offering a unified familiar & native experience for users on all variants of Android (Google devices, Samsung devices, …​).

BiometricPrompt uses the available resources in each device to offer whichever options are possible. Those include Iris authentication, fingerprint authentication, PIN authentication, Pattern authentication, etc.

In essence, there are two components to be taken into account:

BiometricPrompt can be used to only allow biometrically authenticated users into your app, or into specific sections of your app

You can (and should) instruct Okta OIDC SDK to store all data in a biometrically protected encryption system

I created an easy-to-launch Kotlin wrapper of BiometricPrompt for you:

Simply trigger this so that when a user who is not biometrically authenticated tries to launch MainActivity , they are only allowed through if they biometrically authenticate in their device. Also, remember to use GuardedEncryptionManager to store Okta OIDC data:

Now, whenever a user opens a new instance of your app, they will be able to access it using their biometric information. In the below example, a Google Pixel phone, the authentication is a fingerprint:

Learn More About Android Auth and OIDC

It’s now easier than ever to implement OAuth 2.0 and OpenID authorization thanks to Okta OIDC SDK. A high effort, high maintenance chore just became a very straightforward task.

By taking advantage of BiometricPrompt and Kotlin, we can make our apps even safer, while still creating a seamless user experience that feels native to each manufacturer’s UI style.

Although the example we’ve created here does enough to satisfy the needs of the majority of apps, Okta OIDC SDK doesn’t stop there. The Okta OIDC Android repository contains a variety of ideas and suggestions to improve user experience like:

Using your own OkHttp client

Using a custom UI to log in

Having fine-grained control over session tokens’ expiration, refresh, etc…​

Settings to handle preference of browser client for the authentication process (Chrome, Samsung browser, Firefox, etc…​)

As a reminder, you can find the source code for this example on GitHub.

This post has given you the foundations to set up a successful OIDC client. If you want to deepen your knowledge around modern authentication systems, check these additional resources on Android, OAuth 2.0 and OpenID Connect:

If you enjoyed this blog post and want to see more like it, follow @oktadev on Twitter, subscribe to our YouTube channel, or follow us on LinkedIn. As always, please leave your questions and comments below—we love to hear from you!

Changelog:

  • Dec 24, 2020: Updated to Okta OIDC for Android v1.0.17. See the code changes in the example app on GitHub. Changes to this article can be viewed in oktadeveloper/okta-blog#510.

Okta Developer Blog Comment Policy

We welcome relevant and respectful comments. Off-topic comments may be removed.

Источник

Оцените статью