Notification listener service android

Отслеживание уведомлений на Android 4.0-4.2

Начиная с версии 4.3 в Android OS была добавлена возможность отслеживать все уведомления в системе используя NotificationListenerService. К сожалению, обратная совместимость с предыдущими версиями OS отсутствует. Что делать, если подобный функционал необходим на устройствах с более старой версией операционной системы?

В статье можно найти набор костылей и хаков для отслеживания уведомлений на Android OS версии 4.0-4.2. Не на всех устройствах результат 100% работоспособен, поэтому приходится использовать дополнительные костыли, чтобы предположить удаление уведомлений в определенных случаях.

Поиск информации в интернете по этому вопросу приводит к выводу, что необходимо использовать AccessibilityService и отслеживать событие TYPE_NOTIFICATION_STATE_CHANGED. Тестирование показало, что данное событие происходит лишь в тот момент, когда уведомление добавляется в статусную строку, но не происходит, когда уведомление удаляется. Чтение дополнительных данных о пришедшем уведомлении и отслеживание удаления и является наибольшими костылями в решении этой задачи.

Отслеживание входящих уведомлений с извлечение дополнительной информации

Итак, уведомление пришло, получено событие TYPE_NOTIFICATION_STATE_CHANGED. Мы можем узнать package name приложения, которое послало уведомление используя метод AccessibilityEvent.getPackageName(). Само уведомление можно извлечь используя метод AccessibilityRecord.getParcelableData(), на выходе получим объект типа Notification. Но, к сожалению, набор доступных данных в извлеченном уведомлении весьма скуден. Для дальнейшего отслеживания удаления уведомления нам потребуется достать хотя бы текстовый заголовок. Для этого придется использовать reflection и другие костыли.

В вышеприведенном коде извлекаются все строковые значения и View Ids, относящиеся к объекту типа Notification. Для этого используются Reflection и чтение из Parcelable объектов. Но мы не знаем, какое View Id имеет заголовок уведомления. Для того, чтобы определить это используется следующий код:

Логика вышеприведенного кода в том, что создается тестовое уведомление с уникальным текстовым значением для заголовка. Создается View для данного уведомления при помощи LayoutInflater и рекурсивным поиском ищется дочерний TextView с ранее заданным текстом. Id найденного объекта и будет уникальным идентификатором заголовка всех входящих уведомлений.

После того, как заголовок был извлечен, сохраняем пару package, title в нашем списке активных уведомлений для дальнейших проверок.

С первой частью, вроде как, справились. Такой подход работает более менее стабильно на различных версия Android. Перейдем ко второй части, в которой мы будем пытаться отследить удаление уведомлений.

Отслеживание удаления уведомлений

По скольку стандартным способом узнать, когда уведомление было удалено не представляется возможным, необходимо ответить на вопрос: в каких случаях оно может быть удалено? На ум приходят следующие варианты:

  1. Пользователь смахнул уведомление
  2. Пользователь открыл приложение по клику на уведомлении и оно исчезло.
  3. Пользователь нажал кнопку очистить все уведомления.
  4. Приложение само удалило уведомление.

Сразу вынужден признать, что с последним пунктом ничего сделать пока не смог, но есть надежда, что такое поведение не слишком частое, и поэтому не слишком востребованное.

Рассмотрим каждый сценарий в отдельности.

Пользователь смахнул уведомление

Отследив, какие события происходят, когда пользователь смахивает уведомления, обнаружил, что генерируется событие типа TYPE_WINDOW_CONTENT_CHANGED для package name «android.system.ui» с windowId принадлежащему статусной строке. К сожалению, окно переключения между приложениями тоже имеет package name «android.system.ui» но другой windowId. WindowId это не константа, и может меняться после перезапуска устройства или на разных версиях Android.

Как же вычислить, что событие пришло именно из статусной строки? Мне пришлось изрядно поломать голову над этим вопросом. В конце концов, пришлось реализовать определенный костыль для этого. Предположил, что статусная строка должна быть развернута в момент удаления уведомления пользователем. На ней должна присутствовать кнопка очистить все уведомления с определенным accessibility description. К счастью, константа имеет одно и то же название на разных версиях Android. Теперь необходимо проанализировать иерархию вида на предмет присутствия данной кнопки, и тогда мы сможем обнаружить windowId принадлежащий статусной строке. Возможно, кто-нибудь из хабражителей знает более достоверный способ сделать это, буду благодарен, если поделитесь знаниями.

Определяем, принадлежит ли событие статусной строке:

Теперь необходимо определить, было ли удалено уведомление или все еще присутствует. Используем способ, который не обладает 100% надежностью: извлекаем все строки из статусной строки и ищем совпадения с ранее сохраненными заголовками уведомлений. Если заголовок отсутствует, считаем, что уведомление было удалено. Бывает, что приходит событие с нужным windowId но с пустым AccessibilityNodeInfo (случается, когда пользователь смахивает последнее доступное уведомление). В таком случае считаем, что все уведомления были удалены.

Пользователь открыл приложение по клику на уведомлении и оно исчезло

Было бы идеально, если бы данное поведение генерировало, как и в первом случае, событие TYPE_WINDOW_CONTENT_CHANGED для package name «android.system.ui», не пришлось бы рассматривать этот случай отдельно. Но тесты показали, что нужное событие генерируется, но не всегда: это зависит от версии Android, скорости закрытия статусной строки и еще непонятно от чего. В своем приложении мне необходимо было перестать уведомлять пользователя о пропущенном уведомлении. Было решено подстраховаться и считать, что раз пользователь открыл приложение, у которого имеются пропущенные уведомления, можно считать, что ранее сохраненные уведомления для него не важны и могут о себе не напоминать.

Когда приложение открывается, генерируется событие TYPE_WINDOW_STATE_CHANGED, откуда можно узнать packageName и удалить все отслеживаемые уведомления для него.

Пользователь нажал кнопку очистить все уведомления

Тут, как и в предыдущем случае, событие TYPE_WINDOW_CONTENT_CHANGED генерируется не всегда. Пришлось предположить, что раз пользователь нажал на кнопку, то ранее полученные уведомления больше не важны и перестать о них уведомлять.

Необходимо отследить событие TYPE_VIEW_CLICKED в статусной строке и если оно принадлежит кнопке «Очистить все», перестать отслеживать все уведомления.

Что с Android до версии 4.0?

К сожалению, мне пока не удалось найти рабочий способ отследить удаление уведомлений. Возможность работать с ViewHierarchy в AccessibilityService была добавлена только начиная с API версии 14. Если кто-нибудь знает способ, как получить доступ к ViewHierarchy статусной строки напрямую, возможно, эту задачу удастся решить

Надеюсь, кому-нибудь интересна рассмотренная в статье тема. Буду рад услышать ваши идеи по поводу того, как улучшить результат отслеживания удаления уведомлений.

Источник

Пример Android NotificationListenerService

Вступление

NotificationListenerService представлен в Android 4.3 (API 18). Это позволяет приложению получать информацию об уведомлениях при создании или удалении. Класс NotificationListenerService является производным от класса Service . У него есть два абстрактных метода, а именно: 1. onNotificationPosted 2. onNotificationRemoved.

Чтобы использовать NotificationListenerService, нам нужно создать Java-файл, который расширяет NotificationListenerService и реализовать два метода обратного вызова. Оба метода имеют параметр с именем «sbn», который является объектом класса StatusBarNotification . StatusBarNotification предоставляет необходимую информацию об уведомлениях.

NotificationListenerService предоставляет возможность извлечения активных уведомлений с помощью getActiveNotifications, а также предоставляет возможность удалять уведомления с помощью cancelAllNotifications.

Полезные методы

  1. NotificationListenerService
    onNotificationPosted()
    onNotificationRemoved()
    cancelAllNotifications()
    getActiveNotifications()
  2. StatusBarNotification
    getId()
    getNotification()
    getPackageName()
    getPostTime()
    isClearable()
    isOngoing()

Примечание. Пользователю необходимо активировать разрешение на получение уведомлений в «Настройки> Безопасность> Доступ к уведомлению».

Исходный код NotificationListenerService

пример

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

  • Создать уведомление — это создаст простое уведомление, чтобы мы могли протестировать событие onNotificationPosted
  • Очистить все уведомления — это создаст все уведомления в панели уведомлений
  • Список уведомлений — будет отображать список уведомлений в текстовом представлении
  • TextView — отображать события уведомлений и список уведомлений.

Этот пример имеет Activity, Service и BroadcastReceiver. BroadcastReceiver используется для связи между активностью и сервисом. Мы не можем получить доступ к методам cancelAllNotifications () и getActiveNotifications () непосредственно из активности, поэтому я использую BroadcastReceivers.

Источник

Android NotificationListenerService Example

Posted by: Ketan Parmar in Android Core October 15th, 2013 7 Comments Views

Introduction

NotificationListenerService is introduced in Android 4.3 (API 18). It allows an application to receive information about notifications as it creates or removes. NotificationListenerService class is derived from the Service class. It has two abstract methods namely 1. onNotificationPosted 2. onNotificationRemoved.

To use NotificationListenerService, we need to create a java file which extends NotificationListenerService and implement two callback methods. Both methods have a parameter named “sbn”, which is an object of StatusBarNotification class. StatusBarNotification provides necessary information about Notifications.

NotificationListenerService provides facility to fetch active notifications using getActiveNotifications and also provides a feature to remove notifications using cancelAllNotifications.

Useful Methods

  1. NotificationListenerService
    onNotificationPosted()
    onNotificationRemoved()
    cancelAllNotifications()
    getActiveNotifications()
  2. StatusBarNotification
    getId()
    getNotification()
    getPackageName()
    getPostTime()
    isClearable()
    isOngoing()

Note: User require to enable notification permission from “Settings > Security > Notification access”.

Source Code of NotificationListenerService

Example

This is simple example of NotificationListenerService, It has simple UI contain three buttons and one textview.

  • Create Notification – It will create simple notification so that we can test onNotificationPosted event
  • Clear All Notification – It will create all notification in notificationbar
  • List of Notification – It will display notification list in textview
  • TextView – display notification events and list of notification.

This example has Activity, Service and BroadcastReceiver. BroadcastReceiver used for communication between activity and service. We can’t access cancelAllNotifications() and getActiveNotifications() methods from activity directly so I use BroadcastReceivers.

Источник

Notification Listener Service Class

Definition

Some information relates to prerelease product that may be substantially modified before it’s released. Microsoft makes no warranties, express or implied, with respect to the information provided here.

A service that receives calls from the system when new notifications are posted or removed, or their ranking changed.

Remarks

Portions of this page are modifications based on work created andВ shared by the Android Open Source Project and used according to terms described in the Creative Commons 2.5 Attribution License.

Constructors

A constructor used when creating managed representations of JNI objects; called by the runtime.

Fields

Use with #getSystemService(String) to retrieve a android.view.accessibility.AccessibilityManager for giving the user feedback for UI events through the registered event listeners.

(Inherited from Context) AccountService

Use with #getSystemService(String) to retrieve a android.accounts.AccountManager for receiving intents at a time of your choosing.

(Inherited from Context) ActivityService

Use with #getSystemService(String) to retrieve a android.app.ActivityManager for interacting with the global system state.

(Inherited from Context) AlarmService

Use with #getSystemService(String) to retrieve a android.app.AlarmManager for receiving intents at a time of your choosing.

(Inherited from Context) AppOpsService

Use with #getSystemService(String) to retrieve a android.app.AppOpsManager for tracking application operations on the device.

(Inherited from Context) AppSearchService

Use with #getSystemService(String) to retrieve an android.app.appsearch.AppSearchManager for indexing and querying app data managed by the system.

Читайте также:  Лучшая графика для андроида

(Inherited from Context) AppwidgetService

Use with #getSystemService(String) to retrieve a android.appwidget.AppWidgetManager for accessing AppWidgets.

(Inherited from Context) AudioService

Use with #getSystemService(String) to retrieve a android.media.AudioManager for handling management of volume, ringer modes and audio routing.

(Inherited from Context) BatteryService

Use with #getSystemService(String) to retrieve a android.os.BatteryManager for managing battery state.

(Inherited from Context) BindNotPerceptible

Flag for #bindService : If binding from an app that is visible or user-perceptible, lower the target service’s importance to below the perceptible level.

(Inherited from Context) BiometricService

Use with #getSystemService(String) to retrieve a android.hardware.biometrics.BiometricManager for handling biometric and PIN/pattern/password authentication.

(Inherited from Context) BlobStoreService

Use with #getSystemService(String) to retrieve a android.app.blob.BlobStoreManager for contributing and accessing data blobs from the blob store maintained by the system.

(Inherited from Context) BluetoothService

Use with #getSystemService(String) to retrieve a android.bluetooth.BluetoothManager for using Bluetooth.

(Inherited from Context) BugreportService

Service to capture a bugreport.

(Inherited from Context) CameraService

Use with #getSystemService(String) to retrieve a android.hardware.camera2.CameraManager for interacting with camera devices.

(Inherited from Context) CaptioningService

Use with #getSystemService(String) to retrieve a android.view.accessibility.CaptioningManager for obtaining captioning properties and listening for changes in captioning preferences.

(Inherited from Context) CarrierConfigService

Use with #getSystemService(String) to retrieve a android.telephony.CarrierConfigManager for reading carrier configuration values.

(Inherited from Context) ClipboardService

Use with #getSystemService(String) to retrieve a android.content.ClipboardManager for accessing and modifying the contents of the global clipboard.

(Inherited from Context) CompanionDeviceService

Use with #getSystemService(String) to retrieve a android.companion.CompanionDeviceManager for managing companion devices

(Inherited from Context) ConnectivityDiagnosticsService

Use with #getSystemService(String) to retrieve a android.net.ConnectivityDiagnosticsManager for performing network connectivity diagnostics as well as receiving network connectivity information from the system.

(Inherited from Context) ConnectivityService

Use with #getSystemService(String) to retrieve a android.net.ConnectivityManager for handling management of network connections.

(Inherited from Context) ConsumerIrService

Use with #getSystemService(String) to retrieve a android.hardware.ConsumerIrManager for transmitting infrared signals from the device.

(Inherited from Context) CrossProfileAppsService

Use with #getSystemService(String) to retrieve a android.content.pm.CrossProfileApps for cross profile operations.

(Inherited from Context) DevicePolicyService

Use with #getSystemService(String) to retrieve a android.app.admin.DevicePolicyManager for working with global device policy management.

(Inherited from Context) DisplayHashService

Use with #getSystemService(String) to access android.view.displayhash.DisplayHashManager to handle display hashes.

(Inherited from Context) DisplayService

Use with #getSystemService(String) to retrieve a android.hardware.display.DisplayManager for interacting with display devices.

(Inherited from Context) DomainVerificationService

Use with #getSystemService(String) to access android.content.pm.verify.domain.DomainVerificationManager to retrieve approval and user state for declared web domains.

(Inherited from Context) DownloadService

Use with #getSystemService(String) to retrieve a android.app.DownloadManager for requesting HTTP downloads.

(Inherited from Context) DropboxService

Use with #getSystemService(String) to retrieve a android.os.DropBoxManager instance for recording diagnostic logs.

(Inherited from Context) EuiccService

Use with #getSystemService(String) to retrieve a android.telephony.euicc.EuiccManager to manage the device eUICC (embedded SIM).

(Inherited from Context) FileIntegrityService

Use with #getSystemService(String) to retrieve an android.security.FileIntegrityManager .

(Inherited from Context) FingerprintService

Use with #getSystemService(String) to retrieve a android.hardware.fingerprint.FingerprintManager for handling management of fingerprints.

(Inherited from Context) FlagFilterTypeAlerting

A flag value indicating that this notification listener can see altering type notifications.

A flag value indicating that this notification listener can see conversation type notifications.

A flag value indicating that this notification listener can see important ( > NotificationManager#IMPORTANCE_MIN ) ongoing type notifications.

A flag value indicating that this notification listener can see silent type notifications.

Use with #getSystemService(String) to retrieve a GameManager .

(Inherited from Context) HardwarePropertiesService

Use with #getSystemService(String) to retrieve a android.os.HardwarePropertiesManager for accessing the hardware properties service.

(Inherited from Context) InputMethodService

Use with #getSystemService(String) to retrieve a android.view.inputmethod.InputMethodManager for accessing input methods.

(Inherited from Context) InputService

Use with #getSystemService(String) to retrieve a android.hardware.input.InputManager for interacting with input devices.

(Inherited from Context) IpsecService

Use with #getSystemService(String) to retrieve a android.net.IpSecManager for encrypting Sockets or Networks with IPSec.

(Inherited from Context) JobSchedulerService

Use with #getSystemService(String) to retrieve a android.app.job.JobScheduler instance for managing occasional background tasks.

(Inherited from Context) KeyguardService

Use with #getSystemService(String) to retrieve a android.app.KeyguardManager for controlling keyguard.

(Inherited from Context) LauncherAppsService

Use with #getSystemService(String) to retrieve a android.content.pm.LauncherApps for querying and monitoring launchable apps across profiles of a user.

(Inherited from Context) LayoutInflaterService

Use with #getSystemService(String) to retrieve a android.view.LayoutInflater for inflating layout resources in this context.

(Inherited from Context) LocationService

Use with #getSystemService(String) to retrieve a android.location.LocationManager for controlling location updates.

(Inherited from Context) MediaCommunicationService

Use with #getSystemService(String) to retrieve a android.media.MediaCommunicationManager for managing android.media.MediaSession2 .

(Inherited from Context) MediaMetricsService

Use with #getSystemService(String) to retrieve a android.media.metrics.MediaMetricsManager for interacting with media metrics on the device.

(Inherited from Context) MediaProjectionService

Use with #getSystemService(String) to retrieve a android.media.projection.MediaProjectionManager instance for managing media projection sessions.

(Inherited from Context) MediaRouterService

Use with #getSystemService to retrieve a android.media.MediaRouter for controlling and managing routing of media.

(Inherited from Context) MediaSessionService

Use with #getSystemService(String) to retrieve a android.media.session.MediaSessionManager for managing media Sessions.

(Inherited from Context) MetaDataDefaultFilterTypes

The name of the meta-data tag containing a comma separated list of default integer notification types that should be provided to this listener.

The name of the meta-data tag containing a comma separated list of default integer notification types that this listener never wants to receive.

Use with #getSystemService(String) to retrieve a android.media.midi.MidiManager for accessing the MIDI service.

(Inherited from Context) NetworkStatsService

Use with #getSystemService(String) to retrieve a android.app.usage.NetworkStatsManager for querying network usage stats.

(Inherited from Context) NfcService

Use with #getSystemService(String) to retrieve a android.nfc.NfcManager for using NFC.

(Inherited from Context) NotificationService

Use with #getSystemService(String) to retrieve a android.app.NotificationManager for informing the user of background events.

(Inherited from Context) NsdService

Use with #getSystemService(String) to retrieve a android.net.nsd.NsdManager for handling management of network service discovery

(Inherited from Context) PeopleService

Use with #getSystemService(String) to access a PeopleManager to interact with your published conversations.

(Inherited from Context) PerformanceHintService

Use with #getSystemService(String) to retrieve a android.os.PerformanceHintManager for accessing the performance hinting service.

(Inherited from Context) PowerService

Use with #getSystemService(String) to retrieve a android.os.PowerManager for controlling power management, including «wake locks,» which let you keep the device on while you’re running long tasks.

(Inherited from Context) PrintService

android.print.PrintManager for printing and managing printers and print tasks.

(Inherited from Context) ReasonChannelRemoved

Notification was canceled due to the backing channel being deleted

Notification was canceled due to the app’s storage being cleared

Flag for #registerReceiver : The receiver can receive broadcasts from Instant Apps.

(Inherited from Context) RestrictionsService

Use with #getSystemService(String) to retrieve a android.content.RestrictionsManager for retrieving application restrictions and requesting permissions for restricted operations.

(Inherited from Context) RoleService

Use with #getSystemService(String) to retrieve a android.app.role.RoleManager for managing roles.

(Inherited from Context) SearchService

Use with #getSystemService(String) to retrieve a android.app.SearchManager for handling searches.

(Inherited from Context) SensorService

Use with #getSystemService(String) to retrieve a android.hardware.SensorManager for accessing sensors.

(Inherited from Context) ServiceInterface

The Intent that must be declared as handled by the service.

Use with #getSystemService(String) to retrieve a android.content.pm.ShortcutManager for accessing the launcher shortcut service.

(Inherited from Context) StopForegroundDetach

Flag for #stopForeground(int) : if set, the notification previously provided to #startForeground will be detached from the service.

(Inherited from Service) StopForegroundRemove

Flag for #stopForeground(int) : if set, the notification previously provided to #startForeground will be removed.

(Inherited from Service) StorageService

Use with #getSystemService(String) to retrieve a android.os.storage.StorageManager for accessing system storage functions.

(Inherited from Context) StorageStatsService

Use with #getSystemService(String) to retrieve a android.app.usage.StorageStatsManager for accessing system storage statistics.

(Inherited from Context) SuppressedEffectScreenOff

Whether notification suppressed by DND should not interruption visually when the screen is off.

Whether notification suppressed by DND should not interruption visually when the screen is on.

Use with #getSystemService(String) to retrieve a android.os.health.SystemHealthManager for accessing system health (battery, power, memory, etc) metrics.

(Inherited from Context) TelecomService

Use with #getSystemService(String) to retrieve a android.telecom.TelecomManager to manage telecom-related features of the device.

(Inherited from Context) TelephonyImsService

Use with #getSystemService(String) to retrieve an android.telephony.ims.ImsManager .

(Inherited from Context) TelephonyService

Use with #getSystemService(String) to retrieve a android.telephony.TelephonyManager for handling management the telephony features of the device.

(Inherited from Context) TelephonySubscriptionService

Use with #getSystemService(String) to retrieve a android.telephony.SubscriptionManager for handling management the telephony subscriptions of the device.

(Inherited from Context) TextClassificationService

Use with #getSystemService(String) to retrieve a TextClassificationManager for text classification services.

(Inherited from Context) TextServicesManagerService

Use with #getSystemService(String) to retrieve a android.view.textservice.TextServicesManager for accessing text services.

(Inherited from Context) TvInputService

Use with #getSystemService(String) to retrieve a android.media.tv.TvInputManager for interacting with TV inputs on the device.

(Inherited from Context) UiModeService

Use with #getSystemService(String) to retrieve a android.app.UiModeManager for controlling UI modes.

(Inherited from Context) UsageStatsService

Use with #getSystemService(String) to retrieve a android.app.usage.UsageStatsManager for querying device usage stats.

(Inherited from Context) UsbService

Use with #getSystemService(String) to retrieve a android.hardware.usb.UsbManager for access to USB devices (as a USB host) and for controlling this device’s behavior as a USB device.

(Inherited from Context) UserService

Use with #getSystemService(String) to retrieve a android.os.UserManager for managing users on devices that support multiple users.

(Inherited from Context) VibratorManagerService

Use with #getSystemService(String) to retrieve a android.os.VibratorManager for accessing the device vibrators, interacting with individual ones and playing synchronized effects on multiple vibrators.

(Inherited from Context) VibratorService

Use with #getSystemService(String) to retrieve a android.os.Vibrator for interacting with the vibration hardware.

(Inherited from Context) VpnManagementService

Use with #getSystemService(String) to retrieve a android.net.VpnManager to manage profiles for the platform built-in VPN.

(Inherited from Context) WallpaperService

Use with #getSystemService(String) to retrieve a com.

(Inherited from Context) WifiAwareService

Use with #getSystemService(String) to retrieve a android.net.wifi.aware.WifiAwareManager for handling management of Wi-Fi Aware.

(Inherited from Context) WifiP2pService

Use with #getSystemService(String) to retrieve a android.net.wifi.p2p.WifiP2pManager for handling management of Wi-Fi peer-to-peer connections.

(Inherited from Context) WifiRttRangingService

Use with #getSystemService(String) to retrieve a android.net.wifi.rtt.WifiRttManager for ranging devices with wifi.

(Inherited from Context) WifiService

Use with #getSystemService(String) to retrieve a android.net.wifi.WifiManager for handling management of Wi-Fi access.

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

(Inherited from Context) WindowService

Use with #getSystemService(String) to retrieve a android.view.WindowManager for accessing the system’s window manager.

(Inherited from Context)

Properties

Return the application that owns this service.

(Inherited from Service) ApplicationContext

Return the context of the single, global Application object of the current process.

(Inherited from ContextWrapper) ApplicationInfo

Return the full application info for this context’s package.

(Inherited from ContextWrapper) Assets

Return an AssetManager instance for your application’s package.

(Inherited from ContextWrapper) AttributionSource (Inherited from Context) AttributionTag

Attribution can be used in complex apps to logically separate parts of the app.

(Inherited from Context) BaseContext (Inherited from ContextWrapper) CacheDir

Returns the absolute path to the application specific cache directory on the filesystem.

(Inherited from ContextWrapper) Class

Returns the runtime class of this Object .

(Inherited from Object) ClassLoader

Return a class loader you can use to retrieve classes in this package.

(Inherited from ContextWrapper) CodeCacheDir

Returns the absolute path to the application specific cache directory on the filesystem designed for storing cached code.

(Inherited from ContextWrapper) ContentResolver

Return a ContentResolver instance for your application’s package.

(Inherited from ContextWrapper) CurrentInterruptionFilter

Gets the current notification interruption filter active on the host.

Gets the set of hints representing current state.

Returns current ranking information.

Get the display this context is associated with.

(Inherited from Context) ExternalCacheDir

Returns the absolute path to the directory on the primary external filesystem (that is somewhere on ExternalStorageDirectory where the application can place cache files it owns.

(Inherited from ContextWrapper) FilesDir

Returns the absolute path to the directory on the filesystem where files created with OpenFileOutput(String, FileCreationMode) are stored.

(Inherited from ContextWrapper) ForegroundServiceType

If the service has become a foreground service by calling #startForeground(int, Notification) or #startForeground(int, Notification, int) , #getForegroundServiceType() returns the current foreground service type.

(Inherited from Service) Handle

The handle to the underlying Android instance.

(Inherited from Object) IsDeviceProtectedStorage (Inherited from ContextWrapper) IsRestricted

Indicates whether this Context is restricted.

(Inherited from Context) IsUiContext

Returns true if the context is a UI context which can access UI components such as WindowManager , android.view.LayoutInflater LayoutInflater or android.app.WallpaperManager WallpaperManager .

(Inherited from Context) JniIdentityHashCode (Inherited from Object) JniPeerMembers MainExecutor

Return an Executor that will run enqueued tasks on the main thread associated with this context.

(Inherited from Context) MainLooper

Return the Looper for the main thread of the current process.

(Inherited from ContextWrapper) NoBackupFilesDir

Returns the absolute path to the directory on the filesystem similar to FilesDir.

(Inherited from ContextWrapper) ObbDir

Return the primary external storage directory where this application’s OBB files (if there are any) can be found.

(Inherited from ContextWrapper) OpPackageName

Return the package name that should be used for android.app.AppOpsManager calls from this context, so that app ops manager’s uid verification will work with the name.

(Inherited from Context) PackageCodePath

Return the full path to this context’s primary Android package.

(Inherited from ContextWrapper) PackageManager

Return PackageManager instance to find global package information.

(Inherited from ContextWrapper) PackageName

Return the name of this application’s package.

(Inherited from ContextWrapper) PackageResourcePath

Return the full path to this context’s primary Android package.

(Inherited from ContextWrapper) Params

Return the set of parameters which this Context was created with, if it was created via #createContext(ContextParams) .

(Inherited from Context) PeerReference (Inherited from Object) Resources

Return a Resources instance for your application’s package.

(Inherited from ContextWrapper) Theme

Return the Theme object associated with this Context.

(Inherited from ContextWrapper) ThresholdClass

This API supports the Mono for Android infrastructure and is not intended to be used directly from your code.

This API supports the Mono for Android infrastructure and is not intended to be used directly from your code.

Methods

Set the base context for this ContextWrapper.

(Inherited from ContextWrapper) BindService(Intent, Bind, IExecutor, IServiceConnection)

Same as #bindService(Intent, ServiceConnection, int) with executor to control ServiceConnection callbacks.

(Inherited from Context) BindService(Intent, IServiceConnection, Bind)

Connect to an application service, creating it if needed.

(Inherited from ContextWrapper) BindServiceAsUser(Intent, IServiceConnection, Int32, UserHandle) (Inherited from Context) CancelAllNotifications()

Inform the notification manager about dismissal of all notifications.

Inform the notification manager about dismissal of a single notification.

Inform the notification manager about dismissal of a single notification.

Inform the notification manager about dismissal of specific notifications.

Determine whether the calling process of an IPC or you have been granted a particular permission.

(Inherited from ContextWrapper) CheckCallingOrSelfUriPermission(Uri, ActivityFlags)

Determine whether the calling process of an IPC or you has been granted permission to access a specific URI.

(Inherited from ContextWrapper) CheckCallingOrSelfUriPermissions(IList , Int32)

Determine whether the calling process of an IPC or you has been granted permission to access a list of URIs.

(Inherited from Context) CheckCallingPermission(String)

Determine whether the calling process of an IPC you are handling has been granted a particular permission.

(Inherited from ContextWrapper) CheckCallingUriPermission(Uri, ActivityFlags)

Determine whether the calling process and user ID has been granted permission to access a specific URI.

(Inherited from ContextWrapper) CheckCallingUriPermissions(IList , Int32)

Determine whether the calling process and user ID has been granted permission to access a list of URIs.

(Inherited from Context) CheckPermission(String, Int32, Int32)

Determine whether the given permission is allowed for a particular process and user ID running in the system.

(Inherited from ContextWrapper) CheckSelfPermission(String) (Inherited from ContextWrapper) CheckUriPermission(Uri, Int32, Int32, ActivityFlags)

Determine whether a particular process and user ID has been granted permission to access a specific URI.

(Inherited from ContextWrapper) CheckUriPermission(Uri, String, String, Int32, Int32, ActivityFlags)

Check both a Uri and normal permission.

(Inherited from ContextWrapper) CheckUriPermissions(IList , Int32, Int32, Int32)

Determine whether a particular process and user ID has been granted permission to access a list of URIs.

(Inherited from Context) ClearRequestedListenerHints()

Clears listener hints set via #getCurrentListenerHints() .

Creates and returns a copy of this object.

(Inherited from Object) CreateAttributionContext(String)

Return a new Context object for the current Context but attribute to a different tag.

(Inherited from Context) CreateConfigurationContext(Configuration)

Return a new Context object for the current Context but whose resources are adjusted to match the given Configuration.

(Inherited from ContextWrapper) CreateContext(ContextParams)

Creates a context with specific properties and behaviors.

(Inherited from Context) CreateContextForSplit(String) (Inherited from ContextWrapper) CreateDeviceProtectedStorageContext() (Inherited from ContextWrapper) CreateDisplayContext(Display)

Return a new Context object for the current Context but whose resources are adjusted to match the metrics of the given Display.

(Inherited from ContextWrapper) CreatePackageContext(String, PackageContextFlags)

Return a new Context object for the given application name.

(Inherited from ContextWrapper) CreateWindowContext(Display, Int32, Bundle)

Creates a Context for a non-activity window.

(Inherited from Context) CreateWindowContext(Int32, Bundle)

Creates a Context for a non-activity window.

(Inherited from Context) DatabaseList()

Returns an array of strings naming the private databases associated with this Context’s application package.

(Inherited from ContextWrapper) DeleteDatabase(String)

Delete an existing private SQLiteDatabase associated with this Context’s application package.

(Inherited from ContextWrapper) DeleteFile(String)

Delete the given private file associated with this Context’s application package.

(Inherited from ContextWrapper) DeleteSharedPreferences(String) (Inherited from ContextWrapper) Dispose() (Inherited from Object) Dispose(Boolean) (Inherited from Object) Dump(FileDescriptor, PrintWriter, String[])

Print the Service’s state into the given stream.

(Inherited from Service) EnforceCallingOrSelfPermission(String, String)

If neither you nor the calling process of an IPC you are handling has been granted a particular permission, throw a SecurityException.

(Inherited from ContextWrapper) EnforceCallingOrSelfUriPermission(Uri, ActivityFlags, String)

If the calling process of an IPC or you has not been granted permission to access a specific URI, throw SecurityException.

(Inherited from ContextWrapper) EnforceCallingPermission(String, String)

If the calling process of an IPC you are handling has not been granted a particular permission, throw a SecurityException.

(Inherited from ContextWrapper) EnforceCallingUriPermission(Uri, ActivityFlags, String)

If the calling process and user ID has not been granted permission to access a specific URI, throw SecurityException.

(Inherited from ContextWrapper) EnforcePermission(String, Int32, Int32, String)

If the given permission is not allowed for a particular process and user ID running in the system, throw a SecurityException.

(Inherited from ContextWrapper) EnforceUriPermission(Uri, Int32, Int32, ActivityFlags, String)

If a particular process and user ID has not been granted permission to access a specific URI, throw SecurityException.

(Inherited from ContextWrapper) EnforceUriPermission(Uri, String, String, Int32, Int32, ActivityFlags, String)

Enforce both a Uri and normal permission.

(Inherited from ContextWrapper) Equals(Object)

Indicates whether some other object is «equal to» this one.

(Inherited from Object) FileList()

Returns an array of strings naming the private files associated with this Context’s application package.

(Inherited from ContextWrapper) GetActiveNotifications()

Request the list of outstanding notifications (that is, those that are visible to the current user).

Request the list of outstanding notifications (that is, those that are visible to the current user).

Returns a color associated with a particular resource ID and styled for the current theme.

(Inherited from Context) GetColorStateList(Int32)

Returns a color state list associated with a particular resource ID and styled for the current theme.

(Inherited from Context) GetDatabasePath(String) (Inherited from ContextWrapper) GetDir(String, FileCreationMode)

Retrieve, creating if needed, a new directory in which the application can place its own custom data files.

(Inherited from ContextWrapper) GetDrawable(Int32)

Returns a drawable object associated with a particular resource ID and styled for the current theme.

(Inherited from Context) GetExternalCacheDirs()

Returns absolute paths to application-specific directories on all external storage devices where the application can place cache files it owns.

(Inherited from ContextWrapper) GetExternalFilesDir(String)

Returns the absolute path to the directory on the primary external filesystem (that is somewhere on ExternalStorageDirectory) where the application can place persistent files it owns.

(Inherited from ContextWrapper) GetExternalFilesDirs(String)

Returns absolute paths to application-specific directories on all external storage devices where the application can place persistent files it owns.

Читайте также:  Формата vsd для андроида

(Inherited from ContextWrapper) GetExternalMediaDirs()

Returns absolute paths to application-specific directories on all external storage devices where the application can place media files.

(Inherited from ContextWrapper) GetFileStreamPath(String)

Returns the absolute path on the filesystem where a file created with OpenFileOutput(String, FileCreationMode) is stored.

(Inherited from ContextWrapper) GetHashCode()

Returns a hash code value for the object.

(Inherited from Object) GetNotificationChannelGroups(String, UserHandle)

Returns all notification channel groups belonging to the given package for a given user.

Returns all notification channels belonging to the given package for a given user.

Returns absolute paths to application-specific directories on all external storage devices where the application’s OBB files (if there are any) can be found.

(Inherited from ContextWrapper) GetSharedPreferences(String, FileCreationMode)

Retrieve and hold the contents of the preferences file ‘name’, returning a SharedPreferences through which you can retrieve and modify its values.

(Inherited from ContextWrapper) GetSnoozedNotifications()

Like #getActiveNotifications() , but returns the list of currently snoozed notifications, for all users this listener has access to.

Returns a localized string from the application’s package’s default string table.

(Inherited from Context) GetString(Int32, Object[])

Returns a localized string from the application’s package’s default string table.

(Inherited from Context) GetSystemService(Class)

Return the handle to a system-level service by class.

(Inherited from Context) GetSystemService(String)

Return the handle to a system-level service by name.

(Inherited from ContextWrapper) GetSystemServiceName(Class) (Inherited from ContextWrapper) GetText(Int32)

Return a localized, styled CharSequence from the application’s package’s default string table.

(Inherited from Context) GetTextFormatted(Int32)

Return a localized, styled CharSequence from the application’s package’s default string table.

(Inherited from Context) GrantUriPermission(String, Uri, ActivityFlags)

Grant permission to access a specific Uri to another package, regardless of whether that package has general permission to access the Uri’s content provider.

(Inherited from ContextWrapper) JavaFinalize()

Called by the garbage collector on an object when garbage collection determines that there are no more references to the object.

(Inherited from Object) MigrateNotificationFilter(Int32, IList )

Lets an app migrate notification filters from its app into the OS.

MoveDatabaseFrom(Context, String) (Inherited from ContextWrapper) MoveSharedPreferencesFrom(Context, String) (Inherited from ContextWrapper) Notify()

Wakes up a single thread that is waiting on this object’s monitor.

(Inherited from Object) NotifyAll()

Wakes up all threads that are waiting on this object’s monitor.

(Inherited from Object) ObtainStyledAttributes(IAttributeSet, Int32[])

Retrieve styled attribute information in this Context’s theme.

(Inherited from Context) ObtainStyledAttributes(IAttributeSet, Int32[], Int32, Int32)

Retrieve styled attribute information in this Context’s theme.

(Inherited from Context) ObtainStyledAttributes(Int32, Int32[])

Retrieve styled attribute information in this Context’s theme.

(Inherited from Context) ObtainStyledAttributes(Int32[])

Retrieve styled attribute information in this Context’s theme.

(Inherited from Context) OnBind(Intent)

This is not the lifecycle event you are looking for.

Called by the system when the device configuration changes while your component is running.

(Inherited from Service) OnCreate()

Called by the system when the service is first created.

(Inherited from Service) OnDestroy()

Called by the system to notify a Service that it is no longer used and is being removed.

(Inherited from Service) OnInterruptionFilterChanged(InterruptionFilterType)

Implement this method to be notified when the #getCurrentInterruptionFilter() interruption filter changed.

Implement this method to learn about when the listener is enabled and connected to the notification manager.

Implement this method to learn about when the listener is disconnected from the notification manager.

Implement this method to be notified when the #getCurrentListenerHints() Listener hints change.

This is called when the overall system is running low on memory, and actively running processes should trim their memory usage.

(Inherited from Service) OnNotificationChannelGroupModified(String, UserHandle, NotificationChannelGroup, NotificationChannelOrGroupEventType)

Implement this method to learn about notification channel group modifications.

Implement this method to learn about notification channel modifications.

Implement this method to learn about new notifications as they are posted by apps.

Implement this method to learn about new notifications as they are posted by apps.

Implement this method to be notified when the notification ranking changes.

Implement this method to learn when notifications are removed.

Implement this method to learn when notifications are removed.

Implement this method to learn when notifications are removed.

Called when new clients have connected to the service, after it had previously been notified that all had disconnected in its #onUnbind .

(Inherited from Service) OnSilentStatusBarIconsVisibilityChanged(Boolean)

Implement this method to be notified when the behavior of silent notifications in the status bar changes.

Called by the system every time a client explicitly starts the service by calling android.content.Context#startService , providing the arguments it supplied and a unique integer token representing the start request.

(Inherited from Service) OnTaskRemoved(Intent)

This is called if the service is currently running and the user has removed a task that comes from the service’s application.

(Inherited from Service) OnTrimMemory(TrimMemory)

Called when the operating system has determined that it is a good time for a process to trim unneeded memory from its process.

(Inherited from Service) OnUnbind(Intent)

Called when all clients have disconnected from a particular interface published by the service.

(Inherited from Service) OpenFileInput(String)

Open a private file associated with this Context’s application package for reading.

(Inherited from ContextWrapper) OpenFileOutput(String, FileCreationMode)

Open a private file associated with this Context’s application package for writing.

(Inherited from ContextWrapper) OpenOrCreateDatabase(String, FileCreationMode, SQLiteDatabase+ICursorFactory)

Open a new private SQLiteDatabase associated with this Context’s application package.

(Inherited from ContextWrapper) OpenOrCreateDatabase(String, FileCreationMode, SQLiteDatabase+ICursorFactory, IDatabaseErrorHandler)

Open a new private SQLiteDatabase associated with this Context’s application package.

(Inherited from ContextWrapper) PeekWallpaper()

Add a new ComponentCallbacks to the base application of the Context, which will be called at the same times as the ComponentCallbacks methods of activities and other components are called.

(Inherited from Context) RegisterReceiver(BroadcastReceiver, IntentFilter)

Register a BroadcastReceiver to be run in the main activity thread.

(Inherited from ContextWrapper) RegisterReceiver(BroadcastReceiver, IntentFilter, ActivityFlags) (Inherited from ContextWrapper) RegisterReceiver(BroadcastReceiver, IntentFilter, String, Handler)

Register to receive intent broadcasts, to run in the context of scheduler .

(Inherited from ContextWrapper) RegisterReceiver(BroadcastReceiver, IntentFilter, String, Handler, ActivityFlags) (Inherited from ContextWrapper) RemoveStickyBroadcast(Intent)

Sets the desired #getCurrentInterruptionFilter() interruption filter .

Sets the desired #getCurrentListenerHints() listener hints .

Request that the listener be rebound, after a previous call to #requestUnbind .

Request that the service be unbound.

Remove all permissions to access a particular content provider Uri that were previously added with M:Android.Content.Context.GrantUriPermission(System.String,Android.Net.Uri,Android.Net.Uri).

(Inherited from ContextWrapper) SendBroadcast(Intent)

Broadcast the given intent to all interested BroadcastReceivers.

(Inherited from ContextWrapper) SendBroadcast(Intent, String)

Broadcast the given intent to all interested BroadcastReceivers, allowing an optional required permission to be enforced.

(Inherited from ContextWrapper) SendBroadcastAsUser(Intent, UserHandle)

Version of SendBroadcast(Intent) that allows you to specify the user the broadcast will be sent to.

(Inherited from ContextWrapper) SendBroadcastAsUser(Intent, UserHandle, String)

Version of SendBroadcast(Intent, String) that allows you to specify the user the broadcast will be sent to.

(Inherited from ContextWrapper) SendBroadcastWithMultiplePermissions(Intent, String[])

Broadcast the given intent to all interested BroadcastReceivers, allowing an array of required permissions to be enforced.

(Inherited from Context) SendOrderedBroadcast(Intent, Int32, String, String, BroadcastReceiver, Handler, String, Bundle, Bundle) (Inherited from ContextWrapper) SendOrderedBroadcast(Intent, String) (Inherited from ContextWrapper) SendOrderedBroadcast(Intent, String, BroadcastReceiver, Handler, Result, String, Bundle)

Version of SendBroadcast(Intent) that allows you to receive data back from the broadcast.

(Inherited from ContextWrapper) SendOrderedBroadcast(Intent, String, String, BroadcastReceiver, Handler, Result, String, Bundle) (Inherited from Context) SendOrderedBroadcastAsUser(Intent, UserHandle, String, BroadcastReceiver, Handler, Result, String, Bundle) (Inherited from ContextWrapper) SendStickyBroadcast(Intent)

Perform a #sendBroadcast(Intent) that is «sticky,» meaning the Intent you are sending stays around after the broadcast is complete, so that others can quickly retrieve that data through the return value of #registerReceiver(BroadcastReceiver, IntentFilter) .

(Inherited from ContextWrapper) SendStickyBroadcast(Intent, Bundle)

Perform a #sendBroadcast(Intent) that is «sticky,» meaning the Intent you are sending stays around after the broadcast is complete, so that others can quickly retrieve that data through the return value of #registerReceiver(BroadcastReceiver, IntentFilter) .

(Inherited from Context) SendStickyBroadcastAsUser(Intent, UserHandle)

(Inherited from ContextWrapper) SetForeground(Boolean) (Inherited from Service) SetHandle(IntPtr, JniHandleOwnership)

Sets the Handle property.

(Inherited from Object) SetNotificationsShown(String[])

Inform the notification manager that these notifications have been viewed by the user.

Set the base theme for this context.

(Inherited from ContextWrapper) SetWallpaper(Bitmap)

Inform the notification manager about snoozing a specific notification.

Same as StartActivities(Intent[], Bundle) with no options specified.

(Inherited from ContextWrapper) StartActivities(Intent[], Bundle)

Launch multiple new activities.

(Inherited from ContextWrapper) StartActivity(Intent)

Same as StartActivity(Intent, Bundle) with no options specified.

(Inherited from ContextWrapper) StartActivity(Intent, Bundle)

Launch a new activity.

(Inherited from ContextWrapper) StartActivity(Type) (Inherited from Context) StartForeground(Int32, Notification)

If your service is started (running through Context#startService(Intent) ), then also make this service run in the foreground, supplying the ongoing notification to be shown to the user while in this state.

(Inherited from Service) StartForeground(Int32, Notification, ForegroundService)

If your service is started (running through Context#startService(Intent) ), then also make this service run in the foreground, supplying the ongoing notification to be shown to the user while in this state.

(Inherited from Service) StartForegroundService(Intent) (Inherited from ContextWrapper) StartInstrumentation(ComponentName, String, Bundle)

Start executing an Instrumentation class.

(Inherited from ContextWrapper) StartIntentSender(IntentSender, Intent, ActivityFlags, ActivityFlags, Int32) (Inherited from ContextWrapper) StartIntentSender(IntentSender, Intent, ActivityFlags, ActivityFlags, Int32, Bundle)

Like StartActivity(Intent, Bundle), but taking a IntentSender to start.

(Inherited from ContextWrapper) StartService(Intent)

Request that a given application service be started.

(Inherited from ContextWrapper) StopForeground(Boolean)

Remove this service from foreground state, allowing it to be killed if more memory is needed.

(Inherited from Service) StopForeground(StopForegroundFlags)

Remove this service from foreground state, allowing it to be killed if more memory is needed.

(Inherited from Service) StopSelf()

Stop the service, if it was previously started.

(Inherited from Service) StopSelf(Int32)

Stop the service, if it was previously started.

(Inherited from Service) StopSelfResult(Int32)

Stop the service if the most recent time it was started was startId .

(Inherited from Service) StopService(Intent)

Request that a given application service be stopped.

(Inherited from ContextWrapper) ToArray () (Inherited from Object) ToString()

Returns a string representation of the object.

(Inherited from Object) UnbindService(IServiceConnection)

Disconnect from an application service.

(Inherited from ContextWrapper) UnregisterComponentCallbacks(IComponentCallbacks)

Remove a ComponentCallbacks object that was previously registered with #registerComponentCallbacks(ComponentCallbacks) .

(Inherited from Context) UnregisterFromRuntime() (Inherited from Object) UnregisterReceiver(BroadcastReceiver)

Unregister a previously registered BroadcastReceiver.

(Inherited from ContextWrapper) UpdateNotificationChannel(String, UserHandle, NotificationChannel)

Updates a notification channel for a given package for a given user.

For a service previously bound with #bindService or a related method, change how the system manages that service’s process in relation to other processes.

(Inherited from Context) Wait()

Causes the current thread to wait until another thread invokes the java.lang.Object#notify() method or the java.lang.Object#notifyAll() method for this object.

(Inherited from Object) Wait(Int64)

Causes the current thread to wait until another thread invokes the java.lang.Object#notify() method or the java.lang.Object#notifyAll() method for this object.

(Inherited from Object) Wait(Int64, Int32)

Causes the current thread to wait until another thread invokes the java.lang.Object#notify() method or the java.lang.Object#notifyAll() method for this object.

(Inherited from Object)

Explicit Interface Implementations

IJavaPeerable.Disposed() (Inherited from Object)
IJavaPeerable.DisposeUnlessReferenced() (Inherited from Object)
IJavaPeerable.Finalized() (Inherited from Object)
IJavaPeerable.JniManagedPeerState (Inherited from Object)
IJavaPeerable.SetJniIdentityHashCode(Int32) (Inherited from Object)
IJavaPeerable.SetJniManagedPeerState(JniManagedPeerStates) (Inherited from Object)
IJavaPeerable.SetPeerReference(JniObjectReference) (Inherited from Object)

Extension Methods

Performs an Android runtime-checked type conversion.

Источник

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