Android what applications are running

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 …

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

Читайте также:  Андроид авто не работает с huawei

Источник

Running Your Android Application on an Android Device

After you prepare your development system for Android development, enable USB debugging in your Android device and configure your system to detect your Android device, you can run a FireMonkey mobile application on a connected Android device.

  1. Connect your Android device to your development system using your device’s USB cable. You should see your Android device listed under Portable Devices in the Device Manager (available from the Control Panel). For more information, see Configuring Your System to Detect Your Android Device.
  2. In RAD Studio, select either File > New >FireMonkey Mobile Application — Delphi or File > New >FireMonkey Mobile Application — C++Builder .
  3. In the Project Manager, activate (double-click) the Android target platform.
  4. Enable the Android SDK for your device:
    1. In the Project Manager, right-click the Android node and select Properties.
    2. In Platform Properties, click the down-arrow in the SDK (Software Development Kit) field and select either:
      • Your installed Android SDK version, if it is displayed
      • Add New
        1. In the Add a New SDK dialog box, click the down-arrow in the Select an SDK version field and select your installed Android SDK.
        2. Complete the fields in the Create a New Android SDK wizard. Most of the fields are completed automatically by the wizard.
  5. Enable your Android device as the target platform: In the Android target platform in the Project Manager, open the Target node and double-click your Android device. When your Android device is correctly installed, the SDK version number appears after the Android target name; for example: Android — Android SDK 22.0.1Tips: If your device is not shown, try these steps:
    1. In the IDE, right-click the Target node and select Refresh.
    2. In the Control Panel, open the Device Manager:
      1. Verify that your Android device is listed, typically under Portable Devices.
      2. If your device is not listed, right-click any node and select Scan for hardware changes.
      3. If necessary, use the Android SDK Manager to uninstall and then reinstall the device driver for your Android device. Select Start | All Programs | Embarcadero RAD Studio XE6 | Android Tools .

    The following image shows a populated Android Target node displaying the Nexus 10 device, one emulator that is running, and several emulators that are not running:

  6. If you selected the Application Store platform configuration on the Configuration node of the Project Manager, you must have a signing certificate configured for the Application Store platform configuration on the Provisioning page. The Debug platform configuration does not require a signing certificate.
  7. Run your application:
    • Run with debugging ( Run >Run or F9 )
    • Run without debugging ( Run >Run Without Debugging or Shift+Ctrl+F9 ).

RAD Studio builds your application for Android and runs your application on the selected Android device. If your Android device screen is locked, unlock it to access your application.

Running Your Application with Clean Data and Cache Folders

When you run an application on an Android device, RAD Studio installs your application on your device using the package name that you defined in the Version Info options page to uniquely identify your application. By default, the package name is «com.embarcadero.$(ModuleName)», where $(ModuleName) is the name of your project, such as «Project1».

If you run your application on a device that already contains a previously-installed application with the same package name as the application that you want to run, the Run command reinstalls your application, but only updates the application executable; your application’s data and cache folders are not updated.

To configure RAD Studio so that the Run Without Debugging and Run actions completely uninstall any previously-installed version of your application, including the data and cache folders, before installing the newer version:

  1. Select Run >Parameters .
  2. Enter «-cleaninstall» in the Parameters field:
  3. Click OK to save your changes.

Troubleshooting

Stuck at «Uninstalling» on the Run Dialog Box

You might need to enable USB debugging specifically for your computer if you are running Android 4.2.2 or later and when you click Run or Run Without Debug, RAD Studio does not go beyond the following screen:

You might also need to enable the general USB debugging setting in your device. If this is the case, your device should show a dialog box asking you to allow USB debugging:

Click OK to allow USB debugging.

If you accidentally click Cancel, disconnect your device from your PC and then reconnect it to make the dialog box reappear on your device.

Источник

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.

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.

Источник

Читайте также:  Tv приставка android 4500
Оцените статью