Android SDK: Common Android Components
In this series we are learning the essential features of Android development that you need to know to start building apps. So far, we’ve looked at the structure and typical elements in an Android app, including user interface elements and data storage. You can use what we covered already to start creating your own apps. But before you do, we will run through some common Android components in this tutorial, then have a quick look at the SDK samples in the next tutorial.
Introduction
There are four main Android app components: activities , services , content providers , and broadcast receivers . Whenever you create or use any of them, you must include elements in the project manifest. We’ve met Activities already so I won’t spend any more time on them, but I will go through the other three main app components. I’ll also mention a couple of resources your apps are most likely to use, including fragments and the action bar .
1. Services
A service in Android is a background process. Services are typically used for processes that are ongoing or that take a significant period of time. A service doesn’t have a user interface, so they are often combined with other components such as activities . A typical example is an app in which an activity starts a service running on user interaction, with the service perhaps uploading data to a web resource. The user can continue to interact with the activity while the service runs because it executes in the background.
To add a service component to the manifest, use the following syntax with the element placed inside the application element:
You can create a service class in Eclipse using the same process you would for an activity, choosing service as the superclass. Services are different from the activity components that we’ve looked at previously, in a number of important ways. If you start a service that runs from an activity and the user navigates away from the activity to another app, the service will continue to run. A service therefore has a different lifecycle to the one we explored for activities. You need to bear this in mind to ensure your apps are efficient.
Other app components can bind to services, requesting and receiving data from them. If a bound service is running, it stops when all of the components that are bound to it stop. Although a service is separate from the app user interface, a service started in an activity will run in the same thread as it. However if your service is going to use a significant amount of processing resources, you can create a separate thread to run it in. For more on services, see the Android Developer Guide.
2. Content Providers
A content provider is a component for managing a data set. This data set can be private to your application or can be shared, with other apps able to query and modify the data. If you create a content provider to manage data for your own app, your UI components such as activities will use the content provider, typically through the content resolver class to interact with the data. When used by other apps, the content provider manages access to the data through standard methods to interact with structured data sets such as databases.
If you are at all familiar with relational databases, you intuitively understand the methods used to access data with a content provider. The content provider presents data in a set of tables with rows and columns, and each column within a row (or record) includes a single data value. Handling data returned through a content provider is therefore similar to handling database query results.
Although you may of course create a content provider app at some point, in your initial apps you are far more likely to access one created by another developer or the Android system itself, for example the device calendar or contacts. Content providers can define permissions that client apps are required to have in order to use them. To use a content provider in your app, you need to add the relevant permissions for it in your manifest.
See the Content Providers section in the Android Developer Guide for more information.
3. Broadcast Receivers
The Android system makes various types of broadcasts an app can respond to. You can also develop apps to make these broadcasts, but this is far less likely than to listen for existing broadcasts, at least for your first apps. System announcements include information about the device’s hardware, such as the battery level, the screen shutting off, the charger being plugged into an outlet, etc.
To receive broadcast announcements on Android, your apps can use a broadcast receiver . A typical example of this is a battery level widget in which you want to update the display when the battery level changes. In this case, you could use a service class in conjunction with a broadcast receiver to let your app keep listening for announcements in the background.
The Android system models broadcast announcements as intents , which can be used to start an activity . An intent is an action that the system performs, such as launching an activity or making an announcement. To use a broadcast receiver, your apps must declare it in the manifest, along with an optional intent filter , indicating the actions you want to receive:
This applies to a broadcast receiver in which your app can receive the battery low intent. Note that you can’t receive all system announcements by declaring their actions in the manifest in this way. In some cases you need to register to receive them in Java, for example, with the BATTERY_CHANGED action. See the broadcast receiver class for more on this type of app.
4. Other Classes
As we’ve seen, the Android components are designed to provide interaction between apps. Just as broadcast announcements are available to any app on the system, Android provides certain actions you can use to carry out common tasks in your apps, such as dialing a number. Similarly, you can often use functionality provided by other developers to carry out processing, saving on the amount of code you must implement yourself and letting you focus on the unique aspects of your apps. When you launch one intent from another, you can set it up to return a result to the launching activity, even if the intent that is launched is not part of your app. This lets your app continue to function after the requested action is completed.
Other Android components you should be aware of include fragment and the action bar . Let me briefly run through them:
Fragments
Rather than simply using an activity and a layout to define the whole user interface for each app screen, it is often more efficient to use fragments . With fragments, you can divide the parts of your user interface into logical sections and even reuse those sections in more than one screen of your app. This saves you from the task of implementing the same visual/interactive elements more than once and it gives you a single point of change for these sections. Fragments are modeled as part of an activity, so a fragment is tied to the lifecycle of the activity it is in. See the fragment section of the Developer Guide for more.
Action Bar
The action bar is another key user interface element you may find useful. The action bar gives your app a user interface component that is consistent across the Android system, which makes it an intuitive element for the platform’s users. Typical items displayed in the action bar include an indicator of the user’s location within your app if appropriate and shortcuts to common actions including navigation between the parts of the app. To use the action bar in an activity, make sure that your class extends the ActionBarActivity class and apply a AppCompat theme to the activity in the manifest. See the Developer Guide for more information about the action bar.
Conclusion
Which Android classes and components you use naturally depend on what your app does. However, the above components give you an overview of which classes and components you can choose from. It is often difficult to decide which component or class to use for a particular feature or function, so make sure you understand the purpose of each one before you make a decision. In the next few tutorials, we will look at the Android samples and the app publishing process.
Источник
Android компонент с нуля
Задание:
Разработать кнопку-бегунок, которая работает следующим образом: прямоугольная область, слева находится блок со стрелкой, показывающий направление сдвига:
Пользователь зажимает стрелку и переводит её в право, по мере отвода, стрелка вытягивает цветные квадратики:
Как только пользователь отпускает блок, то вся линия сдвигается влево и скрывает все показанные блоки. После скрытия последнего блока должно генерироваться широковещательное сообщение что лента полностью спрятана.
Подготовка
Для создания нового компонента создадим новый проект. Далее создаём новый класс с именем «CustomButton», в качестве предка используем класс «View». Далее создадим конструктор класса и в итоге наш будущий компонент будет иметь вид:
Теперь приступаем к написанию кода класса. Прежде чем начать писать код, скиньте в папку /res/drawable-hdpi, изображение разноцветной ленты. В конструкторе нужно перво наперво инициализировать все объекты и сделать все предварительные настройки. Делаем следующее:
1 — Копируем ссылку на контекст основной активности;
2 — Загружаем подготовленную заготовку-полоску разделённую цветными квадратиками;
3 — Настраиваем компонент необходимый для рисования на поверхности/
Также объявим объекты в начале класса:
Теперь нам необходимо переопределить процедуру настройки размеров компонента — onMeasure. Я специально сделал постоянные размеры для компонента (300*50) чтобы не усложнять пример. Процедура будет иметь вид:
Теперь переопределим процедуру перерисовки компонента «onDraw». Данная процедура вызывается каждый раз когда необходимо перерисовать компонент. Процедура будет иметь вид:
Заготовка для нашего нового компонента готова, давайте поместим её на главную активность. Во первых разместим на главной поверхности новый LinearLayout, под именем «LinearLayout1». Далее в конструкторе класса создадим класс для новой кнопки, создадим класс реализации«LinearLayout1» и добавим кнопку на поверхность. Класс активности будет иметь вид:
Если вы запустите проект на выполнение то на устройстве (эмуляторе) вы увидите примерно следующее:
Функционал
Теперь приступим к реализации анимации и реакции на внешние события. Когда пользователь нажимает на компонент интерфейса, предком которого является View, то автоматически генерируются события, в частности можно отследить координаты нажатия на компонент, и этапы нажатия (нажали, подвигали, отжали). Поэтому требуется переопределить процедуру onTouchEvent, отвечающую за внешние события. Процедура имеет один аргумент «MotionEvent event», он содержит в себе все параметры текущего события. Извлекаем эти параметры следующим образом:
Приводим процедуру к следующему виду:
Каждую строчку расписывать не буду, определю только главную идею. Пользователь нажимает на стрелку компонента, это действие фиксируется в переменной _Last_Action = 1, также фиксируем что пользователь не вытянул ни одного кубика из ленты — _X = 0. Далее отслеживаем перемещение пальца по компоненту и вычисляем сколько кубиков должно показаться на экране, для этого вычисляем _X. Принудительная перерисовка происходит с помощью команды invalidate(). В конце фиксируем отжатие пальца и запускаем таймер, если пользователь вытянул хотя бы один кубик. Таймер необходим чтобы возвращать полоску в исходное состояние не резко, а постепенно.
Теперь реализуем сам таймер, который будет возвращать полоску в исходное положение. Код таймера будет иметь вид:
В данной процедуре происходит цикличное выполнение операции уменьшения значения переменной _X на 1, тем самым показывая какой сектор должен быть показан на компоненте. Так как из дополнительных потоков нельзя влиять на внешний вид компонента, приходится посылать сообщения перерисовки через Handle. Поэтому в конструктор класса добавим реализацию перехвата сообщений для Handle и перерисовку внешнего вида виджета:
Теперь осталось изменить процедуру перерисовки виджета, а именно строку позиционирования ленты на поверхности (ширина одного квадратика на ленте, равна 60 pix, а общая длинна составляет 300 pix):
Добавим все переменные в начало реализации класса.
В итоге класс будет меть вид:
Внешние сообщения
Сильно мудрить не будем, реализуем событие что «лента спрятана» с помощью широковещательных сообщений. В реализации таймера добавим строки отправки сообщений:
В переменной «Name» хранится имя нашего компонента. Для сохранения имени, создадим дополнительную процедуру:
Добавим в блок объявления объектов имя компонента — public String Name.
Теперь в конструкторе нашей активности добавим перехватчик широковещательных сообщений:
После строки создания объекта кнопки, добавим строку передачи нового имени в объект:
Источник
get application name from package name
I want to get the application name from application package name. Somebody please show me how I can get this.
5 Answers 5
You can use PackageManager class to obtain ApplicationInfo :
This would return the application name as defined in tag of its manifest.
and replace packageName with your package full name.
you can get packageName using mContext.getPackageName() where mContext = yourActivityName.this for Activity and getActivity() for fragment.
It seems that you are able to receive the event of new package added after that its a very simple concept to get the all relevant information about that package like one such information is the application name so here is the concept
-> your device package manager has all the information related to it so just make an object of that it will give you all the information related with the package name.
-> You should also remember that the intent gives you «package: real_package_name» so first you have to get real name first by spilling(I used) or by any other simple implementation of String
-> Here is the code hope you will get what you want I m also giving information about how you can get app name,app icon,app version,app version code etc.
But at the time of the application Uninstall you can only get the package name as on Un installation all other information gets removed by the system.
Источник