Android launcher activity example

Build a Custom Launcher on Android

Introduction

In its most basic form, a launcher is an application that does the following:

  • it represents the home screen of a device
  • it lists and launches applications that are installed on the device

In other words, it is the application that shows up when you press the home button. Unless you’ve already installed a custom launcher, you are currently using the default launcher that comes with your Android installation. A lot of device manufacturers have their own default, custom launchers that conform to their proprietary look and feel, for example, Samsung TouchWiz and HTC Sense.

In this tutorial, we are going to create a simple launcher with a basic user interface. It will have two screens:

  • a home screen showing the device’s wallpaper
  • a screen showing the icons and details of the applications installed on the device

By the way, if you work a lot with Android, you may want to check out one of the 1,000+ Android app templates on Envato Market. There’s a huge variety, so you’re sure to find something there to help you with your work. Or you could outsource areas that aren’t your speciality by hiring an app developer or designer on Envato Studio.

1. Requirements

You need to have the following installed and configured on your development machine:

  • Android SDK and platform tools
  • Eclipse IDE 3.7.2 or higher with the ADT plugin
  • an emulator or Android device running Android 2.2 or higher

You can download the SDK and platform tools the Android developer portal.

2. Project Setup

Launch Eclipse and create a new Android application project. I’m naming the application SimpleLauncher, but you can name it anything you want. Make sure you use a unique package. The lowest SDK version our launcher supports is Froyo and the target SDK is Jelly Bean.

Since we don’t want to create an Activity , deselect Create Activity. Click Finish to continue.

3. Project Manifest

The next step is modifying the AndroidManifest.xml file by adding two activities. The first Activity displays the home screen. Let’s name it HomeActivity as shown below.

By adding the categories android.intent.category.HOME and android.intent.category.DEFAULT to the intent-filter group, the associated Activity behaves like a launcher and shows up as an option when you press the device’s home button.

We also need to set the launchMode to singleTask to make sure that only one instance of this Activity is held by the system at any time. To show the user’s wallpaper, set the theme to Theme.Wallpaper.NoTitleBar.FullScreen .

The second Activity we need to add displays the applications that are installed on the user’s device. It’s also responsible for launching applications. We don’t need any special configuration for this Activity . Name it AppsListActivity .

4. Activity Layouts

Create an XML file for the HomeActivity class in the project’s res/layout folder and name it activity_home.xml. The layout has a single Button that responds to click events. Clicking the button takes the user from the home screen to the list of applications.

Next, create an XML file for the AppsListActivity class in the project’s res/layout folder and name it activity_apps_list.xml. The layout contains a ListView that takes up the entire screen.

Читайте также:  Layout spinner android studio

Finally, create a third XML file in the same location and name it list_item.xml. This file defines the layout of an item in the ListView . Each list view item represents an application installed on the user’s device. It shows the application’s icon, label, and package name. We display the application icon using an ImageView instance and TextView instances for the label and package name.

5. Implementing the Activity Classes

HomeActivity

With the layouts of the application created, it’s time to create the two Activity classes. When creating the two classes, make sure the name of each class matches the one you specified in the project’s manifest file earlier.

Create a new class named HomeActivity and set android.app.Activity as its superclass.

In the class’s onCreate method, we invoke setContentView , passing in the layout we created earlier. You may remember that we added a button to the activity_home layout that triggers a method named showApps . We now need to implement that method in the HomeActivity class. The implementation is pretty simple, we create an Intent for the AppsListActivity class and start it.

AppsListActivity

Create another Activity class named AppsListActivity and set android.app.Activity as its superclass. In the class’s onCreate method, we invoke setContentView , passing in the activity_apps_list layout we created earlier.

Even though our launcher isn’t finished yet, you can save and run your application at this point. When you press the device’s home button, you should see a pop-up asking you which launcher you’d like to use.

If you choose Simple Launcher Home, you should see your new home screen with a single button in the top right corner of the screen. You should also see your device’s current wallpaper.

Go back to Eclipse and create a class named AppDetail that will contain the details of an application, its package name, label, and application icon. The interface is pretty basic as you can see below.

6. Fetching Applications

In the loadApps method of the AppsListActivity class, we use the queryIntentActivities method of the PackageManager class to fetch all the Intents that have a category of Intent.CATEGORY_LAUNCHER . The query returns a list of the applications that can be launched by a launcher. We loop through the results of the query and add each item to a list named apps . Take a look at the following code snippet for clarification.

7. Displaying the List of Applications

With the apps variable containing all the details we need, we can show the list of applications using the ListView class. We create a simple ArrayAdapter and override its getView method to render the list’s items. We then associate the ListView with the adapter.

8. Listening for Clicks

When the user clicks an item in the ListView , the corresponding application should be launched by our launcher. We use the getLaunchIntentForPackage method of the PackageManager class to create an Intent with which we start the application. Take a look at the following code snippet.

9. Putting It All Together

To make everything work together, we need to invoke loadApps , loadListView , and addClickListener in the onCreate method of the AppsListActivity class as shown below.

Build and run your application once more to see the result. You should now be able to see the applications that can be launched when you click the button on the home screen of our launcher. Click on an item to launch the corresponding application.

Conclusion

You now have your own custom launcher. It’s very basic, but you can add all the customizations you want. If you want to dig deeper into custom launchers, I encourage you to take a look at the sample applications on the Android Developer Portal.

Читайте также:  Режим управления одной рукой android отключить

Источник

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

Источник

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