Android find installed packages

davidnunez / gist:1404789

This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters. Learn more about bidirectional Unicode characters

pm list packages -f

This comment has been minimized.

Copy link Quote reply

full-of-foo commented Nov 15, 2013

This comment has been minimized.

Copy link Quote reply

full-of-foo commented Nov 15, 2013

Nice one liner: » adb shell ‘pm list packages -f’ »

This comment has been minimized.

Copy link Quote reply

banshee commented May 1, 2014

And for just the packages:

adb shell ‘pm list packages -f’ | sed -e ‘s/.*=//’ | sort

Need to delete a bunch of things? This gives you an uninstall for everything that’s installed; cut and paste to adjust:

adb shell ‘pm list packages -f’ | sed -e ‘s/.*=//’ | sed -e ‘s/^/adb uninstall /’ | sort | less

This comment has been minimized.

Copy link Quote reply

sunnychan2012 commented Jul 31, 2014

how to save it as a notepad text file?
I found the answer:
adb shell pm list packages -f > b:\1.txt

This comment has been minimized.

Copy link Quote reply

amr commented Sep 13, 2014

Building up on banshee’s one liner, for me there was a trailing \r, removing it was needed, as such:

adb shell ‘pm list packages -f’ | sed -e ‘s/.*=//’ | sed ‘s/\r//g’ | sort

Only then I was able to do get the following to work:

Источник

How to get a list of installed apps in Android 11

In Android 11, we can see a lot of updates that improve privacy. If your app uses the PackageManager methods to get the list of installed apps in the user’s device, you will have to make some changes in your code for devices using Android 11. In this blog post, we will be discussing all our options.

If you are already querying the user’s installed apps, the following code snippet will look familiar. This is how you can get a list of installed apps of the user.

Now for your users using Android 11, the code remains the same but it won’t work unless you add some additional elements in the AndroidManifest .

There are 3 different ways of querying installed apps of the user in Android 11. Let’s have a look at them:

Query specific packages

If you already know which apps you want to query just mention the package names inside the element in the AndroidManifest .

Query using intent filter

In case you don’t know all the package names of the apps that you want to query but there is a set of apps with similar functionality that you want to query then you can use an intent filter inside the element according to your requirements like it has been done in the code snippet below.

The element looks like but there are few differences. element has the following restrictions:

Читайте также:  Башенки алавар для андроид

Query all the apps

If you want to query all the apps of the user like you were doing earlier, you need to include QUERY_ALL_PACKAGES permission in the AndroidManifest . It is a normal permission and it is granted as soon as the app is installed.

Ideally one should request the least amount of packages and respect the user’s privacy. In most cases this permission won’t be required, only for apps like launchers it makes sense to ask the user for permission to query all the installed apps on their phone.

There is one loophole that I noticed while exploring the element if you add android.intent.action.MAIN as the action element in the intent filter, you can see almost all the apps of the user without adding the permission since almost all apps would have this element in the AndroidManifest .

Thanks for reading! If you enjoyed this story, please click the 👏 button and share it to help others!

If you have any kind of feedback, feel free to connect with me on Twitter .

Источник

Package visibility in Android 11

On Android 10 and earlier, apps could query the full list of installed apps on the system using methods like queryIntentActivities() . In most cases, this is far broader access than is necessary for an app to implement its functionality. With our ongoing focus on privacy, we’re introducing changes on how apps can query and interact with other installed apps on the same device on Android 11. In particular, we’re bringing better scoped access to the list of apps installed on a given device.

To provide better accountability for access to installed apps on a device, apps targeting Android 11 (API level 30) will see a filtered list of installed apps by default. In order to access a broader list of installed apps, an app can specify information about apps they need to query and interact with directly. This can be done by adding a element in the Android manifest.

For most common scenarios, including any implicit intents started with startActivity() , you won’t have to change anything! For other scenarios, like opening a specific third party application directly from your UI, developers will have to explicitly list the application package names or intent filter signatures like this:

If you use Custom Tabs to open URLs, you might be calling resolveActivity() and queryIntentActivities() in order to launch a non-browser app if one is available for the URL. In Android 11 there’s a better way to do this, which avoids the need to query other apps: the FLAG_ACTIVITY_REQUIRE_NON_BROWSER intent flag. When you call startActivity() with this flag, an ActivityNotFoundException will be thrown if a browser would have been launched. When this happens, you can open the URL in a Custom Tab instead.

In rare cases, your app might need to query or interact with all installed apps on a device, independent of the components they contain. To allow your app to see all other installed apps, Android 11 introduces the QUERY_ALL_PACKAGES permission. In an upcoming Google Play policy update, look for guidelines for apps that need the QUERY_ALL_PACKAGES permission.

When targeting API level 30 and adding a element to your app, use the latest available release of the Android Gradle plugin. Soon we’ll be releasing updates to older Android Gradle plugin versions to add support for this element. You can find more information and use cases about Package Visibility in the developer documentation.

Источник

Получение списка приложений в Android

Android SDK предоставляет много средств для работы с системой. В том числе он позволяет получать список приложений, которые установлены на устройстве. Это может быть полезно, когда нужно получить сведения о сторонних приложениях (размер APK, путь до приложения, имя пакета и т.д.). Например, в наших приложениях получение списка, содержащего сторонние приложения, играет большую роль: в GreenBro с помощью этого списка выводятся сведения о приложениях, а также выполняются различные действия.

Читайте также:  Операционная система android для навигаторов

В Менеджере системных приложений и APK Extractor же список приложений необходим, чтобы удалять приложения и извлекать APK из приложений соответственно.

В этой статье мы рассмотрим, как можно получать список приложений, установленных на устройстве, а также как происходит установка приложений на устройство.

Класс PackageManager

PackageManager предоставляет API, который фактически управляет установкой, удалением и обновлением приложений. Когда мы устанавливаем файл APK, PackageManager анализирует этот APK и выводит результат.

Получить экземпляр класса PackageManager можно с помощью метода getPackageManager(). PackageManager предоставляет методы для запросов к установленным пакетам и соответствующим разрешениям.

Где хранятся файлы APK на Android?

В зависимости от типа данных, на Androiid файлы могут храниться в следующих местах:

  • Предустановленные и системные приложения (Камера, Браузер и т.д.) хранятся в /system/app/
  • Установленные пользователем приложения хранятся в /data/app/
  • PackageManager создаёт каталог /data/data/ / для хранения базы данных, файлов с предпочтениями, нативных библиотек и кеша.

Как PackageManager хранит информацию о приложении?

Менеджер пакетов хранит информацию о приложении в трёх файлах, расположенных в /data/system.

packages.xml

Этот XML-файл содержит список разрешений и пакеты\приложения. Он хранит две вещи: разрешения и пакет. Например:

Разрешения хранятся в теге

. Каждое разрешение имеет три атрибута: name, package и protection. Атрибут name это имя разрешения, которое мы используем в AndroidManifest.xml. Атрибут package указывает на пакет, которому принадлежит разрешение, в большинстве случаев это «android». Атрибут protection указывает на уровень безопасности.

содержит 10 атрибутов и несколько подтегов.

Атрибут Описание
name Имя пакета
codePath Путь установки APK
nativeLibraryPath Нативная библиотека, расположенная по умолчанию в /data/data/ /lib
flag Хранит флаги ApplicationInfo
ft Время в шестнадцатtричном формате
lt Время установки в шестнадцатеричном формате
ut Время последнего обновления в шестнадцатеричном формате
version Код версии из AndroidManifest.xml
sharedUserId Идентификатор пользователя Linux, который будет использоваться совместно с другими приложениями.
userId Идентификатор пользователя Linux

Подтеги же здесь следующие:

  • представляет собой информацию о сигнатуре, атрибут count — количество тегов .
  • это ключ сертификата, атрибут index представляет собой глобальный индекс сертификата.

содержат разрешения, которые разработчик установил в AndroidManifest.xml

packages.list

Это простой текстовый файл, содержащий имя пакета, идентификатор пользователя, флаги и каталог data.

package-stopped.xml

Этот файл содержит список пакетов, которые были остановлены. Остановленные приложения не могут принимать широковещательные сообщения.

Получаем список приложений

Рассмотрим получение списка установленных приложений на примере GreenBro.

При запуске приложения запускается AsyncTask, внутри которого получаем экземпляр PackageManager и затем копируем в список List все данные об установленных приложениях.

Метод getInstalledApplications() принимает в качестве параметра флаг GET_META_DATA, который определяет, что нам нужные метаданные каждого пакета.

Результатом является список объектов ApplicationInfo для каждого установленного приложения. Класс ApplicationInfo предоставляет подробную информацию о пакете, собранную из тега в AndroidManifest.xml, нам оттуда нужны лишь самые важные данные.

Поэтому в цикле проверяем каждый объект из полученного списка и записывать данные в собственный класс AppInfo, чтобы затем использовать в основном потоке.

Здесь с помощью метода getPackageInfo() класса PackageManager мы получаем общую информацию о приложении по заданному имени пакета. После эта информация объединяется с информацией, полученной от getInstalledApplications() и сохраняется в объекте AppInfo со следующими полями:

  • title — название приложения
  • packageName — имя пакета
  • sourceDir — полный путь до APK приложения
  • publicSourceDir — путь до общедоступных частей sourceDir
  • versionName — имя версии
  • isSystem — определяет, является ли приложение системным
  • size — размер приложения (в удобной форме)
  • longSize — размер приложения в long
  • dataDir — полный путь к каталогу data
  • nativeLibraryDir — путь до нативных библиотек
  • modified — дата последнего изменения
  • firstInstallTime — дата установки
  • lastUpdateTime — дата последнего обновления
  • enabled — определяет, включено ли приложение

Чтобы узнать название приложения, можно также воспользоваться PackageManager, как показано ниже.

Проверка же на то, является ли приложение системным, тоже достаточно проста и показана ниже.

В конце работы AsyncTask возвращает результат обратно в основной поток. Вот и всё, мы загрузили себе список всех установленных на устройстве приложений и можем продолжить с ним работу.

Получение списка приложений в Android : 4 комментария

Подскажите пожалуйста, в конструкции:
final PackageManager pm = context.getPackageManager();
List apps = new ArrayList();
List packages = pm.getInstalledApplications(PackageManager.GET_META_DATA);
Чем является «context»?

Это локальная переменная, Вы можете передавать контекст из активити или фрагмента

» List packages = pm.getInstalledApplications( »

а есть ли функция наподобие getRunnedApplications(), которая выдает список запущенных последних приложений?

как отличить приложение от сервиса? Проверка на системное приложение не помогает

Источник

Find package name or application ID of an Android app

Android apps use package name as their unique identification. In some references, it may also be called Application ID. Although there are some differences between the two, for most of us non-developers, it is the same. It usually consists of 3 parts, but it can have 2 parts as well. For example, the package ID of Mozilla’s Firefox Browser for Android is org.mozilla.firefox.

As mentioned, the package name is unique to an application. Play Store and Android smartphones identify apps using the package name. Two different apps can have the same name, however, their package name or application ID will always be different. If you have a need of the package name of a particular app, then follow any of the methods listed below.

Finding the Package Name of Android Apps

There are several ways to find out the package name of an Android app. I am listing down the various methods. You can follow any of them as per your convenience.

Method 1 – From the Play Store

As I mentioned, the Play Store also uses the Android app package name to list unique apps. So, the easiest way to find the app package name is via the Play Store.

On a PC/Mac:

  1. Open play.google.com in your web browser.
  2. Use the search bar to look for the app for which you need the package name.
  3. Open the app page and look at the URL. The package name forms the end part of the URL i.e. after the id=?. Copy it and use it as needed.
    Note: Ignore any other information in the URL. It is not a part of the package name.

Do note that it is only applicable to apps which are listed on Play Store. For 3rd party apps, follow one of the alternative methods as listed below.

On Android mobile device

Most Android mobile browsers will redirect you to the Play Store app when you access the website. So, how do you find the package name from Play Store Android app? Here are the steps you can follow:

  1. Scroll down to the end of the page till you see the (share) button.
  2. Use it and share the Play Store app link to any service from where you can select and copy text. I usually use messaging without sending it to any recipient.
  3. The app package name will at the end of the app link which you just shared. Copy it off and use it as needed.

Method 2 – Use an app on your phone

Trying to find the package name of an app installed on your device? Or the app is installed from a 3rd party source, then you can rely on the Package Viewer apps available on Play Store. We are using a well-known app called Package name viewer 2.0 for this tutorial.

  1. Install Package Name Viewer 2.0 from the Play Store.
  2. Scroll through the app list to find the app for which you need the package name. You can also use the search button to quickly look for a particular application or game.
  3. The package name is listed just under the name of app. Just tap on the app name to get more options like copy.

Источник

Читайте также:  Aimp настройка эквалайзера андроид
Оцените статью