- Как создавать лаунчеры для андроид
- Build a Custom Launcher on Android
- Introduction
- 1. Requirements
- 2. Project Setup
- 3. Project Manifest
- 4. Activity Layouts
- 5. Implementing the Activity Classes
- HomeActivity
- AppsListActivity
- 6. Fetching Applications
- 7. Displaying the List of Applications
- 8. Listening for Clicks
- 9. Putting It All Together
- Conclusion
Как создавать лаунчеры для андроид
Если очень грубо определить, что такое лаунчер, то это приложение, которое может представлять домашний экран устройства и показывать список работающих на устройстве приложений. Другими словами, лаунчер это то, что вы видите при нажатии кнопки Home на устройстве. Сейчас вы скорее всего используете стандартный лаунчер, который был установлен вместе с операционной системой. На Play Market существует множество таких программ, установив которые, вы можете видоизменить оформление своего аппарата:
Фактически каждый производитель смартфонов и планшетов имеет свой собственный лаунчер и стиль оформления (например, Samsung — TouchWiz, HTC — Sense).
В этом уроке мы научимся создавать простой лаунчер с базовым пользовательским интерфейсом. В нашем приложении будет два экрана:
— домашний экран, отображающий обои рабочего стола;
— экран, показывающий список установленных приложений и некоторую информацию о них;
Итак, начинаем. Создаем новый проект, названия традиционно оставляем по умолчанию, можете ввести какие нибудь свои. Минимальная версия для запуска приложения — Android 2.2, выбираем Blank Activity.
Сразу идем редактировать файл манифест приложения. Нам нужно добавить здесь 2 activity и задать им некоторые настройки. Открываем файл AndroidManifest.xml и добавим туда следующее:
В этот код мы добавили категории android.intent.category.HOME и android.intent.category.DEFAULT для того, чтобы наше приложение вело себя как лаунчер и отображалось при нажатии на кнопку Home устройства.
Также нужно настроить режим запуска launchMode на singleTask для того, чтобы на данный момент работает только одно нужное Activity. Для отображения пользовательской картинки на заставке, мы использовали настройку темы Theme.Wallpaper.NoTitleBar.FullScreen.
Второе activity, как уже было сказано, будет отображать установленные на устройстве приложения и немного информации о них. Для этой activity не будет использоваться никаких особенных настроек, назовем ее AppsListActivity:
Создадим xml файл разметки для будущего класса HomeActivity. В папке res/layout создаем файл по имени activity_home.xml. Он будет содержать всего одну кнопку, при нажатии на которую пользователь с домашнего экрана будет попадать на экран со списком установленных приложений:
Далее создаем файл xml для AppsListActivity в той же папке, назовем его activity_apps_list.xml. Он будет содержать ListView для отображения списка приложений:
Создаем еще один xml файл по имени list_item.xml. Этот файл будет определять вид заданного выше ListView. Каждый пункт списка будет представлять одно установленное на устройство приложение. Здесь будет отображаться иконка, название и имя пакета приложения. Отображение иконки будет происходить через элемент ImageView, а имя приложения и пакета в TextView:
Теперь нужно создать необходимые java классы. Когда будете создавать классы, убедитесь, что они связаны с данными в файле манифеста, что мы выполняли в начале.
Создаем в приложении файл HomeActivity.java, задаем ему наследование от класса Activity и настраиваем переход на другой экран со списком приложений при нажатии на кнопку, созданную нами ранее (подробный урок по созданию перехода):
Создаем еще одно activity с именем AppsListActivity.java. Настроим этому классу вид интерфейса с ранее созданного файла activity_apps_list.xml:
Уже сейчас можно попробовать протестировать приложение на эмуляторе/устройстве. Пока, что оно не обладает желаемым функционалом, но все же. Запустите приложение и нажмите кнопку Home, вы увидите окно в котором вам будет предложено выбрать лаунчер для запуска, стандартный и наш. Запускаем наш и видим примерно следующее:
Мы видим заставку рабочего стола и нашу кнопку запуска второго activity.
Полюбовались и хватит, возвращаемся к работе в Android Studio. Создаем еще один класс по имени AppDetail, который будет содержать более детальную информацию о приложении, название пакета, имя приложения и иконку. Код этого класса предельно простой и выглядит так:
В методе loadApps класса AppsListActivity мы используем метод queryIntentActivities, он нужен для того, чтобы выбрать все объекты Intent, которые имеют категорию Intent.CATEGORY_LAUNCHER. Запрос будет возвращать список приложений, которые могут быть запущены нашим лаунчером. Мы запускаем цикл по результатам запроса и создаем и добавляем каждый его пункт в список по имени apps. Чтобы реализовать все сказанное, добавляем следующий код:
Теперь нужно настроить отображение списка приложений. В созданном списке apps мы поместили все необходимые данные о приложении, теперь их надо отобразить в созданном в начале урока ListView. Для этого мы создаем ArrayAdapter и описываем метод getView, а также связываем ArrayAdapter с ListView:
Когда пользователь нажимает на пункты списка с приложениями, то наш лаунчер должен запускать соответствующее приложение. Это будет выполняться благодаря методу getLaunchIntentForPackage , создающего намерение Intent, запускающее нужное приложение:
Осталось собрать все описанные выше методы в один рабочий механизм. В классе AppsListActivity вызываем методы loadApps, loadListView и addClickListener:
Запускаем наше приложение. Теперь при нажатии на кнопку вызова второго activity «Show Apps» мы видим список из установленных приложений. При нажатии на выбранный элемент списка, мы будем запускать соответствующее приложение:
Поздравляю! Теперь в придачу до собственных калькулятора, браузера, конвертера и много другого, мы имеем еще и собственный Android Launcher. Надеюсь урок был вам интересен и полезен.
Источник
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.
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.
Источник