Android app that could

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:

Читайте также:  Boot меню самсунг андроид

Источник

Android Application Launch explained: from Zygote to your Activity.onCreate()

Apr 30, 2018 · 6 min read

This article explains how Android launches your application when a user clicks an app icon. The Android system does a lot of heavy lifting behind the curtains to make your launch activity visible to a user. This article covers this process in detail by highlighting the important phases and call sequences.

Android applications are unique in two ways:

  1. Multiple Entry points: Android apps are composed of different components and they can invoke the components owned by other apps. These components roughly correspond to multiple entry points for any application. Hence, they differ from traditional applications which have a single entry point like main() method.
  2. Own Little World: Every Android application lives in its own world, it runs in a separate process, it has its own Dalvik VM instance and is assigned a unique user ID.

When does Android process start?

An Android process is started whenever it is required.

Any time a user or some other sys t em component requests a component (could be a service, an activity or an intent receiver) that belongs to your application be executed, the Android system spins off a new process for your app if it’s not already running. Generally processes keep running until killed by the system. Application processes are created on demand and a lot of things happen before you see your application’s launch activity up and running.

Every app runs in its own process: By default, every Android app runs in its own Android process which is nothing but a Linux process which gets one execution thread to start with. For example, when you click on a hyper-link in your e-mail, a web page opens in a browser window. Your mail client and the browser are two separate apps and they run in their two separate individual processes. The click event causes Android platform to launch a new process so that it can instantiate the browser activity in the context of its own process. The same holds good for any other component in an application.

Zygote : Spawning new life, new process

Let’s step back for a moment and have a quick look on system start-up process. Like the most Linux based systems, at startup, the boot loader loads the kernel and starts the init process. The init then spawns the low level Linux processes called “daemons” e.g. android debug daemon, USB daemon etc. These daemons typically handle the low level hardware interfaces including radio interface.

Init process then starts a very interesting process called ‘ Zygote ’.

As the name implies it’s the very beginning for the rest of the Android application. This is the process which initializes a very first instance of Dalvik virtual machine. It also pre-loads all common classes used by Android application framework and various apps installed on a system. It thus prepares itself to be replicated. It stats listening on a socket interface for future requests to spawn off new virtual machines (VM)for managing new application processes. On receiving a new request, it forks itself to create a new process which gets a pre-initialized VM instance.

After zygote, init starts the runtime process.

The zygote then forks to start a well managed process called system server. System server starts all core platform services e.g activity manager service and hardware services in its own context.

At this point the full stack is ready to launch the first app process — Home app which displays the home screen also known as Launcher application.

When a user clicks an app icon in Launcher …

The click event gets translated into startActivity(intent) and it is routed to ActivityManagerService via Binder IPC. The ActvityManagerService performs multiple steps

  1. The first step is to collect information about the target of the intent object. This is done by using resolveIntent() method on PackageManager object. PackageManager.MATCH_DEFAULT_ONLY and PackageManager.GET_SHARED_LIBRARY_FILES flags are used by default.
  2. The target information is saved back into the intent object to avoid re-doing this step.
  3. Next important step is to check if user has enough privileges to invoke the target component of the intent. This is done by calling grantUriPermissionLocked() method.
  4. If user has enough permissions, ActivityManagerService checks if the target activity requires to be launched in a new task. The task creation depends on Intent flags such as FLAG_ACTIVITY_NEW_TASK and other flags such as FLAG_ACTIVITY_CLEAR_TOP.
  5. Now, it’s the time to check if the ProcessRecord already exists for the process.If the ProcessRecord is null, the ActivityManager has to create a new process to instantiate the target component.

As you saw above many things happen behind the scene when a user clicks on an icon and a new application gets launched. Here is the full picture :

There are three distinct phases of process launch :

  1. Process Creation
  2. Binding Application
  3. Launching Activity / Starting Service / Invoking intent receiver …
Читайте также:  Idle home makeover андроид

ActivityManagerService creates a new process by invoking startProcessLocked() method which sends arguments to Zygote process over the socket connection. Zygote forks itself and calls ZygoteInit.main() which then instantiates ActivityThread object and returns a process id of a newly created process.

Every process gets one thread by default. The main thread has a Looper instance to handle messages from a message queue and it calls Looper.loop() in its every iteration of run() method. It’s the job of a Looper to pop off the messages from message queue and invoke the corresponding methods to handle them. ActivityThread then starts the message loop by calling Looper.prepareLoop() and Looper.loop() subsequently.

The following sequence captures the call sequence in detail —

The next step is to attach this newly created process to a specific application. This is done by calling bindApplication() on the thread object. This method sends BIND_APPLICATION message to the message queue. This message is retrieved by the Handler object which then invokes handleMessage() method to trigger the message specific action — handleBindApplication(). This method invokes makeApplication() method which loads app specific classes into memory.

This call sequence is depicted in following figure.

Launching an Activity:

After the previous step, the system contains the process responsible for the application with application classes loaded in process’s private memory. The call sequence to launch an activity is common between a newly created process and an existing process.

The actual process of launching starts in realStartActivity() method which calls sheduleLaunchActivity() on the application thread object. This method sends LAUNCH_ACTIVITY message to the message queue. The message is handled by handleLaunchActivity() method as shown below.

Assuming that user clicks on Video Browser application. the call sequence to launch the activity is as shown in the figure.

The Activity starts its managed lifecycle with onCreate() method call. The activity comes to foreground with onRestart() call and starts interacting with the user with onStart() call.

Thanks for reading through 🙌🏼. If you found this post useful, please applaud using the 👏 button and share it through your circles.

This article was initially published as two part series (Part 1 and Part 2) on my blog ./ mult-core-dump in 2010. These articles have been cited in multiple documents including the very famous Introduction to the Android Graphics Pipeline

Источник

15 best Android apps available right now

Here it is ladies and gentlemen. The crème de la crème. The Android apps that stand alone at the top of the pantheon. These apps have become ubiquitous with Android and if you’re looking for good stuff it’s assumed that you have some of this stuff already. There are a ton of amazing Android apps out there. However, there are a few that stand out above the rest. These apps are useful to just about everyone no matter what their use case may be. Without further delay, here are the best Android apps currently available.

Most people should be relatively familiar with most of these apps. They are the best, and the best things are rarely anonymous. It’s difficult to get into the hall of fame, but we do have the best lists attached to each selection in case you want to see more options.

The best Android apps available right now:

1Weather

Price: Free / $1.99

1Weather is arguably the best weather app out there. It features a simple, paginated design that shows you the current weather, forecast for up to 12 weeks, a radar, and other fun stats. Along with that, you’ll get a fairly decent set of lightly customizable widgets and the standard stuff like severe weather notifications and a radar so you can see the storms approaching. The Ui is logical and reasonably easy to navigate as well.

The free version has all of the features with advertising. The $1.99 charge removes advertising. Otherwise, the two versions work the same way. Most will also likely enjoy the range of weather fun facts as well when you open the app. We have a list of the best weather apps and widgets if you want more options.

Google Drive

Price: Free / $1.99-$299.99 per month

Some of the features of these apps include live collaboration, deep sharing features, and compatibility with Microsoft Office documents. You can find more cloud storage apps here and more office apps here if you want something different.

Google Maps and Waze

Price: Free

If you add to that the Waze experience, which includes tons of its own features, and you won’t need another navigation app. Ever. Google also owns and operates Waze. It’s unique and fun in ways that Google Maps isn’t and we also highly recommend it. Of course, we have more GPS apps options as well here if you need them.

Google Search / Assistant / Feed

Price: Free

There is also a second Google Assistant app for those who want a quick launch icon on the home screen. The hardware stuff costs money, but Google Assistant is free. There are other decent personal assistants like Amazon Alexa, and you can check them out here.

Читайте также:  Лучший атлас мира для андроид

LastPass

Price: Free / $12 per year

LastPass is one of those must-have Android apps. It’s a password manager that lets you save your login credentials in a safe, secure way. On top of that, it can help generate nearly impossible passwords for you to use on your accounts. It’s all controlled with a master password. It has cross-platform support (premium version only) so you can use it on computers, mobile devices, tablets, or whatever.

There are others, but LastPass always feels like it’s one step ahead. Additionally, the premium version is cheap. You can also grab LastPass Authenticator to go along with it for added security. There are other options for great password managers here and some free LastPass alternatives if the new, more restricted free version isn’t doing it for you. LastPass also has an authenticator app for additional security.

Read more:

Microsoft SwiftKey

Price: Free

Microsoft SwiftKey Keyboard is one of the most powerful and customizable third-party keyboards available. It hit the market several years ago with a predictive engine unlike anything any other keyboard had and the app has grown a lot of over the years. It’s a free download and you can purchase themes for it if you want to.

Other features include a dedicated number row, SwiftKey Flow which allows for gesture typing, multiple language support, cross-device syncing of your library, and much more. It’s about as good as it gets in the keyboard space. It’s true that Microsoft now owns SwiftKey, but so far they have managed not to mess it up. Gboard, Google’s keyboard app, is also exceptionally good and we honestly could’ve listed either one. There are some other great Android keyboards here as well.

Nova Launcher

Price: Free / $4.99

You can even make it look like the Pixel Launcher if you want to. If you go premium, you can tack on gesture controls, unread count badges for apps, and icon swipe actions. Those looking for something simpler may want to try Lawnchair Launcher, Hyperion Launcher, and Rootless Launcher. Of course, we have a list of the best Android launchers with even more options as well.

Podcast Addict

Price: Free / $3.99

You can also set download rules, create playlists easily, and it supports both Chromecast and SONOS along with Android Auto and Wear OS. The UI and settings aren’t the most elegant things we’ve seen. However, the app makes up for it by hitting literally every other box we could think of. Pocket Casts and CastBox are other excellent options in this space, and we have a list of even more great podcast apps here.

Poweramp

Price: Free trial / $4.99

The UI has a tiny bit of a learning curve, but it’s one of the better-looking music players as well with optional themes in the Google Play Store. There are other great music apps here, but the top slot arguably Poweramp’s title to lose. Poweramp also has an equalizer app (Google Play link) if you want a better equalizer app.

Solid Explorer

Price: Free trial / $2.99

File browsing is something everyone inevitably has (or wants) to do, so you might as well do it with a capable, fantastic file browser. Solid Explorer is pretty much as good as it gets in the file explorer apps realm. It features Material Design, archiving support, support for the most popular cloud services, and even some more power-user stuff like FTP, SFPT, WebDav, and SMB/CIFS support.

It looks great, it’s incredibly stable, and it just works well. There is a 14-day free trial with a $2.99 price tag at the end of it. There are other file browsers with more features, but few blend together looks, ease of use, and features like Solid Explorer does. If this doesn’t work for you, here are some other outstanding file browsers.

Check out some excellent hardware as well:

Tasker and IFTTT

Price: $2.99 and Free, respectively

Tasker is a glorious application if you have the patience to learn how to use the app. What it does is allow users to create custom made commands and then use them in various places. There are many apps out there that have Tasker support and you can even use Tasker to create very complex commands for NFC tags. It’s difficult to truly explain what this app can do because it can do so many things. Between the apps supported, plugins you can add, and the sheer volume of stuff that you can do, there aren’t many apps out there as useful as this one.

IFTTT is another excellent automation app. In some cases, it may even be better than Tasker thanks to its simplicity and wide range of uses. Tasker is also available free as part of the Google Play Pass. There are some other great Android tools and utility apps, but none of them can step up to Tasker and IFTTT.

Источник

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