- Полный список
- How to change default apps in Android
- How to manage default apps
- Manage defaults as you go
- Nuclear option: Reset all default apps
- In Depth: Android Package Manager and Package Installer
- Learn more about Android Package Manager and Installer, including where APK files are stored in Android, where the manager stores data, and more.
- What are Package Manager and Package Installer?
- Where are APK Files Stored in Android?
- What is the APK Installation Process in Detail?
- How Does the Package Manager Store Data?
Полный список
— разбираемся, что такое Package для приложения
Package можно перевести как пакет. Этот вариант перевода я и буду использовать в уроке.
Пакет приложения мы прописываем в визарде создания приложения.
Потом его можно найти в манифесте.
Он же по дефолту становится пакетом для Java-классов
Как-то не особо значимая цель .
Может быть он используется как-то еще? Оказывается да. Более того, пакет — это крайне важная вещь при создании приложения. Пакет является идентификатором приложения в системе. Т.е. когда вы устанавливаете приложение, система смотрит его пакет и ищет уже установленное приложение с таким пакетом. Если не нашлось, то все ок и приложение устанавливается.
А вот если нашлось, то тут в дело вступает механизм подписи приложения ключом, который мы рассмотрели на прошлом уроке. Система проверяет, если установленное и устанавливаемое приложения подписаны одним и тем же ключом, то, вероятнее всего, это означает, что оба приложения создал один автор. И устанавливаемое приложение является обновлением установленного, т.к. их пакеты и ключи одинаковы. Система устанавливает новое приложение, заменяя старое — т.е. обновляет старое.
Если же система определила, что приложения были подписаны разными ключами, то это значит, что приложения были созданы разными авторами, пакеты совпали случайно, и новое вовсе не является обновлением старого. В этом случае при установке нового, старое было бы заменено, а значит потеряно (а не обновлено), т.к. приложения абсолютно разные. И система не дает поставить новое приложение, пока не будет вручную удалено старое.
Проведем пару тестов. Я создам два приложения Package1 и Package2 с одинаковым пакетом.
Установлю первое. Оно появилось в списке.
Теперь не удаляя первое, установлю второе.
Первое исчезло. Осталось только второе.
Система решила, что второе является обновлением первого (т.к. пакеты и ключи совпадают), поэтому первое благополучно снесла и заменила вторым. Собственно, это и происходит при обычном обновлении.
Теперь подпишу Package2 другим ключом, чем оно было подписано изначально и попробую обновить через adb.
Параметр r здесь означает, что приложение надо переустановить, если оно уже существует.
Видим ошибку Failure [INSTALL_PARSE_FAILED_INCONSISTENT_CERTIFICATES]. Система сверила ключи у установленного и устанавливаемого приложений, увидела, что они разные и решила, что это будет не обновление, а просто приложение от другого разработчика ломится с тем же пакетом. И вполне разумно решила не удалять имеющееся приложение, а предупредить пользователя, что не совпадают ключи.
Если закинуть это приложение на эмулятор и поставить через файловый менеджер, получим примерно то же сообщение.
Из вышесказанного можно сделать следующий вывод: ваш ключ, которым вы подписываете приложение ни в коем случае нельзя терять или давать кому-либо.
Если вы ключ потеряете, то ваше приложение навсегда потеряет возможность быть обновленным. Даже если вы создадите новый ключ с тем же алиасом, паролем и данными владельца, это все равно будет другой ключ. И подписанная им следующая версия приложения будет рассматриваться системой не как обновление, а как попытка приложения от другого разработчика заменить ваше приложение и не даст его установить, пока не удалите установленное.
Если же вы ключ кому-то предоставите, то этот человек сможет сделать обновление для вашего приложения без вашего участия. И если этот человек имеет доступ и к вашей учетке разработчика в маркете, то он сможет залить туда свою версию вашего приложения.
Также не забывайте пароли от хранилища и от ключа. Это будет равносильно тому, что вы потеряли ключ. В общем, относитесь к вашим ключам со всей серьезностью.
И в конце урока небольшой ликбез. Пакет имеет еще одно значение. Как вы уже наверно заметили по вкладке Devices в Eclipse, пакет используется в качестве имени процесса, в котором запускается приложение. При этом, под каждое приложение система создает пользователя. Это позволяет разграничить доступ к данным. Каждое приложение запускается и работает со своими данными в отдельном процессе под отдельным пользователем. Соответственно, другие приложения не имеют к этим данным доступа, т.к. запущены под другими пользователями.
На следующем уроке:
— разбираемся с ViewPager
Присоединяйтесь к нам в Telegram:
— в канале StartAndroid публикуются ссылки на новые статьи с сайта startandroid.ru и интересные материалы с хабра, medium.com и т.п.
— в чатах решаем возникающие вопросы и проблемы по различным темам: Android, Kotlin, RxJava, Dagger, Тестирование
— ну и если просто хочется поговорить с коллегами по разработке, то есть чат Флудильня
— новый чат Performance для обсуждения проблем производительности и для ваших пожеланий по содержанию курса по этой теме
Источник
How to change default apps in Android
It’s a problem you might run into regularly. You tap a file that you really want to open with a particular app, but for some reason, Android keeps opening it with some application you couldn’t care less about. That’s because you’ve got the wrong app selected for that type of file. You’re in the right place, however. In this brief guide, we’ll walk you through the process of changing default apps on Android.
Editor’s note: These instructions were put together using a Pixel 4a running stock Android 11. It’s a great device to base any guide on but some steps might be different, depending on the device and software you use.
How to manage default apps
The process used to be much more complicated, but Google has turned managing default apps into an effortless task. It’s baked right into the settings. Just go into your Settings app, select Apps & notifications, click on Advanced, and then go into Default apps.
From there, you can pick your default browser, call redirecting, caller ID, digital assistant, home launcher, phone, and SMS default applications. You can also go into Opening links to edit individual apps on your phone.
Step-by-step instructions to manage default apps:
- Open the Settings app on your Android phone.
- Go into Apps & notifications.
- Hit Advanced.
- Select Default apps.
- Pick the apps you want for each option.
Manage defaults as you go
The Android operating system uses a pretty slick concept called “implicit intent.” Basically, if the user or an app calls for the device to do something like “take a picture,” the operating system will look for an app that can get the job done. If more than one option exists, and no default has been selected (or if a new possibility has been installed since the last time a default was set), then Android will ask the user which app they would prefer to use. This makes the process of setting default apps easy and intuitive.
Next time you open any link or action, and Android gives you options for which app to use, select your preferred default app. You can now select Just once or Always. Select Always if you want to make that app the default one. The operating will remember your preference from then on.
The only issue with doing this is that sometimes people accidentally set a default app they didn’t intend to. You can follow the steps in the previous section to change your preference. Once you get to the Default apps section, go into Opening links. Find the app you want to change your preferences for and go into it. You’ll get all the options you need there.
Step-by-step instructions to manage defaults as you go:
- Open a link to a website or action you want to set a default app for. I’m using BestBuy as an example.
- Android will ask you which app you want to use.
- You can pick to use this app Just Once or Always.
- Pick Always to set it as the preferred method.
Nuclear option: Reset all default apps
If you can’t quite figure out which app default is giving you fits and the option to choose a new default isn’t appearing no matter what you do, there’s still hope!
However, bear in mind that going through with this procedure will also enable all disabled apps, reset any app notification options, remove any background data restrictions or permission restrictions placed on specific apps. You won’t lose any data, but if you play around with your apps’ settings a lot, you might have to do a fair amount of reconfiguring to get things back to how you like them.
If you’re ready for an app settings reset, go into your Settings app. Select Apps & notifications, and tap on See all apps. Hit the three-dot menu button in the top-right corner. Tap on Reset app preferences. Confirm by tapping on Reset apps.
Step-by-step instructions to reset default apps:
- Open the Settings app on your Android phone.
- Go into Apps & notifications.
- Tap on the See all apps option.
- Hit the three-dot menu button.
- Tap on Reset app preferences.
- Confirm by selecting Reset apps.
Источник
In Depth: Android Package Manager and Package Installer
Learn more about Android Package Manager and Installer, including where APK files are stored in Android, where the manager stores data, and more.
Join the DZone community and get the full member experience.
We are installing and uninstalling APK(s) every day, sometimes many in a day, but have you tried to get answers to the following questions ?
- What are Package Manager and Package Installer ?
- Where are APK files stored in Android ?
- What is the APK installation process in detail ?
- How does Package Manager store data ?
- Where I can find the source code of Package Manager and Package Installer ?
What are Package Manager and Package Installer?
PackageInstaller is the default application for Android to interactively install a normal package. PackageInstaller provide user interface to manage applications/packages. PackageInstaller calls InstallAppProgress activity to receive instructions from the user. InstallAppProgress will ask Package Manager Service to install package via installd. Source code is available at /packages/apps/PackageInstaller.
Installd daemon’s primary role is to receive request from Package Manager Service via Linux domain socket / dev/ socket/ installed. installd executes a series of steps to install APK with root permission.
Package Manage is an API that actually manages application install, uninstall, and upgrade. When we install the APK file, Package Manager parse the package (APK) file and displays confirmation. When the user presses the OK button, Package Manager calls the method named «installPackage» with these four parameters namely uri, installFlags, observer, installPackageName. Package Manager starts one service named «package», and now all fuzzy things happen in this service. You can check «PackageInstallerActivity.java» and «InstallAppProgress.java» in the PackageInstaller source code. Package Manager Service runs in system_service process and install daemon (installd) runs as a native process. Both start at system boot time.
Where are APK Files Stored in Android?
a. Pre-Install (i.e. Camera, Calendar, Browser,etc.) APK is stored in /system/app/
b. User Install (ApiDemo, Any.do, etc.) APK is stored in /data/app/
c. Package Manager creates a data directory /data/data/
/ to store the database, shared preference, native library and cache data.
You might see an apk file and *.odex file for the same APK. The ODEX file is totally a different discussion and purpose.
What is the APK Installation Process in Detail?
The following process executes in Package Manager Service.
- Waiting
- Add a package to the queue for the installation process
- Determine the appropriate location of the package installation
- Determine installation Install / Update new
- Copy the apk file to a given directory
- Determine the UID of the app
- Request the installd daemon process
- Create the application directory and set permissions
- Extraction of dex code to the cache directory
- To reflect and packages.list / system / data / packages.xml the latest status
- Broadcast to the system along with the name of the effect of the installation is complete package
- Intent.ACTION_PACKAGE_ADDED: If the new ( Intent.ACTION_PACKAGE_REPLACED): the case of an update
How Does the Package Manager Store Data?
Package Manager stores application information in three files, located in /data/system. The following sample is extracted from Android 4 ICS emulator image.
1. packages.xml :This file contain list of permissions and Packages/Applications.
This XML file stores two things 1. permissions 2. package (application), permission are store under
tag. Each Permission has three attributes namely name, package and protection. The name attribute has permission name, which we are using in AndroidManifest.xml, the package attribute indicates permission belonging to package. In most cases «android» is the value, because the
tag contains default permissions and protection indicates level of security.
The package tag contain 10 attributes and a few sub tags.
Sr | Attribute Name | Description |
1 | name | package name |
2 | codePath | APK file installation location (/system/app/ or /data/app/) |
3 | nativeLibraryPath | native library (*.so file) default path is /data/data/ /lib/ |
4 | flag | Store ApplicationInfo Flags [http://developer.android.com/reference/android/content/pm/ApplicationInfo.html] |
5 | ft | timestamp in hex format |
6 | lt | timestamp in hex format of first time installation |
7 | ut | timestamp in hex format of last update |
8 | version | Version Code from AndroidManifest.xml file []http://developer.android.com/guide/topics/manifest/manifest-element.html#vcode] |
9 | sharedUserId | The name of Linux user ID that will be shared with other applications, It is same parameter which we define in AndroidManifest.xml [http://developer.android.com/guide/topics/manifest/manifest-element.html#uid] |
10 | userId | The name of a Linux user ID |
Sub Tags
a. sigs signature information, count attribute represents the number of cert tag.
b. cert contain certification key, index attribute represents the global index of certificate. I have found that it increments when new certificates are installed with the application.
Источник