Commit ae70af1e by songyanzhi

feat:init

parent 9290ecd4
# EditorConfig is awesome:http://EditorConfig.org
# top-most EditorConfig file
root = true
# Don't use tabs for indentation.
[*]
indent_style = space
# (Please don't specify an indent_size here; that has too many unintended consequences.)
# Code files
[*.{cs,csx,vb,vbx}]
indent_size = 4
insert_final_newline = true
charset = utf-8-bom
# Xml project files
[*.{csproj,vbproj,vcxproj,vcxproj.filters,proj,projitems,shproj}]
indent_size = 2
# Xml config files
[*.{props,targets,ruleset,config,nuspec,resx,vsixmanifest,vsct}]
indent_size = 2
# JSON files
[*.json]
indent_size = 2
# Dotnet code style settings:
[*.{cs,vb}]
# Sort using and Import directives with System.* appearing first
dotnet_sort_system_directives_first = true
# Avoid "this." and "Me." if not necessary
dotnet_style_qualification_for_field = false:suggestion
dotnet_style_qualification_for_property = false:suggestion
dotnet_style_qualification_for_method = false:suggestion
dotnet_style_qualification_for_event = false:suggestion
# Use language keywords instead of framework type names for type references
dotnet_style_predefined_type_for_locals_parameters_members = true:suggestion
dotnet_style_predefined_type_for_member_access = true:suggestion
# Suggest more modern language features when available
dotnet_style_object_initializer = true:suggestion
dotnet_style_collection_initializer = true:suggestion
dotnet_style_coalesce_expression = true:suggestion
dotnet_style_null_propagation = true:suggestion
dotnet_style_explicit_tuple_names = true:suggestion
# CSharp code style settings:
[*.cs]
# Prefer "var" everywhere
csharp_style_var_for_built_in_types = true:suggestion
csharp_style_var_when_type_is_apparent = true:suggestion
csharp_style_var_elsewhere = true:suggestion
# Prefer method-like constructs to have a block body
csharp_style_expression_bodied_methods = false:none
csharp_style_expression_bodied_constructors = false:none
csharp_style_expression_bodied_operators = false:none
# Prefer property-like constructs to have an expression-body
csharp_style_expression_bodied_properties = true:none
csharp_style_expression_bodied_indexers = true:none
csharp_style_expression_bodied_accessors = true:none
# Suggest more modern language features when available
csharp_style_pattern_matching_over_is_with_cast_check = true:suggestion
csharp_style_pattern_matching_over_as_with_null_check = true:suggestion
csharp_style_inlined_variable_declaration = true:suggestion
csharp_style_throw_expression = true:suggestion
csharp_style_conditional_delegate_call = true:suggestion
# Newline settings
csharp_new_line_before_open_brace = all
csharp_new_line_before_else = true
csharp_new_line_before_catch = true
csharp_new_line_before_finally = true
csharp_new_line_before_members_in_object_initializers = true
csharp_new_line_before_members_in_anonymous_types = true
# This file is understood by git 1.7.2+.
# Windows specific files should always be crlf on checkout
*.bat text eol=crlf
*.cmd text eol=crlf
*.ps1 text eol=crlf
# Check out the following as ln always for osx/linux/cygwin
*.sh text eol=lf
# Opt in the following types to always normalize line endings
# on checkin and always use native endings on checkout.
*.config text
*.cs text diff=csharp
*.csproj text
*.md text
*.msbuild text
*.nuspec text
*.pp text
*.ps1 text
*.sln text
*.tt text
*.txt text
*.xaml text
*.xml text
# Binary files
*.bmp binary
*.jpeg binary
*.jpg binary
*.nupkg binary
*.png binary
*.sdf binary
*.java linguist-language=Dart
*.kt linguist-language=Dart
*.swift linguist-language=Dart
*.m linguist-language=Dart
*.h linguist-language=Dart
# Miscellaneous
*.class
*.lock
*.log
*.pyc
*.swp
.DS_Store
.atom/
.buildlog/
.history
.project
.svn/
bin/
migrate_working_dir/
# IntelliJ related
*.iml
*.ipr
*.iws
.idea/
# Android Studio related
android/.classpath
android/.settings/
# Visual Studio Code related
.vscode/
# Flutter repo-specific
/bin/cache/
/bin/mingit/
/dev/benchmarks/mega_gallery/
/dev/bots/.recipe_deps
/dev/bots/android_tools/
/dev/docs/doc/
/dev/docs/lib/
/dev/docs/pubspec.yaml
/packages/flutter/coverage/
version
# Flutter/Dart/Pub related
/pubspec.lock
**/doc/api/
.dart_tool/
.flutter-plugins
.flutter-plugins-dependencies
.packages
.pub-cache/
.pub/
build/
flutter_*.png
linked_*.ds
unlinked.ds
unlinked_spec.ds
flutter_export_environment.sh
# Android related
**/android/**/gradle-wrapper.jar
**/android/.gradle
**/android/captures/
**/android/gradlew
**/android/gradlew.bat
**/android/local.properties
**/android/**/GeneratedPluginRegistrant.java
# iOS/XCode related
**/ios/**/*.mode1v3
**/ios/**/*.mode2v3
**/ios/**/*.moved-aside
**/ios/**/*.pbxuser
**/ios/**/*.perspectivev3
**/ios/**/*sync/
**/ios/**/.sconsign.dblite
**/ios/**/.tags*
**/ios/**/.vagrant/
**/ios/**/DerivedData/
**/ios/**/Icon?
**/ios/**/Pods/
**/ios/**/.symlinks/
**/ios/**/profile
**/ios/**/xcuserdata
**/ios/.generated/
**/ios/Flutter/App.framework
**/ios/Flutter/Flutter.framework
**/ios/Flutter/Generated.xcconfig
**/ios/Flutter/app.flx
**/ios/Flutter/app.zip
**/ios/Flutter/flutter_assets/
**/ios/ServiceDefinitions.json
**/ios/Runner/GeneratedPluginRegistrant.*
# Exceptions to above rules.
!**/ios/**/default.mode1v3
!**/ios/**/default.mode2v3
!**/ios/**/default.pbxuser
!**/ios/**/default.perspectivev3
!/packages/flutter_tools/test/data/dart_dependencies_test/**/.packages
# This file tracks properties of this Flutter project.
# Used by Flutter tool to assess capabilities and perform upgrades etc.
#
# This file should be version controlled and should not be manually edited.
version:
revision: 06b979c4d5e1b499745422269f01a00341257058
channel: master
project_type: plugin
# Contributor Covenant Code of Conduct
## Our Pledge
In the interest of fostering an open and welcoming environment, we as
contributors and maintainers pledge to participate in our project and
our community a harassment-free experience for everyone, regardless of age, body
size, disability, ethnicity, gender identity and expression, level of experience,
nationality, personal appearance, race, religion, or sexual identity and
orientation.
## Our Standards
Examples of behavior that contributes to creating a positive environment
include:
* Using welcoming and inclusive language
* Being respectful of differing viewpoints and experiences
* Gracefully accepting constructive criticism
* Focusing on what is best for the community
* Showing empathy towards other community members
Examples of unacceptable behavior by participants include:
* The use of sexualized language or imagery and unwelcome sexual attention or
advances
* Trolling, insulting/derogatory comments, and personal or political attacks
* Public or private harassment
* Publishing others' private information, such as physical or electronic
address, without explicit permission
* Other conduct that could reasonably be considered inappropriate in a
professional setting
## Our Responsibilities
Project maintainers are responsible for clarifying the standards of acceptable
behavior and are expected to take appropriate and fair corrective action in
response to any instances of unacceptable behavior.
Project maintainers have the right and responsibility to remove, edit, or
reject comments, commits, code, wiki edits, issues, and other contributions
that are not aligned to this Code of Conduct, or to ban temporarily or
permanently any contributor for other behaviors that they deem inappropriate,
threatening, offensive, or harmful.
## Scope
This Code of Conduct applies both within and in public spaces
when an individual represents the project or its community. Examples of
representing a project or community include using an official project e-mail
address, posting via an official social media account, or acting as an appointed
representative at an online or offline event. Representation of a project may be
further defined and clarified by project maintainers.
## Enforcement
Instances of abusive, harassing, or otherwise unacceptable behavior may be
reported by contacting the project team at [hello@baseflow.com](mailto:hello@baseflow.com). All
complaints will be reviewed and investigated and will result in a response that
is deemed necessary and appropriate to the circumstances. The project team is
obligated to maintain confidentiality with regard to the reporter of an incident.
You can post more details of specific enforcement policies separately.
Project maintainers who do not follow or enforce the Code of Conduct in good
Faith may face temporary or permanent repercussions as determined by other
members of the project's leadership.
## Attribution
This Code of Conduct is adapted from the [Contributor Covenant][homepage], version 1.4,
available at [http://contributor-covenant.org/version/1/4][version]
[homepage]: http://contributor-covenant.org
[version]: http://contributor-covenant.org/version/1/4/
# Contributing to the Flutter Permission handler plugin
## What you will need
* A Linux, Mac OS X, or Windows machine (note: to run and compile iOS-specific parts you'll need access to a Mac OS X machine);
* git (used for source version control, installation instructions can be found [here](https://git-scm.com/));
* The Flutter SDK (installation instructions can be found [here](https://flutter.io/get-started/install/));
* A personal GitHub account (if you don't have one, you can sign up for free [here](https://github.com/))
## Setting up your development environment
* Fork `https://github.com/Baseflow/flutter-permission-handler` into your own GitHub account. If you already have a fork and moving to a new computer, make sure you update your fork.
* If you haven't configured your machine with an SSH key that's known to GitHub, then
follow [GitHub's directions](https://help.github.com/articles/generating-ssh-keys/)
to generate an SSH key.
* Clone your forked repo on your local development machine: `git clone git@github.com:<your_name_here>/flutter-permission-handler.git`
* Change into the `flutter-permission-handler` directory: `cd flutter-permission-handler`
* Add an upstream to the original repo, so that fetches from the master repository and not your clone: `git remote add upstream git@github.com:Baseflow/flutter-permission-handler.git`
## Running the example project
* Change into the example directory: `cd example`
* Run the App: `flutter run`
## Contribute
We really appreciate contributions via GitHub pull requests. To contribute take the following steps:
* Make sure you are up to date with the latest code on the master:
* `git fetch upstream`
* `git checkout upstream/develop -b <name_of_your_branch>`
* Apply your changes
* Verify your changes and fix potential warnings/ errors:
* Check formatting: `flutter format .`
* Run static analyses: `flutter analyze`
* Run unit-tests: `flutter test`
* Commit your changes: `git commit -am "<your informative commit message>"`
* Push changes to your fork: `git push origin <name_of_your_branch>`
Send us your pull request:
* Go to `https://github.com/Baseflow/flutter-permission-handler` and click the "Compare & pull request" button.
Please make sure you solved all warnings and errors reported by the static code analyses and that you fill in the full pull request template. Failing to do so will result in us asking you to fix it.
MIT License MIT License
Copyright (c) 2020 Baseflow Copyright (c) 2018 Baseflow
Permission is hereby granted, free of charge, to any person obtaining a copy Permission is hereby granted, free of charge, to any person obtaining a copy
of this software and associated documentation files (the "Software"), to deal of this software and associated documentation files (the "Software"), to deal
......
# Flutter permission_handler plugin [![pub package](https://img.shields.io/pub/v/permission_handler.svg)](https://pub.dartlang.org/packages/permission_handler) [![Build status](https://github.com/Baseflow/flutter-permission-handler/actions/workflows/permission_handler.yaml/badge.svg?branch=master)](https://github.com/Baseflow/flutter-permission-handler/actions/workflows/permission_handler.yaml) [![style: effective dart](https://img.shields.io/badge/style-effective_dart-40c4ff.svg)](https://github.com/tenhobi/effective_dart) [![codecov](https://codecov.io/gh/Baseflow/flutter-permission-handler/branch/master/graph/badge.svg)](https://codecov.io/gh/Baseflow/flutter-permission-handler)
The Flutter permission_handler plugin is build following the federated plugin architecture. A detailed explanation of the federated plugin concept can be found in the [Flutter documentation](https://flutter.dev/docs/development/packages-and-plugins/developing-packages#federated-plugins). This means the permission_handler plugin is separated into the following packages: On most operating systems, permissions aren't just granted to apps at install time.
Rather, developers have to ask the user for permission while the app is running.
1. [`permission_handler`][1]: the app facing package. This is the package users depend on to use the plugin in their project. For details on how to use the `permission_handler` plugin you can refer to its [README.md][2] file. At this moment the Android and iOS platform implementations are also part of this package. Additional platform support will be added in their own individual "platform package(s)". This plugin provides a cross-platform (iOS, Android) API to request permissions and check their status.
2. [`permission_handler_platform_interface`][3]: this packages declares the interface which all platform packages must implement to support the app-facing package. Instructions on how to implement a platform packages can be found in the [README.md][4] of the `permission_handler_platform_interface` package. You can also open the device's app settings so users can grant permission.
On Android, you can show a rationale for requesting permission.
[1]: https://pub.dev/packages/permission_handler See the [FAQ](#faq) section for more information on common questions when using the permission_handler plugin.
[2]: ./permission_handler/README.md
[3]: https://pub.dev/packages/permission_handler_platform_interface ## Setup
[4]: ./permission_handler_platform_interface/README.md
While the permissions are being requested during runtime, you'll still need to tell the OS which permissions your app might potentially use. That requires adding permission configuration to Android* and iOS-specific files.
<details>
<summary>Android (click to expand)</summary>
**Upgrade pre-1.12 Android projects**
Since version 4.4.0 this plugin is implemented using the Flutter 1.12 Android plugin APIs. Unfortunately, this means App developers also need to migrate their Apps to support the new Android infrastructure. You can do so by following the [Upgrading pre 1.12 Android projects](https://github.com/flutter/flutter/wiki/Upgrading-pre-1.12-Android-projects) migration guide. Failing to do so might result in unexpected behavior. The most common known error is the permission_handler not returning after calling the `.request()` method on permission.
**AndroidX**
As of version 3.1.0, the <kbd>permission_handler</kbd> plugin switched to the AndroidX version of the Android Support Libraries. This means you need to make sure your Android project is also upgraded to support AndroidX. Detailed instructions can be found [here](https://flutter.dev/docs/development/packages-and-plugins/androidx-compatibility).
The TL;DR version is:
1. Add the following to your "gradle.properties" file:
```properties
android.useAndroidX=true
android.enableJetifier=true
```
2. Make sure you set the `compileSdkVersion` in your "android/app/build.gradle" file to 33:
```gradle
android {
compileSdkVersion 33
...
}
```
3. Make sure you replace all the `android.` dependencies to their AndroidX counterparts (a full list can be found [here](https://developer.android.com/jetpack/androidx/migrate)).
Add permissions to your `AndroidManifest.xml` file.
There are `debug`, `main`, and `profile` versions which are chosen depending on how you start your app.
In general, it's sufficient to add permission only to the `main` version.
[Here](https://github.com/Baseflow/flutter-permission-handler/blob/master/permission_handler/example/android/app/src/main/AndroidManifest.xml)'s an example `AndroidManifest.xml` with a complete list of all possible permissions.
</details>
<details>
<summary>iOS (click to expand)</summary>
Add permission to your `Info.plist` file.
[Here](https://github.com/Baseflow/flutter-permission-handler/blob/master/permission_handler/example/ios/Runner/Info.plist)'s an example `Info.plist` with a complete list of all possible permissions.
> IMPORTANT: ~~You will have to include all permission options when you want to submit your App.~~ This is because the `permission_handler` plugin touches all different SDKs and because the static code analyzer (run by Apple upon App submission) detects this and will assert if it cannot find a matching permission option in the `Info.plist`. More information about this can be found [here](https://github.com/Baseflow/flutter-permission-handler/issues/26).
The <kbd>permission_handler</kbd> plugin use [macros](https://github.com/Baseflow/flutter-permission-handler/blob/master/permission_handler_apple/ios/Classes/PermissionHandlerEnums.h) to control whether a permission is enabled.
You must list the permission you want to use in your application:
1. Add the following to your `Podfile` file:
```ruby
post_install do |installer|
installer.pods_project.targets.each do |target|
flutter_additional_ios_build_settings(target)
target.build_configurations.each do |config|
# You can remove unused permissions here
# for more information: https://github.com/BaseflowIT/flutter-permission-handler/blob/master/permission_handler/ios/Classes/PermissionHandlerEnums.h
# e.g. when you don't need camera permission, just add 'PERMISSION_CAMERA=0'
config.build_settings['GCC_PREPROCESSOR_DEFINITIONS'] ||= [
'$(inherited)',
## dart: PermissionGroup.calendar
'PERMISSION_EVENTS=1',
## dart: PermissionGroup.calendarFullAccess
'PERMISSION_EVENTS_FULL_ACCESS=1',
## dart: PermissionGroup.reminders
'PERMISSION_REMINDERS=1',
## dart: PermissionGroup.contacts
'PERMISSION_CONTACTS=1',
## dart: PermissionGroup.camera
'PERMISSION_CAMERA=1',
## dart: PermissionGroup.microphone
'PERMISSION_MICROPHONE=1',
## dart: PermissionGroup.speech
'PERMISSION_SPEECH_RECOGNIZER=1',
## dart: PermissionGroup.photos
'PERMISSION_PHOTOS=1',
## The 'PERMISSION_LOCATION' macro enables the `locationWhenInUse` and `locationAlways` permission. If
## the application only requires `locationWhenInUse`, only specify the `PERMISSION_LOCATION_WHENINUSE`
## macro.
##
## dart: [PermissionGroup.location, PermissionGroup.locationAlways, PermissionGroup.locationWhenInUse]
'PERMISSION_LOCATION=1',
'PERMISSION_LOCATION_WHENINUSE=0',
## dart: PermissionGroup.notification
'PERMISSION_NOTIFICATIONS=1',
## dart: PermissionGroup.mediaLibrary
'PERMISSION_MEDIA_LIBRARY=1',
## dart: PermissionGroup.sensors
'PERMISSION_SENSORS=1',
## dart: PermissionGroup.bluetooth
'PERMISSION_BLUETOOTH=1',
## dart: PermissionGroup.appTrackingTransparency
'PERMISSION_APP_TRACKING_TRANSPARENCY=1',
## dart: PermissionGroup.criticalAlerts
'PERMISSION_CRITICAL_ALERTS=1',
## dart: PermissionGroup.criticalAlerts
'PERMISSION_ASSISTANT=1',
]
end
end
end
```
2. Remove the `#` character in front of the permission you want to use. For example, if you need access to the calendar make sure the code looks like this:
```ruby
## dart: PermissionGroup.calendar
'PERMISSION_EVENTS=1',
```
3. Delete the corresponding permission description in `Info.plist`
e.g. when you don't need camera permission, just delete 'NSCameraUsageDescription'
The following lists the relationship between `Permission` and `The key of Info.plist`:
| Permission | Info.plist | Macro |
|---------------------------------------------------------------------------------------------| ------------------------------------------------------------------------------------------------------------- | ------------------------------------ |
| PermissionGroup.calendar (< iOS 17) | NSCalendarsUsageDescription | PERMISSION_EVENTS |
| PermissionGroup.calendarWriteOnly (iOS 17+) | NSCalendarsWriteOnlyAccessUsageDescription | PERMISSION_EVENTS |
| PermissionGroup.calendarFullAccess (iOS 17+) | NSCalendarsFullAccessUsageDescription | PERMISSION_EVENTS_FULL_ACCESS |
| PermissionGroup.reminders | NSRemindersUsageDescription | PERMISSION_REMINDERS |
| PermissionGroup.contacts | NSContactsUsageDescription | PERMISSION_CONTACTS |
| PermissionGroup.camera | NSCameraUsageDescription | PERMISSION_CAMERA |
| PermissionGroup.microphone | NSMicrophoneUsageDescription | PERMISSION_MICROPHONE |
| PermissionGroup.speech | NSSpeechRecognitionUsageDescription | PERMISSION_SPEECH_RECOGNIZER |
| PermissionGroup.photos | NSPhotoLibraryUsageDescription | PERMISSION_PHOTOS |
| PermissionGroup.photosAddOnly | NSPhotoLibraryAddUsageDescription | PERMISSION_PHOTOS_ADD_ONLY |
| PermissionGroup.location, PermissionGroup.locationAlways, PermissionGroup.locationWhenInUse | NSLocationUsageDescription, NSLocationAlwaysAndWhenInUseUsageDescription, NSLocationWhenInUseUsageDescription | PERMISSION_LOCATION |
| PermissionGroup.locationWhenInUse | NSLocationWhenInUseUsageDescription | PERMISSION_LOCATION_WHENINUSE |
| PermissionGroup.notification | PermissionGroupNotification | PERMISSION_NOTIFICATIONS |
| PermissionGroup.mediaLibrary | NSAppleMusicUsageDescription, kTCCServiceMedia |
PERMISSION_MEDIA_LIBRARY |
4. Clean & Rebuild
</details>
## How to use
There are a number of [`Permission`](https://pub.dev/documentation/permission_handler_platform_interface/latest/permission_handler_platform_interface/Permission-class.html#constants)s.
You can get a `Permission`'s `status`, which is either `granted`, `denied`, `restricted`, `permanentlyDenied`, `limited`, or `provisional`.
```dart
var status = await Permission.camera.status;
if (status.isDenied) {
// We haven't asked for permission yet or the permission has been denied before, but not permanently.
}
// You can also directly ask permission about its status.
if (await Permission.location.isRestricted) {
// The OS restricts access, for example, because of parental controls.
}
```
Can use also this style for better readability of your code when using the `Permission` class.
```dart
await Permission.camera
.onDeniedCallback(() {
// Your code
})
.onGrantedCallback(() {
// Your code
})
.onPermanentlyDeniedCallback(() {
// Your code
})
.onRestrictedCallback(() {
// Your code
})
.onLimitedCallback(() {
// Your code
})
.onProvisionalCallback(() {
// Your code
})
.request();
```
Call `request()` on a `Permission` to request it.
If it has already been granted before, nothing happens.
`request()` returns the new status of the `Permission`.
```dart
if (await Permission.contacts.request().isGranted) {
// Either the permission was already granted before or the user just granted it.
}
// You can request multiple permissions at once.
Map<Permission, PermissionStatus> statuses = await [
Permission.location,
Permission.storage,
].request();
print(statuses[Permission.location]);
```
Some permissions, for example, location or acceleration sensor permissions, have an associated service, which can be `enabled` or `disabled`.
```dart
if (await Permission.locationWhenInUse.serviceStatus.isEnabled) {
// Use location.
}
```
You can also open the app settings:
```dart
if (await Permission.speech.isPermanentlyDenied) {
// The user opted to never again see the permission request dialog for this
// app. The only way to change the permission's status now is to let the
// user manually enables it in the system settings.
openAppSettings();
}
```
On Android, you can show a rationale for using permission:
```dart
bool isShown = await Permission.contacts.shouldShowRequestRationale;
```
Some permissions will not show a dialog asking the user to allow or deny the requested permission.
This is because the OS setting(s) of the app are being retrieved for the corresponding permission.
The status of the setting will determine whether the permission is `granted` or `denied`.
The following permissions will show no dialog:
- Notification
- Bluetooth
The following permissions will show no dialog, but will open the corresponding setting intent for the user to change the permission status:
- manageExternalStorage
- systemAlertWindow
- requestInstallPackages
- accessNotificationPolicy
The `locationAlways` permission can not be requested directly, the user has to request the `locationWhenInUse` permission first.
Accepting this permission by clicking on the 'Allow While Using App' gives the user the possibility to request the `locationAlways` permission.
This will then bring up another permission popup asking you to `Keep Only While Using` or to `Change To Always Allow`.
## FAQ
### Requesting "storage" permissions always returns "denied" on Android 13+. What can I do?
On Android, the `Permission.storage` permission is linked to the Android `READ_EXTERNAL_STORAGE` and `WRITE_EXTERNAL_STORAGE` permissions. Starting from Android 10 (API 29) the `READ_EXTERNAL_STORAGE` and `WRITE_EXTERNAL_STORAGE` permissions have been marked deprecated and have been fully removed/disabled since Android 13 (API 33).
If your application needs access to media files Google recommends using the `READ_MEDIA_IMAGES`, `READ_MEDIA_VIDEO`, or `READ_MEDIA_AUDIO` permissions instead. These can be requested using the `Permission.photos`, `Permission.videos`, and `Permission.audio` respectively. To request these permissions make sure the `compileSdkVersion` in the `android/app/build.gradle` file is set to `33`.
If your application needs access to Android's file system, it is possible to request the `MANAGE_EXTERNAL_STORAGE` permission (using `Permission.manageExternalStorage`). As of Android 11 (API 30), the `MANAGE_EXTERNAL_STORAGE` permission is considered a high-risk or sensitive permission. Therefore it is required to [declare the use of these permissions](https://support.google.com/googleplay/android-developer/answer/9214102) if you intend to release the application via the Google Play Store.
### Requesting `Permission.locationAlways` always returns "denied" on Android 10+ (API 29+). What can I do?
Starting with Android 10, apps are required to first obtain permission to read the device's location in the foreground, before requesting to read the location in the background as well. When requesting the 'location always' permission directly, or when requesting both permissions at the same time, the system will ignore the request. So, instead of calling only `Permission.location.request()`, make sure to first call either `Permission.location.request()` or `Permission.locationWhenInUse.request()`, and obtain permission to read the GPS. Once you obtain this permission, you can call `Permission.locationAlways.request()`. This will present the user with the option to update the settings so the location can always be read in the background. For more information, visit the [Android documentation on requesting location permissions](https://developer.android.com/training/location/permissions#request-only-foreground).
### Checking or requesting a permission terminates the application on iOS. What can I do?
First of all make sure all that the `ios/Runner/Info.plist` file contains entries for all the permissions the application requires. If an entry is missing iOS will terminate the application as soon as the particular permission is being checked or requested.
If the application requires access to SiriKit (by requesting the `Permission.assistant` permission), also make sure to add the `com.apple.developer.siri` entitlement to the application configuration. To do so create a file (if it doesn't exists already) called `Runner.entitlements` in the `ios/Runner` folder that is part of the project. Open the file and add the following contents:
```xml
<?xml version="1.0" encoding="UTF-8"?>
<!DOCTYPE plist PUBLIC "-//Apple//DTD PLIST 1.0//EN" "http://www.apple.com/DTDs/PropertyList-1.0.dtd">
<plist version="1.0">
<dict>
<key>com.apple.developer.siri</key>
<true/>
</dict>
</plist>
```
The important part here is the `key` with value `com.apple.developer.siri` and the element `<true/>`. It is possible that this file also contains other entitlements depending on the needs of the application.
## Issues
Please file any issues, bugs, or feature requests as an issue on our [GitHub](https://github.com/Baseflow/flutter-permission-handler/issues) page. Commercial support is available if you need help with integration with your app or services. You can contact us at [hello@baseflow.com](mailto:hello@baseflow.com).
## Want to contribute
If you would like to contribute to the plugin (e.g. by improving the documentation, solving a bug, or adding a cool new feature), please carefully review our [contribution guide](../CONTRIBUTING.md) and send us your [pull request](https://github.com/Baseflow/flutter-permission-handler/pulls).
## Author
This Permission handler plugin for Flutter is developed by [Baseflow](https://baseflow.com). You can contact us at <hello@baseflow.com>
include: package:flutter_lints/flutter.yaml
linter:
rules:
- public_member_api_docs
MIT License
Copyright (c) 2018 Baseflow
Permission is hereby granted, free of charge, to any person obtaining a copy
of this software and associated documentation files (the "Software"), to deal
in the Software without restriction, including without limitation the rights
to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
copies of the Software, and to permit persons to whom the Software is
furnished to do so, subject to the following conditions:
The above copyright notice and this permission notice shall be included in all
copies or substantial portions of the Software.
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
SOFTWARE.
[![pub package](https://img.shields.io/pub/v/permission_handler.svg)](https://pub.dartlang.org/packages/permission_handler) [![Build status](https://github.com/Baseflow/flutter-permission-handler/actions/workflows/permission_handler.yaml/badge.svg?branch=master)](https://github.com/Baseflow/flutter-permission-handler/actions/workflows/permission_handler.yaml) [![style: effective dart](https://img.shields.io/badge/style-effective_dart-40c4ff.svg)](https://github.com/tenhobi/effective_dart) [![codecov](https://codecov.io/gh/Baseflow/flutter-permission-handler/branch/master/graph/badge.svg)](https://codecov.io/gh/Baseflow/flutter-permission-handler)
On most operating systems, permissions aren't just granted to apps at install time.
Rather, developers have to ask the user for permission while the app is running.
This plugin provides a cross-platform (iOS, Android) API to request permissions and check their status.
You can also open the device's app settings so users can grant permission.
On Android, you can show a rationale for requesting permission.
See the [FAQ](#faq) section for more information on common questions when using the permission_handler plugin.
## Setup
While the permissions are being requested during runtime, you'll still need to tell the OS which permissions your app might potentially use. That requires adding permission configuration to Android* and iOS-specific files.
<details>
<summary>Android (click to expand)</summary>
**Upgrade pre-1.12 Android projects**
Since version 4.4.0 this plugin is implemented using the Flutter 1.12 Android plugin APIs. Unfortunately, this means App developers also need to migrate their Apps to support the new Android infrastructure. You can do so by following the [Upgrading pre 1.12 Android projects](https://github.com/flutter/flutter/wiki/Upgrading-pre-1.12-Android-projects) migration guide. Failing to do so might result in unexpected behavior. The most common known error is the permission_handler not returning after calling the `.request()` method on permission.
**AndroidX**
As of version 3.1.0, the <kbd>permission_handler</kbd> plugin switched to the AndroidX version of the Android Support Libraries. This means you need to make sure your Android project is also upgraded to support AndroidX. Detailed instructions can be found [here](https://flutter.dev/docs/development/packages-and-plugins/androidx-compatibility).
The TL;DR version is:
1. Add the following to your "gradle.properties" file:
```properties
android.useAndroidX=true
android.enableJetifier=true
```
2. Make sure you set the `compileSdkVersion` in your "android/app/build.gradle" file to 33:
```gradle
android {
compileSdkVersion 33
...
}
```
3. Make sure you replace all the `android.` dependencies to their AndroidX counterparts (a full list can be found [here](https://developer.android.com/jetpack/androidx/migrate)).
Add permissions to your `AndroidManifest.xml` file.
There are `debug`, `main`, and `profile` versions which are chosen depending on how you start your app.
In general, it's sufficient to add permission only to the `main` version.
[Here](https://github.com/Baseflow/flutter-permission-handler/blob/master/permission_handler/example/android/app/src/main/AndroidManifest.xml)'s an example `AndroidManifest.xml` with a complete list of all possible permissions.
</details>
<details>
<summary>iOS (click to expand)</summary>
Add permission to your `Info.plist` file.
[Here](https://github.com/Baseflow/flutter-permission-handler/blob/master/permission_handler/example/ios/Runner/Info.plist)'s an example `Info.plist` with a complete list of all possible permissions.
> IMPORTANT: ~~You will have to include all permission options when you want to submit your App.~~ This is because the `permission_handler` plugin touches all different SDKs and because the static code analyzer (run by Apple upon App submission) detects this and will assert if it cannot find a matching permission option in the `Info.plist`. More information about this can be found [here](https://github.com/Baseflow/flutter-permission-handler/issues/26).
The <kbd>permission_handler</kbd> plugin use [macros](https://github.com/Baseflow/flutter-permission-handler/blob/master/permission_handler_apple/ios/Classes/PermissionHandlerEnums.h) to control whether a permission is enabled.
You must list the permission you want to use in your application:
1. Add the following to your `Podfile` file:
```ruby
post_install do |installer|
installer.pods_project.targets.each do |target|
flutter_additional_ios_build_settings(target)
target.build_configurations.each do |config|
# You can remove unused permissions here
# for more information: https://github.com/BaseflowIT/flutter-permission-handler/blob/master/permission_handler/ios/Classes/PermissionHandlerEnums.h
# e.g. when you don't need camera permission, just add 'PERMISSION_CAMERA=0'
config.build_settings['GCC_PREPROCESSOR_DEFINITIONS'] ||= [
'$(inherited)',
## dart: PermissionGroup.calendar
'PERMISSION_EVENTS=1',
## dart: PermissionGroup.calendarFullAccess
'PERMISSION_EVENTS_FULL_ACCESS=1',
## dart: PermissionGroup.reminders
'PERMISSION_REMINDERS=1',
## dart: PermissionGroup.contacts
'PERMISSION_CONTACTS=1',
## dart: PermissionGroup.camera
'PERMISSION_CAMERA=1',
## dart: PermissionGroup.microphone
'PERMISSION_MICROPHONE=1',
## dart: PermissionGroup.speech
'PERMISSION_SPEECH_RECOGNIZER=1',
## dart: PermissionGroup.photos
'PERMISSION_PHOTOS=1',
## The 'PERMISSION_LOCATION' macro enables the `locationWhenInUse` and `locationAlways` permission. If
## the application only requires `locationWhenInUse`, only specify the `PERMISSION_LOCATION_WHENINUSE`
## macro.
##
## dart: [PermissionGroup.location, PermissionGroup.locationAlways, PermissionGroup.locationWhenInUse]
'PERMISSION_LOCATION=1',
'PERMISSION_LOCATION_WHENINUSE=0',
## dart: PermissionGroup.notification
'PERMISSION_NOTIFICATIONS=1',
## dart: PermissionGroup.mediaLibrary
'PERMISSION_MEDIA_LIBRARY=1',
## dart: PermissionGroup.sensors
'PERMISSION_SENSORS=1',
## dart: PermissionGroup.bluetooth
'PERMISSION_BLUETOOTH=1',
## dart: PermissionGroup.appTrackingTransparency
'PERMISSION_APP_TRACKING_TRANSPARENCY=1',
## dart: PermissionGroup.criticalAlerts
'PERMISSION_CRITICAL_ALERTS=1',
## dart: PermissionGroup.criticalAlerts
'PERMISSION_ASSISTANT=1',
]
end
end
end
```
2. Remove the `#` character in front of the permission you want to use. For example, if you need access to the calendar make sure the code looks like this:
```ruby
## dart: PermissionGroup.calendar
'PERMISSION_EVENTS=1',
```
3. Delete the corresponding permission description in `Info.plist`
e.g. when you don't need camera permission, just delete 'NSCameraUsageDescription'
The following lists the relationship between `Permission` and `The key of Info.plist`:
| Permission | Info.plist | Macro |
|---------------------------------------------------------------------------------------------| ------------------------------------------------------------------------------------------------------------- | ------------------------------------ |
| PermissionGroup.calendar (< iOS 17) | NSCalendarsUsageDescription | PERMISSION_EVENTS |
| PermissionGroup.calendarWriteOnly (iOS 17+) | NSCalendarsWriteOnlyAccessUsageDescription | PERMISSION_EVENTS |
| PermissionGroup.calendarFullAccess (iOS 17+) | NSCalendarsFullAccessUsageDescription | PERMISSION_EVENTS_FULL_ACCESS |
| PermissionGroup.reminders | NSRemindersUsageDescription | PERMISSION_REMINDERS |
| PermissionGroup.contacts | NSContactsUsageDescription | PERMISSION_CONTACTS |
| PermissionGroup.camera | NSCameraUsageDescription | PERMISSION_CAMERA |
| PermissionGroup.microphone | NSMicrophoneUsageDescription | PERMISSION_MICROPHONE |
| PermissionGroup.speech | NSSpeechRecognitionUsageDescription | PERMISSION_SPEECH_RECOGNIZER |
| PermissionGroup.photos | NSPhotoLibraryUsageDescription | PERMISSION_PHOTOS |
| PermissionGroup.photosAddOnly | NSPhotoLibraryAddUsageDescription | PERMISSION_PHOTOS_ADD_ONLY |
| PermissionGroup.location, PermissionGroup.locationAlways, PermissionGroup.locationWhenInUse | NSLocationUsageDescription, NSLocationAlwaysAndWhenInUseUsageDescription, NSLocationWhenInUseUsageDescription | PERMISSION_LOCATION |
| PermissionGroup.locationWhenInUse | NSLocationWhenInUseUsageDescription | PERMISSION_LOCATION_WHENINUSE |
| PermissionGroup.notification | PermissionGroupNotification | PERMISSION_NOTIFICATIONS |
| PermissionGroup.mediaLibrary | NSAppleMusicUsageDescription, kTCCServiceMedia |
PERMISSION_MEDIA_LIBRARY |
4. Clean & Rebuild
</details>
## How to use
There are a number of [`Permission`](https://pub.dev/documentation/permission_handler_platform_interface/latest/permission_handler_platform_interface/Permission-class.html#constants)s.
You can get a `Permission`'s `status`, which is either `granted`, `denied`, `restricted`, `permanentlyDenied`, `limited`, or `provisional`.
```dart
var status = await Permission.camera.status;
if (status.isDenied) {
// We haven't asked for permission yet or the permission has been denied before, but not permanently.
}
// You can also directly ask permission about its status.
if (await Permission.location.isRestricted) {
// The OS restricts access, for example, because of parental controls.
}
```
Can use also this style for better readability of your code when using the `Permission` class.
```dart
await Permission.camera
.onDeniedCallback(() {
// Your code
})
.onGrantedCallback(() {
// Your code
})
.onPermanentlyDeniedCallback(() {
// Your code
})
.onRestrictedCallback(() {
// Your code
})
.onLimitedCallback(() {
// Your code
})
.onProvisionalCallback(() {
// Your code
})
.request();
```
Call `request()` on a `Permission` to request it.
If it has already been granted before, nothing happens.
`request()` returns the new status of the `Permission`.
```dart
if (await Permission.contacts.request().isGranted) {
// Either the permission was already granted before or the user just granted it.
}
// You can request multiple permissions at once.
Map<Permission, PermissionStatus> statuses = await [
Permission.location,
Permission.storage,
].request();
print(statuses[Permission.location]);
```
Some permissions, for example, location or acceleration sensor permissions, have an associated service, which can be `enabled` or `disabled`.
```dart
if (await Permission.locationWhenInUse.serviceStatus.isEnabled) {
// Use location.
}
```
You can also open the app settings:
```dart
if (await Permission.speech.isPermanentlyDenied) {
// The user opted to never again see the permission request dialog for this
// app. The only way to change the permission's status now is to let the
// user manually enables it in the system settings.
openAppSettings();
}
```
On Android, you can show a rationale for using permission:
```dart
bool isShown = await Permission.contacts.shouldShowRequestRationale;
```
Some permissions will not show a dialog asking the user to allow or deny the requested permission.
This is because the OS setting(s) of the app are being retrieved for the corresponding permission.
The status of the setting will determine whether the permission is `granted` or `denied`.
The following permissions will show no dialog:
- Notification
- Bluetooth
The following permissions will show no dialog, but will open the corresponding setting intent for the user to change the permission status:
- manageExternalStorage
- systemAlertWindow
- requestInstallPackages
- accessNotificationPolicy
The `locationAlways` permission can not be requested directly, the user has to request the `locationWhenInUse` permission first.
Accepting this permission by clicking on the 'Allow While Using App' gives the user the possibility to request the `locationAlways` permission.
This will then bring up another permission popup asking you to `Keep Only While Using` or to `Change To Always Allow`.
## FAQ
### Requesting "storage" permissions always returns "denied" on Android 13+. What can I do?
On Android, the `Permission.storage` permission is linked to the Android `READ_EXTERNAL_STORAGE` and `WRITE_EXTERNAL_STORAGE` permissions. Starting from Android 10 (API 29) the `READ_EXTERNAL_STORAGE` and `WRITE_EXTERNAL_STORAGE` permissions have been marked deprecated and have been fully removed/disabled since Android 13 (API 33).
If your application needs access to media files Google recommends using the `READ_MEDIA_IMAGES`, `READ_MEDIA_VIDEO`, or `READ_MEDIA_AUDIO` permissions instead. These can be requested using the `Permission.photos`, `Permission.videos`, and `Permission.audio` respectively. To request these permissions make sure the `compileSdkVersion` in the `android/app/build.gradle` file is set to `33`.
If your application needs access to Android's file system, it is possible to request the `MANAGE_EXTERNAL_STORAGE` permission (using `Permission.manageExternalStorage`). As of Android 11 (API 30), the `MANAGE_EXTERNAL_STORAGE` permission is considered a high-risk or sensitive permission. Therefore it is required to [declare the use of these permissions](https://support.google.com/googleplay/android-developer/answer/9214102) if you intend to release the application via the Google Play Store.
### Requesting `Permission.locationAlways` always returns "denied" on Android 10+ (API 29+). What can I do?
Starting with Android 10, apps are required to first obtain permission to read the device's location in the foreground, before requesting to read the location in the background as well. When requesting the 'location always' permission directly, or when requesting both permissions at the same time, the system will ignore the request. So, instead of calling only `Permission.location.request()`, make sure to first call either `Permission.location.request()` or `Permission.locationWhenInUse.request()`, and obtain permission to read the GPS. Once you obtain this permission, you can call `Permission.locationAlways.request()`. This will present the user with the option to update the settings so the location can always be read in the background. For more information, visit the [Android documentation on requesting location permissions](https://developer.android.com/training/location/permissions#request-only-foreground).
### Checking or requesting a permission terminates the application on iOS. What can I do?
First of all make sure all that the `ios/Runner/Info.plist` file contains entries for all the permissions the application requires. If an entry is missing iOS will terminate the application as soon as the particular permission is being checked or requested.
If the application requires access to SiriKit (by requesting the `Permission.assistant` permission), also make sure to add the `com.apple.developer.siri` entitlement to the application configuration. To do so create a file (if it doesn't exists already) called `Runner.entitlements` in the `ios/Runner` folder that is part of the project. Open the file and add the following contents:
```xml
<?xml version="1.0" encoding="UTF-8"?>
<!DOCTYPE plist PUBLIC "-//Apple//DTD PLIST 1.0//EN" "http://www.apple.com/DTDs/PropertyList-1.0.dtd">
<plist version="1.0">
<dict>
<key>com.apple.developer.siri</key>
<true/>
</dict>
</plist>
```
The important part here is the `key` with value `com.apple.developer.siri` and the element `<true/>`. It is possible that this file also contains other entitlements depending on the needs of the application.
## Issues
Please file any issues, bugs, or feature requests as an issue on our [GitHub](https://github.com/Baseflow/flutter-permission-handler/issues) page. Commercial support is available if you need help with integration with your app or services. You can contact us at [hello@baseflow.com](mailto:hello@baseflow.com).
## Want to contribute
If you would like to contribute to the plugin (e.g. by improving the documentation, solving a bug, or adding a cool new feature), please carefully review our [contribution guide](../CONTRIBUTING.md) and send us your [pull request](https://github.com/Baseflow/flutter-permission-handler/pulls).
## Author
This Permission handler plugin for Flutter is developed by [Baseflow](https://baseflow.com). You can contact us at <hello@baseflow.com>
# Below is a list of people and organizations that have contributed
# to the Flutter project. Names should be added to the list like so:
#
# Name/Organization <email address>
Baseflow <hello@baseflow.com>
Maurits van Beusekom <maurits@baseflow.com>
\ No newline at end of file
## 12.0.7
* Removes additional Android v1 embedding class reference.
## 12.0.6
* Removes deprecated support for Android V1 embedding as support will be removed from Flutter (see [flutter/flutter#144726](https://github.com/flutter/flutter/pull/144726)).
## 12.0.5
* Upgrades Gradle and Android Gradle plugin.
## 12.0.4
* Returns `granted` on permission `Permission.scheduleExactAlarm` for devices running lower than Android S (API 31), before this change the default return was `denied`.
* Updates `minSdkVersion` version to `flutter.minSdkVersion`.
## 12.0.3
* Updates the dependency on `permission_handler_platform_interface` to version 4.1.0 (SiriKit support is only available for iOS or macOS).
## 12.0.2
* Fixes bug where Android activity is leaked when embedded in native Android application.
## 12.0.1
* Fixes a bug where the `ignoreBatteryOptimizations` permission didn't report the correct status when the permission is requested and granted.
## 12.0.0
* **BREAKING CHANGES:**
* Adds `Permission.calendarWriteOnly`.
* Removes `Permission.calendarReadOnly`.
## 11.1.0
* Implements the `Permission.calendarReadOnly` and `PermissionCalendarFullAccess` permissions.
## 11.0.5
* Removes the obsolete `updatePermissionShouldShowStatus` method from the Java code base.
* Fixes some analysis warnings in the Java code base.
## 11.0.4
* Fixes a bug where the status of special permissions would incorrectly be reported as `denied`.
## 11.0.3
* Fixes a bug where `Permission.notification.status` would never return `permanentlyDenied` on Android.
## 11.0.2
* Fixes a bug where `Permission.Phone` would always return 'denied' when requesting the permission status.
* Fixes a bug where Flutter permissions that require multiple Android permissions would base their status on the status of the first Android permission, as opposed to the result of all relevant Android permissions.
## 11.0.1
* Fixes `java.lang.IllegalStateException: Reply already submitted` when requesting post notification permission.
## 11.0.0
* **BREAKING CHANGE:** Fixes a bug where the permission status would return 'denied' regardless of whether the status was 'denied' or 'permanently denied'.
## 10.3.6
* Fixes a bug where requesting multiple permissions would crash the app if at least one of the permissions was a [special permission](https://developer.android.com/guide/topics/permissions/overview#special).
## 10.3.5
* Fixes a bug where `Permission.ScheduleExactAlarm` was not opening the settings
screen.
## 10.3.4
* Fixes a bug where the permission status would return 'permanently denied'
instead of 'denied' when the user dismisses the permission dialog.
## 10.3.3
* Migrates the Gradle compile arguments to the example app, so they are not enforced upon consumers of the plugin.
## 10.3.2
* Updates example app to show `Permission.photos` and hide `Permission.bluetooth`.
## 10.3.1
* Fixes `java.lang.IllegalStateException: Reply already submitted` when checking the status of Bluetooth service.
## 10.3.0
* Adds support for the new Android 13 permission: BODY_SENSORS_BACKGROUND.
## 10.2.3
* Fix missing POST_NOTIFICATIONS permission in the Android example project.
## 10.2.2
* Fixes the SCHEDULE_EXACT_ALARM status check on Android 12 and 13.
## 10.2.1
* Adds compatibility with Android Gradle Plugin 8.0.
## 10.2.0
* Adds support for the new Android 13 permissions: SCHEDULE_EXACT_ALARM, READ_MEDIA_IMAGES, READ_MEDIA_VIDEO and READ_MEDIA_AUDIO
## 10.1.0
* Adds support for the new Android 13 permission: NEARBY_WIFI_DEVICES.
## 10.0.0
* **BREAKING CHANGE**: Updates Android `compileSdkVersion` to `33` to handle the new `POST_NOTIFICATIONS` permission.
> When updating to version 10.0.0 make sure to update the `android/app/build.gradle` file and set the `compileSdkVersion` to `33`.
## 9.0.2+1
* Undoes PR [#765](https://github.com/baseflow/flutter-permission-handler/pull/765) which by mistake requests write_external_storage permission based on the target SDK instead of the actual SDK of the Android device.
## 9.0.2
* Moves Android implementation into its own package.
MIT License
Copyright (c) 2018 Baseflow
Permission is hereby granted, free of charge, to any person obtaining a copy
of this software and associated documentation files (the "Software"), to deal
in the Software without restriction, including without limitation the rights
to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
copies of the Software, and to permit persons to whom the Software is
furnished to do so, subject to the following conditions:
The above copyright notice and this permission notice shall be included in all
copies or substantial portions of the Software.
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
SOFTWARE.
# permission_handler_android
[![pub package](https://img.shields.io/pub/v/permission_handler_android.svg)](https://pub.dartlang.org/packages/permission_handler_android) ![Build status](https://github.com/Baseflow/flutter-permission-handler/workflows/permission_handler_android/badge.svg?branch=master) [![style: flutter lints](https://img.shields.io/badge/style-flutter_lints-40c4ff.svg)](https://pub.dev/packages/flutter_lints)
The official Android implementation of the [permission_handler](https://pub.dev/packages/permission_handler) plugin by [Baseflow](https://baseflow.com).
## Usage
Since version 9.1.0 of the [permission_handler](https://pub.dev/packages/permission_handler) plugin this is the endorsed Android implementation. This means it will automatically be added to your dependencies when you depend on `permission_handler: ^9.1.0` in your applications pubspec.yaml.
More detailed instructions on using the API can be found in the [README.md](../permission_handler/README.md) of the [permission_handler](https://pub.dev/packages/permission_handler) package.
## Issues
Please file any issues, bugs, or feature requests as an issue on our [GitHub](https://github.com/Baseflow/flutter-permission-handler/issues) page. Commercial support is available, you can contact us at <hello@baseflow.com>.
## Want to contribute
If you would like to contribute to the plugin (e.g. by improving the documentation, solving a bug, or adding a cool new feature), please carefully review our [contribution guide](../CONTRIBUTING.md) and send us your [pull request](https://github.com/Baseflow/flutter-permission-handler/pulls).
## Author
This permission_handler plugin for Flutter is developed by [Baseflow](https://baseflow.com).
<?xml version="1.0" encoding="UTF-8"?>
<classpath>
<classpathentry kind="con" path="org.eclipse.jdt.launching.JRE_CONTAINER/org.eclipse.jdt.internal.debug.ui.launcher.StandardVMType/JavaSE-11/"/>
<classpathentry kind="con" path="org.eclipse.buildship.core.gradleclasspathcontainer"/>
<classpathentry kind="output" path="bin/default"/>
</classpath>
*.iml
.gradle
/local.properties
/.idea/workspace.xml
/.idea/libraries
.DS_Store
/build
/captures
arguments=
auto.sync=false
build.scans.enabled=false
connection.gradle.distribution=GRADLE_DISTRIBUTION(VERSION(7.1.1))
connection.project.dir=
eclipse.preferences.version=1
gradle.user.home=
java.home=/Library/Java/JavaVirtualMachines/adoptopenjdk-11.jdk/Contents/Home
jvm.arguments=
offline.mode=false
override.workspace.settings=true
show.console.view=true
show.executions.view=true
group 'com.baseflow.permissionhandler'
version '1.0'
buildscript {
repositories {
google()
mavenCentral()
}
dependencies {
classpath 'com.android.tools.build:gradle:8.0.0'
}
}
rootProject.allprojects {
repositories {
google()
mavenCentral()
}
}
apply plugin: 'com.android.library'
android {
// Conditional for compatibility with AGP <4.2.
if (project.android.hasProperty("namespace")) {
namespace 'com.baseflow.permissionhandler'
}
compileSdk 33
compileOptions {
sourceCompatibility JavaVersion.VERSION_1_8
targetCompatibility JavaVersion.VERSION_1_8
}
defaultConfig {
minSdkVersion 16
}
}
distributionBase=GRADLE_USER_HOME
distributionPath=wrapper/dists
distributionUrl=https\://services.gradle.org/distributions/gradle-6.8-bin.zip
zipStoreBase=GRADLE_USER_HOME
zipStorePath=wrapper/dists
<manifest xmlns:android="http://schemas.android.com/apk/res/android"
package="com.baseflow.permissionhandler">
</manifest>
package com.baseflow.permissionhandler;
import android.content.Context;
import android.content.Intent;
import android.util.Log;
final class AppSettingsManager {
@FunctionalInterface
interface OpenAppSettingsSuccessCallback {
void onSuccess(boolean appSettingsOpenedSuccessfully);
}
void openAppSettings(
Context context,
OpenAppSettingsSuccessCallback successCallback,
ErrorCallback errorCallback) {
if(context == null) {
Log.d(PermissionConstants.LOG_TAG, "Context cannot be null.");
errorCallback.onError("PermissionHandler.AppSettingsManager", "Android context cannot be null.");
return;
}
try {
Intent settingsIntent = new Intent();
settingsIntent.setAction(android.provider.Settings.ACTION_APPLICATION_DETAILS_SETTINGS);
settingsIntent.addCategory(Intent.CATEGORY_DEFAULT);
settingsIntent.setData(android.net.Uri.parse("package:" + context.getPackageName()));
settingsIntent.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
settingsIntent.addFlags(Intent.FLAG_ACTIVITY_NO_HISTORY);
settingsIntent.addFlags(Intent.FLAG_ACTIVITY_EXCLUDE_FROM_RECENTS);
context.startActivity(settingsIntent);
successCallback.onSuccess(true);
} catch (Exception ex) {
successCallback.onSuccess(false);
}
}
}
package com.baseflow.permissionhandler;
@FunctionalInterface
interface ErrorCallback {
void onError(String errorCode, String errorDescription);
}
package com.baseflow.permissionhandler;
import android.content.Context;
import androidx.annotation.NonNull;
import io.flutter.plugin.common.MethodCall;
import io.flutter.plugin.common.MethodChannel;
import io.flutter.plugin.common.MethodChannel.Result;
import java.util.List;
final class MethodCallHandlerImpl implements MethodChannel.MethodCallHandler {
private final Context applicationContext;
private final AppSettingsManager appSettingsManager;
private final PermissionManager permissionManager;
private final ServiceManager serviceManager;
MethodCallHandlerImpl(
Context applicationContext,
AppSettingsManager appSettingsManager,
PermissionManager permissionManager,
ServiceManager serviceManager) {
this.applicationContext = applicationContext;
this.appSettingsManager = appSettingsManager;
this.permissionManager = permissionManager;
this.serviceManager = serviceManager;
}
@Override
public void onMethodCall(@NonNull MethodCall call, @NonNull final Result result) {
switch (call.method) {
case "checkServiceStatus": {
@PermissionConstants.PermissionGroup final int permission = Integer.parseInt(call.arguments.toString());
serviceManager.checkServiceStatus(
permission,
applicationContext,
result::success,
(String errorCode, String errorDescription) -> result.error(
errorCode,
errorDescription,
null));
break;
}
case "checkPermissionStatus": {
@PermissionConstants.PermissionGroup final int permission = Integer.parseInt(call.arguments.toString());
permissionManager.checkPermissionStatus(
permission,
result::success);
break;
}
case "requestPermissions":
final List<Integer> permissions = call.arguments();
permissionManager.requestPermissions(
permissions,
result::success,
(String errorCode, String errorDescription) -> result.error(
errorCode,
errorDescription,
null));
break;
case "shouldShowRequestPermissionRationale": {
@PermissionConstants.PermissionGroup final int permission = Integer.parseInt(call.arguments.toString());
permissionManager.shouldShowRequestPermissionRationale(
permission,
result::success,
(String errorCode, String errorDescription) -> result.error(
errorCode,
errorDescription,
null));
break;
}
case "openAppSettings":
appSettingsManager.openAppSettings(
applicationContext,
result::success,
(String errorCode, String errorDescription) -> result.error(
errorCode,
errorDescription,
null));
break;
default:
result.notImplemented();
break;
}
}
}
package com.baseflow.permissionhandler;
import androidx.annotation.IntDef;
import java.lang.annotation.ElementType;
import java.lang.annotation.Retention;
import java.lang.annotation.RetentionPolicy;
import java.lang.annotation.Target;
final class PermissionConstants {
static final String LOG_TAG = "permissions_handler";
static final int PERMISSION_CODE = 24;
static final int PERMISSION_CODE_IGNORE_BATTERY_OPTIMIZATIONS = 209;
static final int PERMISSION_CODE_MANAGE_EXTERNAL_STORAGE = 210;
static final int PERMISSION_CODE_SYSTEM_ALERT_WINDOW = 211;
static final int PERMISSION_CODE_REQUEST_INSTALL_PACKAGES = 212;
static final int PERMISSION_CODE_ACCESS_NOTIFICATION_POLICY = 213;
static final int PERMISSION_CODE_SCHEDULE_EXACT_ALARM = 214;
// PERMISSION_GROUP
// Deprecated in favor of PERMISSION_GROUP_CALENDAR_WRITE_ONLY and
// PERMISSION_GROUP_CALENDAR_FULL_ACCESS.
static final int PERMISSION_GROUP_CALENDAR = 0;
static final int PERMISSION_GROUP_CAMERA = 1;
static final int PERMISSION_GROUP_CONTACTS = 2;
static final int PERMISSION_GROUP_LOCATION = 3;
static final int PERMISSION_GROUP_LOCATION_ALWAYS = 4;
static final int PERMISSION_GROUP_LOCATION_WHEN_IN_USE = 5;
static final int PERMISSION_GROUP_MEDIA_LIBRARY = 6;
static final int PERMISSION_GROUP_MICROPHONE = 7;
static final int PERMISSION_GROUP_PHONE = 8;
static final int PERMISSION_GROUP_PHOTOS = 9;
static final int PERMISSION_GROUP_PHOTOS_ADD_ONLY = 10;
static final int PERMISSION_GROUP_REMINDERS = 11;
static final int PERMISSION_GROUP_SENSORS = 12;
static final int PERMISSION_GROUP_SMS = 13;
static final int PERMISSION_GROUP_SPEECH = 14;
static final int PERMISSION_GROUP_STORAGE = 15;
static final int PERMISSION_GROUP_IGNORE_BATTERY_OPTIMIZATIONS = 16;
static final int PERMISSION_GROUP_NOTIFICATION = 17;
static final int PERMISSION_GROUP_ACCESS_MEDIA_LOCATION = 18;
static final int PERMISSION_GROUP_ACTIVITY_RECOGNITION = 19;
static final int PERMISSION_GROUP_UNKNOWN = 20;
static final int PERMISSION_GROUP_BLUETOOTH = 21;
static final int PERMISSION_GROUP_MANAGE_EXTERNAL_STORAGE = 22;
static final int PERMISSION_GROUP_SYSTEM_ALERT_WINDOW = 23;
static final int PERMISSION_GROUP_REQUEST_INSTALL_PACKAGES = 24;
static final int PERMISSION_GROUP_APP_TRACK_TRANSPARENCY = 25;
static final int PERMISSION_GROUP_CRITICAL_ALERTS = 26;
static final int PERMISSION_GROUP_ACCESS_NOTIFICATION_POLICY = 27;
static final int PERMISSION_GROUP_BLUETOOTH_SCAN = 28;
static final int PERMISSION_GROUP_BLUETOOTH_ADVERTISE = 29;
static final int PERMISSION_GROUP_BLUETOOTH_CONNECT = 30;
static final int PERMISSION_GROUP_NEARBY_WIFI_DEVICES = 31;
static final int PERMISSION_GROUP_VIDEOS = 32;
static final int PERMISSION_GROUP_AUDIO = 33;
static final int PERMISSION_GROUP_SCHEDULE_EXACT_ALARM = 34;
static final int PERMISSION_GROUP_SENSORS_ALWAYS = 35;
static final int PERMISSION_GROUP_CALENDAR_WRITE_ONLY = 36;
static final int PERMISSION_GROUP_CALENDAR_FULL_ACCESS = 37;
static final int PERMISSION_GROUP_ASSISTANT = 38;
static final int PERMISSION_GROUP_BACKGROUND_REFRESH = 39;
@Retention(RetentionPolicy.SOURCE)
@IntDef({
PERMISSION_GROUP_CALENDAR,
PERMISSION_GROUP_CAMERA,
PERMISSION_GROUP_CONTACTS,
PERMISSION_GROUP_LOCATION,
PERMISSION_GROUP_LOCATION_ALWAYS,
PERMISSION_GROUP_LOCATION_WHEN_IN_USE,
PERMISSION_GROUP_MEDIA_LIBRARY,
PERMISSION_GROUP_MICROPHONE,
PERMISSION_GROUP_PHONE,
PERMISSION_GROUP_PHOTOS,
PERMISSION_GROUP_REMINDERS,
PERMISSION_GROUP_SENSORS,
PERMISSION_GROUP_SENSORS_ALWAYS,
PERMISSION_GROUP_SMS,
PERMISSION_GROUP_SPEECH,
PERMISSION_GROUP_STORAGE,
PERMISSION_GROUP_IGNORE_BATTERY_OPTIMIZATIONS,
PERMISSION_GROUP_NOTIFICATION,
PERMISSION_GROUP_ACCESS_MEDIA_LOCATION,
PERMISSION_GROUP_ACTIVITY_RECOGNITION,
PERMISSION_GROUP_UNKNOWN,
PERMISSION_GROUP_BLUETOOTH,
PERMISSION_GROUP_MANAGE_EXTERNAL_STORAGE,
PERMISSION_GROUP_SYSTEM_ALERT_WINDOW,
PERMISSION_GROUP_REQUEST_INSTALL_PACKAGES,
PERMISSION_GROUP_ACCESS_NOTIFICATION_POLICY,
PERMISSION_GROUP_BLUETOOTH_SCAN,
PERMISSION_GROUP_BLUETOOTH_ADVERTISE,
PERMISSION_GROUP_BLUETOOTH_CONNECT,
PERMISSION_GROUP_NEARBY_WIFI_DEVICES,
PERMISSION_GROUP_VIDEOS,
PERMISSION_GROUP_AUDIO,
PERMISSION_GROUP_SCHEDULE_EXACT_ALARM,
PERMISSION_GROUP_CALENDAR_WRITE_ONLY,
PERMISSION_GROUP_CALENDAR_FULL_ACCESS,
PERMISSION_GROUP_ASSISTANT
})
@interface PermissionGroup {
}
//PERMISSION_STATUS
static final int PERMISSION_STATUS_DENIED = 0;
static final int PERMISSION_STATUS_GRANTED = 1;
static final int PERMISSION_STATUS_RESTRICTED = 2;
static final int PERMISSION_STATUS_LIMITED = 3;
static final int PERMISSION_STATUS_NEVER_ASK_AGAIN = 4;
@Target(ElementType.TYPE_USE)
@Retention(RetentionPolicy.SOURCE)
@IntDef({
PERMISSION_STATUS_DENIED,
PERMISSION_STATUS_GRANTED,
PERMISSION_STATUS_RESTRICTED,
PERMISSION_STATUS_LIMITED,
PERMISSION_STATUS_NEVER_ASK_AGAIN
})
@interface PermissionStatus {
}
//SERVICE_STATUS
static final int SERVICE_STATUS_DISABLED = 0;
static final int SERVICE_STATUS_ENABLED = 1;
static final int SERVICE_STATUS_NOT_APPLICABLE = 2;
@Retention(RetentionPolicy.SOURCE)
@IntDef({
SERVICE_STATUS_DISABLED,
SERVICE_STATUS_ENABLED,
SERVICE_STATUS_NOT_APPLICABLE
})
@interface ServiceStatus {
}
}
\ No newline at end of file
package com.baseflow.permissionhandler;
import android.app.Activity;
import android.content.Context;
import androidx.annotation.NonNull;
import androidx.annotation.Nullable;
import io.flutter.embedding.engine.plugins.FlutterPlugin;
import io.flutter.embedding.engine.plugins.activity.ActivityAware;
import io.flutter.embedding.engine.plugins.activity.ActivityPluginBinding;
import io.flutter.plugin.common.BinaryMessenger;
import io.flutter.plugin.common.MethodChannel;
/**
* Platform implementation of the permission_handler Flutter plugin.
*
* <p>Instantiate this in an add-to-app scenario to gracefully handle activity and context changes.
* See {@code com.example.permissionhandlerexample.MainActivity} for an example.
*/
public final class PermissionHandlerPlugin implements FlutterPlugin, ActivityAware {
private PermissionManager permissionManager;
private MethodChannel methodChannel;
@Nullable private ActivityPluginBinding pluginBinding;
@Nullable
private MethodCallHandlerImpl methodCallHandler;
@Override
public void onAttachedToEngine(@NonNull FlutterPluginBinding binding) {
this.permissionManager = new PermissionManager(binding.getApplicationContext());
startListening(
binding.getApplicationContext(),
binding.getBinaryMessenger()
);
}
@Override
public void onDetachedFromEngine(@NonNull FlutterPluginBinding binding) {
stopListening();
}
@Override
public void onAttachedToActivity(@NonNull ActivityPluginBinding binding) {
startListeningToActivity(
binding.getActivity()
);
pluginBinding = binding;
registerListeners();
}
@Override
public void onReattachedToActivityForConfigChanges(@NonNull ActivityPluginBinding binding) {
onAttachedToActivity(binding);
}
@Override
public void onDetachedFromActivity() {
stopListeningToActivity();
deregisterListeners();
pluginBinding = null;
}
@Override
public void onDetachedFromActivityForConfigChanges() {
onDetachedFromActivity();
}
private void startListening(Context applicationContext, BinaryMessenger messenger) {
methodChannel = new MethodChannel(
messenger,
"flutter.baseflow.com/permissions/methods");
methodCallHandler = new MethodCallHandlerImpl(
applicationContext,
new AppSettingsManager(),
this.permissionManager,
new ServiceManager()
);
methodChannel.setMethodCallHandler(methodCallHandler);
}
private void stopListening() {
methodChannel.setMethodCallHandler(null);
methodChannel = null;
methodCallHandler = null;
}
private void startListeningToActivity(
Activity activity
) {
if (permissionManager != null) {
permissionManager.setActivity(activity);
}
}
private void stopListeningToActivity() {
if (permissionManager != null) {
permissionManager.setActivity(null);
}
}
private void registerListeners() {
if (pluginBinding != null) {
this.pluginBinding.addActivityResultListener(this.permissionManager);
this.pluginBinding.addRequestPermissionsResultListener(this.permissionManager);
}
}
private void deregisterListeners() {
if (this.pluginBinding != null) {
this.pluginBinding.removeActivityResultListener(this.permissionManager);
this.pluginBinding.removeRequestPermissionsResultListener(this.permissionManager);
}
}
}
package com.baseflow.permissionhandler;
import static com.baseflow.permissionhandler.PermissionUtils.strictestStatus;
import android.Manifest;
import android.app.Activity;
import android.app.AlarmManager;
import android.app.Application;
import android.app.NotificationManager;
import android.content.Context;
import android.content.Intent;
import android.content.pm.PackageManager;
import android.net.Uri;
import android.os.Build;
import android.os.Environment;
import android.os.PowerManager;
import android.provider.Settings;
import android.util.Log;
import androidx.annotation.NonNull;
import androidx.annotation.Nullable;
import androidx.core.app.ActivityCompat;
import androidx.core.app.NotificationManagerCompat;
import androidx.core.content.ContextCompat;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.HashMap;
import java.util.HashSet;
import java.util.List;
import java.util.Map;
import java.util.Set;
import io.flutter.plugin.common.PluginRegistry;
final class PermissionManager implements PluginRegistry.ActivityResultListener, PluginRegistry.RequestPermissionsResultListener {
@NonNull
private final Context context;
@Nullable
private RequestPermissionsSuccessCallback successCallback;
@Nullable
private Activity activity;
/**
* The number of pending permission requests.
* <p>
* This number is set by {@link this#requestPermissions(List, RequestPermissionsSuccessCallback, ErrorCallback)}
* and then reduced when receiving results in {@link this#onActivityResult(int, int, Intent)}
* and {@link this#onRequestPermissionsResult(int, String[], int[])}.
*/
private int pendingRequestCount;
/**
* The results of resolved permission requests.
* <p>
* This map holds the results to resolved permission requests received through
* {@link this#onActivityResult(int, int, Intent)} and
* {@link this#onRequestPermissionsResult(int, String[], int[])}.
* It is (re)initialized when new permissions are requested through
* {@link this#requestPermissions(List, RequestPermissionsSuccessCallback, ErrorCallback)}.
*/
private Map<Integer, Integer> requestResults;
public PermissionManager(@NonNull Context context) {
this.context = context;
}
public void setActivity(@Nullable Activity activity) {
this.activity = activity;
}
@Override
public boolean onActivityResult(int requestCode, int resultCode, Intent data) {
if (activity == null) {
return false;
}
int status, permission;
if (requestCode == PermissionConstants.PERMISSION_CODE_IGNORE_BATTERY_OPTIMIZATIONS) {
permission = PermissionConstants.PERMISSION_GROUP_IGNORE_BATTERY_OPTIMIZATIONS;
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.M) {
String packageName = context.getPackageName();
PowerManager pm = (PowerManager) context.getSystemService(Context.POWER_SERVICE);
status = (pm != null && pm.isIgnoringBatteryOptimizations(packageName))
? PermissionConstants.PERMISSION_STATUS_GRANTED
: PermissionConstants.PERMISSION_STATUS_DENIED;
} else {
status = PermissionConstants.PERMISSION_STATUS_RESTRICTED;
}
} else if (requestCode == PermissionConstants.PERMISSION_CODE_MANAGE_EXTERNAL_STORAGE) {
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.R) {
status = Environment.isExternalStorageManager()
? PermissionConstants.PERMISSION_STATUS_GRANTED
: PermissionConstants.PERMISSION_STATUS_DENIED;
} else {
return false;
}
permission = PermissionConstants.PERMISSION_GROUP_MANAGE_EXTERNAL_STORAGE;
} else if (requestCode == PermissionConstants.PERMISSION_CODE_SYSTEM_ALERT_WINDOW) {
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.M) {
status = Settings.canDrawOverlays(activity)
? PermissionConstants.PERMISSION_STATUS_GRANTED
: PermissionConstants.PERMISSION_STATUS_DENIED;
permission = PermissionConstants.PERMISSION_GROUP_SYSTEM_ALERT_WINDOW;
} else {
return false;
}
} else if (requestCode == PermissionConstants.PERMISSION_CODE_REQUEST_INSTALL_PACKAGES) {
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.O) {
status = activity.getPackageManager().canRequestPackageInstalls()
? PermissionConstants.PERMISSION_STATUS_GRANTED
: PermissionConstants.PERMISSION_STATUS_DENIED;
permission = PermissionConstants.PERMISSION_GROUP_REQUEST_INSTALL_PACKAGES;
} else {
return false;
}
} else if (requestCode == PermissionConstants.PERMISSION_CODE_ACCESS_NOTIFICATION_POLICY) {
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.M) {
NotificationManager notificationManager = (NotificationManager) activity.getSystemService(Application.NOTIFICATION_SERVICE);
status = notificationManager.isNotificationPolicyAccessGranted()
? PermissionConstants.PERMISSION_STATUS_GRANTED
: PermissionConstants.PERMISSION_STATUS_DENIED;
permission = PermissionConstants.PERMISSION_GROUP_ACCESS_NOTIFICATION_POLICY;
} else {
return false;
}
} else if (requestCode == PermissionConstants.PERMISSION_CODE_SCHEDULE_EXACT_ALARM) {
permission = PermissionConstants.PERMISSION_GROUP_SCHEDULE_EXACT_ALARM;
AlarmManager alarmManager = (AlarmManager) activity.getSystemService(Context.ALARM_SERVICE);
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.S) {
status = alarmManager.canScheduleExactAlarms()
? PermissionConstants.PERMISSION_STATUS_GRANTED
: PermissionConstants.PERMISSION_STATUS_DENIED;
} else {
status = PermissionConstants.PERMISSION_STATUS_GRANTED;
}
} else {
return false;
}
requestResults.put(permission, status);
pendingRequestCount--;
// Post result if all requests have been handled.
if (successCallback != null && pendingRequestCount == 0) {
this.successCallback.onSuccess(requestResults);
}
return true;
}
@Override
public boolean onRequestPermissionsResult(
int requestCode,
@NonNull String[] permissions,
@NonNull int[] grantResults) {
if (requestCode != PermissionConstants.PERMISSION_CODE) {
pendingRequestCount = 0;
return false;
}
if (requestResults == null) {
return false;
}
if (permissions.length == 0 && grantResults.length == 0) {
Log.w(PermissionConstants.LOG_TAG, "onRequestPermissionsResult is called without results. This is probably caused by interfering request codes. If you see this error, please file an issue in flutter-permission-handler, including a list of plugins used by this application: https://github.com/Baseflow/flutter-permission-handler/issues");
return false;
}
// Calendar permissions are split between WRITE and READ in Android, and split between WRITE
// and FULL ACCESS in the plugin. We need special logic for this translation.
final List<String> permissionList = Arrays.asList(permissions);
final int calendarWriteIndex = permissionList.indexOf(Manifest.permission.WRITE_CALENDAR);
// WRITE -> WRITE.
if (calendarWriteIndex >= 0) {
final int writeGrantResult = grantResults[calendarWriteIndex];
final @PermissionConstants.PermissionStatus int writeStatus =
PermissionUtils.toPermissionStatus(this.activity, Manifest.permission.WRITE_CALENDAR, writeGrantResult);
requestResults.put(PermissionConstants.PERMISSION_GROUP_CALENDAR_WRITE_ONLY, writeStatus);
// WRITE + READ -> FULL ACCESS.
final int calendarReadIndex = permissionList.indexOf(Manifest.permission.READ_CALENDAR);
if (calendarReadIndex >= 0) {
final int readGrantResult = grantResults[calendarReadIndex];
final @PermissionConstants.PermissionStatus int readStatus =
PermissionUtils.toPermissionStatus(this.activity, Manifest.permission.READ_CALENDAR, readGrantResult);
final @PermissionConstants.PermissionStatus int fullAccessStatus = strictestStatus(writeStatus, readStatus);
requestResults.put(PermissionConstants.PERMISSION_GROUP_CALENDAR_FULL_ACCESS, fullAccessStatus);
// Support deprecated CALENDAR permission.
requestResults.put(PermissionConstants.PERMISSION_GROUP_CALENDAR, fullAccessStatus);
}
}
for (int i = 0; i < permissions.length; i++) {
final String permissionName = permissions[i];
// WRITE_CALENDAR and READ_CALENDAR permission results have already been handled.
if (permissionName.equals(Manifest.permission.WRITE_CALENDAR) || permissionName.equals(Manifest.permission.READ_CALENDAR)) {
continue;
}
@PermissionConstants.PermissionGroup final int permission =
PermissionUtils.parseManifestName(permissionName);
if (permission == PermissionConstants.PERMISSION_GROUP_UNKNOWN)
continue;
final int result = grantResults[i];
if (permission == PermissionConstants.PERMISSION_GROUP_PHONE) {
@Nullable @PermissionConstants.PermissionStatus Integer previousResult = requestResults.get(PermissionConstants.PERMISSION_GROUP_PHONE);
@PermissionConstants.PermissionStatus int newResult = PermissionUtils.toPermissionStatus(this.activity, permissionName, result);
@Nullable @PermissionConstants.PermissionStatus Integer strictestStatus = strictestStatus(previousResult, newResult);
requestResults.put(PermissionConstants.PERMISSION_GROUP_PHONE, strictestStatus);
} else if (permission == PermissionConstants.PERMISSION_GROUP_MICROPHONE) {
if (!requestResults.containsKey(PermissionConstants.PERMISSION_GROUP_MICROPHONE)) {
requestResults.put(
PermissionConstants.PERMISSION_GROUP_MICROPHONE,
PermissionUtils.toPermissionStatus(this.activity, permissionName, result));
}
if (!requestResults.containsKey(PermissionConstants.PERMISSION_GROUP_SPEECH)) {
requestResults.put(
PermissionConstants.PERMISSION_GROUP_SPEECH,
PermissionUtils.toPermissionStatus(this.activity, permissionName, result));
}
} else if (permission == PermissionConstants.PERMISSION_GROUP_LOCATION_ALWAYS) {
@PermissionConstants.PermissionStatus int permissionStatus =
PermissionUtils.toPermissionStatus(this.activity, permissionName, result);
if (!requestResults.containsKey(PermissionConstants.PERMISSION_GROUP_LOCATION_ALWAYS)) {
requestResults.put(PermissionConstants.PERMISSION_GROUP_LOCATION_ALWAYS, permissionStatus);
}
} else if (permission == PermissionConstants.PERMISSION_GROUP_LOCATION) {
@PermissionConstants.PermissionStatus int permissionStatus =
PermissionUtils.toPermissionStatus(this.activity, permissionName, result);
if (Build.VERSION.SDK_INT < Build.VERSION_CODES.Q) {
if (!requestResults.containsKey(PermissionConstants.PERMISSION_GROUP_LOCATION_ALWAYS)) {
requestResults.put(
PermissionConstants.PERMISSION_GROUP_LOCATION_ALWAYS,
permissionStatus);
}
}
if (!requestResults.containsKey(PermissionConstants.PERMISSION_GROUP_LOCATION_WHEN_IN_USE)) {
requestResults.put(
PermissionConstants.PERMISSION_GROUP_LOCATION_WHEN_IN_USE,
permissionStatus);
}
requestResults.put(permission, permissionStatus);
} else if (!requestResults.containsKey(permission)) {
requestResults.put(
permission,
PermissionUtils.toPermissionStatus(this.activity, permissionName, result));
}
}
pendingRequestCount -= grantResults.length;
// Post result if all requests have been handled.
if (successCallback != null && pendingRequestCount == 0) {
this.successCallback.onSuccess(requestResults);
}
return true;
}
/**
* Determines the permission status of the provided permission.
* <p>
* To distinguish between a status of 'denied' and a status of 'permanently denied', the plugin
* needs access to an activity. If `this.activity` is null, for example when running the
* application in the background, the resolved status will be 'denied' for both 'denied' and
* 'permanently denied'.
*
* @param permission the permission for which to determine the status.
* @param successCallback the callback to which the resolved status must be supplied.
*/
void checkPermissionStatus(
final @PermissionConstants.PermissionGroup int permission,
final CheckPermissionsSuccessCallback successCallback) {
successCallback.onSuccess(determinePermissionStatus(permission));
}
/**
* Requests the user for the provided permissions.
* <p>
* This method will throw an error if it is called before all permission requests that were
* requested in a previous call have been resolved.
* <p>
* Android distinguishes between
* <a href="https://developer.android.com/guide/topics/permissions/overview#runtime">runtime permissions</a>
* and
* <a href="https://developer.android.com/guide/topics/permissions/overview#special">special permissions</a>.
* Runtime permissions give an app additional access to restricted data or let the app perform
* restricted actions that more substantially affect the system and other apps. These
* permissions present the user with a dialog where they can choose to grant or deny the
* permission. Special permissions guard access to system resources that are particularly
* sensitive or not directly related to user privacy. These permissions are requested by sending
* an {@link Intent} to the OS. The OS will open a special settings page where the user can
* grant the permission.
* Runtime permission request results will be reported through
* {@link this#onRequestPermissionsResult(int, String[], int[])}, while special permissions
* request results will be reported through {@link this#onActivityResult(int, int, Intent)}.
* When these methods receive request results, they check whether all permissions that were
* requested through this method were handled, and if so, return the result back to Dart.
*
* @param permissions the permissions that are requested.
* @param successCallback the callback for returning the permission results.
* @param errorCallback the callback to call in case of an error.
*/
void requestPermissions(
List<Integer> permissions,
RequestPermissionsSuccessCallback successCallback,
ErrorCallback errorCallback) {
if (pendingRequestCount > 0) {
errorCallback.onError(
"PermissionHandler.PermissionManager",
"A request for permissions is already running, please wait for it to finish before doing another request (note that you can request multiple permissions at the same time).");
return;
}
if (activity == null) {
Log.d(PermissionConstants.LOG_TAG, "Unable to detect current Activity.");
errorCallback.onError(
"PermissionHandler.PermissionManager",
"Unable to detect current Android Activity.");
return;
}
this.successCallback = successCallback;
this.requestResults = new HashMap<>();
this.pendingRequestCount = 0; // sanity check
ArrayList<String> permissionsToRequest = new ArrayList<>();
for (Integer permission : permissions) {
@PermissionConstants.PermissionStatus final int permissionStatus = determinePermissionStatus(permission);
if (permissionStatus == PermissionConstants.PERMISSION_STATUS_GRANTED) {
if (!requestResults.containsKey(permission)) {
requestResults.put(permission, PermissionConstants.PERMISSION_STATUS_GRANTED);
}
continue;
}
final List<String> names = PermissionUtils.getManifestNames(activity, permission);
// check to see if we can find manifest names
// if we can't add as unknown and continue
if (names == null || names.isEmpty()) {
if (!requestResults.containsKey(permission)) {
// On Android below M, the android.permission.REQUEST_IGNORE_BATTERY_OPTIMIZATIONS flag in AndroidManifest.xml
// may be ignored and not visible to the App as it's a new permission setting as a whole.
if (permission == PermissionConstants.PERMISSION_GROUP_IGNORE_BATTERY_OPTIMIZATIONS && Build.VERSION.SDK_INT < Build.VERSION_CODES.M) {
requestResults.put(permission, PermissionConstants.PERMISSION_STATUS_RESTRICTED);
} else {
requestResults.put(permission, PermissionConstants.PERMISSION_STATUS_DENIED);
}
// On Android below R, the android.permission.MANAGE_EXTERNAL_STORAGE flag in AndroidManifest.xml
// may be ignored and not visible to the App as it's a new permission setting as a whole.
if (permission == PermissionConstants.PERMISSION_GROUP_MANAGE_EXTERNAL_STORAGE && Build.VERSION.SDK_INT < Build.VERSION_CODES.R) {
requestResults.put(permission, PermissionConstants.PERMISSION_STATUS_RESTRICTED);
} else {
requestResults.put(permission, PermissionConstants.PERMISSION_STATUS_DENIED);
}
}
continue;
}
// Request special permissions.
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.M && permission == PermissionConstants.PERMISSION_GROUP_IGNORE_BATTERY_OPTIMIZATIONS) {
launchSpecialPermission(
Settings.ACTION_REQUEST_IGNORE_BATTERY_OPTIMIZATIONS,
PermissionConstants.PERMISSION_CODE_IGNORE_BATTERY_OPTIMIZATIONS);
} else if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.R && permission == PermissionConstants.PERMISSION_GROUP_MANAGE_EXTERNAL_STORAGE) {
launchSpecialPermission(
Settings.ACTION_MANAGE_APP_ALL_FILES_ACCESS_PERMISSION,
PermissionConstants.PERMISSION_CODE_MANAGE_EXTERNAL_STORAGE);
} else if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.M && permission == PermissionConstants.PERMISSION_GROUP_SYSTEM_ALERT_WINDOW) {
launchSpecialPermission(
Settings.ACTION_MANAGE_OVERLAY_PERMISSION,
PermissionConstants.PERMISSION_CODE_SYSTEM_ALERT_WINDOW);
} else if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.O && permission == PermissionConstants.PERMISSION_GROUP_REQUEST_INSTALL_PACKAGES) {
launchSpecialPermission(
Settings.ACTION_MANAGE_UNKNOWN_APP_SOURCES,
PermissionConstants.PERMISSION_CODE_REQUEST_INSTALL_PACKAGES);
} else if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.M && permission == PermissionConstants.PERMISSION_GROUP_ACCESS_NOTIFICATION_POLICY) {
launchSpecialPermission(
Settings.ACTION_NOTIFICATION_POLICY_ACCESS_SETTINGS,
PermissionConstants.PERMISSION_CODE_ACCESS_NOTIFICATION_POLICY);
} else if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.S && permission == PermissionConstants.PERMISSION_GROUP_SCHEDULE_EXACT_ALARM) {
launchSpecialPermission(
Settings.ACTION_REQUEST_SCHEDULE_EXACT_ALARM,
PermissionConstants.PERMISSION_CODE_SCHEDULE_EXACT_ALARM);
} else if (permission == PermissionConstants.PERMISSION_GROUP_CALENDAR_FULL_ACCESS || permission == PermissionConstants.PERMISSION_GROUP_CALENDAR) {
// Deny CALENDAR_FULL_ACCESS permission if manifest is not listing both write- and read permissions.
final boolean isValidManifest = isValidManifestForCalendarFullAccess();
if (isValidManifest) {
permissionsToRequest.add(Manifest.permission.WRITE_CALENDAR);
permissionsToRequest.add(Manifest.permission.READ_CALENDAR);
pendingRequestCount += 2;
} else {
requestResults.put(permission, PermissionConstants.PERMISSION_STATUS_DENIED);
}
} else {
permissionsToRequest.addAll(names);
pendingRequestCount += names.size();
}
}
// Request runtime permissions.
if (permissionsToRequest.size() > 0) {
final String[] requestPermissions = permissionsToRequest.toArray(new String[0]);
ActivityCompat.requestPermissions(
activity,
requestPermissions,
PermissionConstants.PERMISSION_CODE);
}
// Post results immediately if no requests are pending.
if (this.successCallback != null && pendingRequestCount == 0) {
this.successCallback.onSuccess(requestResults);
}
}
@PermissionConstants.PermissionStatus
private int determinePermissionStatus(final @PermissionConstants.PermissionGroup int permission) {
if (permission == PermissionConstants.PERMISSION_GROUP_NOTIFICATION) {
return checkNotificationPermissionStatus();
}
if (permission == PermissionConstants.PERMISSION_GROUP_BLUETOOTH) {
return checkBluetoothPermissionStatus();
}
if (permission == PermissionConstants.PERMISSION_GROUP_BLUETOOTH_CONNECT
|| permission == PermissionConstants.PERMISSION_GROUP_BLUETOOTH_SCAN
|| permission == PermissionConstants.PERMISSION_GROUP_BLUETOOTH_ADVERTISE) {
if (Build.VERSION.SDK_INT < Build.VERSION_CODES.S) {
return checkBluetoothPermissionStatus();
}
}
// Inspect the manifest for CALENDAR_FULL_ACCESS, as a misconfigured manifest will give a false positive if READ access has been provided.
if (permission == PermissionConstants.PERMISSION_GROUP_CALENDAR_FULL_ACCESS || permission == PermissionConstants.PERMISSION_GROUP_CALENDAR) {
boolean isValidManifest = isValidManifestForCalendarFullAccess();
if (!isValidManifest)
return PermissionConstants.PERMISSION_STATUS_DENIED;
}
final List<String> names = PermissionUtils.getManifestNames(context, permission);
if (names == null) {
Log.d(PermissionConstants.LOG_TAG, "No android specific permissions needed for: " + permission);
return PermissionConstants.PERMISSION_STATUS_GRANTED;
}
//if no permissions were found then there is an issue and permission is not set in Android manifest
if (names.size() == 0) {
Log.d(PermissionConstants.LOG_TAG, "No permissions found in manifest for: " + names + permission);
// On Android below M, the android.permission.REQUEST_IGNORE_BATTERY_OPTIMIZATIONS flag in AndroidManifest.xml
// may be ignored and not visible to the App as it's a new permission setting as a whole.
if (permission == PermissionConstants.PERMISSION_GROUP_IGNORE_BATTERY_OPTIMIZATIONS) {
if (Build.VERSION.SDK_INT < Build.VERSION_CODES.M) {
return PermissionConstants.PERMISSION_STATUS_RESTRICTED;
}
}
// On Android below R, the android.permission.MANAGE_EXTERNAL_STORAGE flag in AndroidManifest.xml
// may be ignored and not visible to the App as it's a new permission setting as a whole.
if (permission == PermissionConstants.PERMISSION_GROUP_MANAGE_EXTERNAL_STORAGE) {
if (Build.VERSION.SDK_INT < Build.VERSION_CODES.R) {
return PermissionConstants.PERMISSION_STATUS_RESTRICTED;
}
}
return Build.VERSION.SDK_INT < Build.VERSION_CODES.M
? PermissionConstants.PERMISSION_STATUS_GRANTED
: PermissionConstants.PERMISSION_STATUS_DENIED;
}
final boolean requiresExplicitPermission = context.getApplicationInfo().targetSdkVersion >= Build.VERSION_CODES.M;
if (requiresExplicitPermission) {
final Set<@PermissionConstants.PermissionStatus Integer> permissionStatuses = new HashSet<>();
for (String name : names) {
if (permission == PermissionConstants.PERMISSION_GROUP_IGNORE_BATTERY_OPTIMIZATIONS) {
String packageName = context.getPackageName();
PowerManager pm = (PowerManager) context.getSystemService(Context.POWER_SERVICE);
if (pm != null && pm.isIgnoringBatteryOptimizations(packageName)) {
permissionStatuses.add(PermissionConstants.PERMISSION_STATUS_GRANTED);
} else {
permissionStatuses.add(PermissionConstants.PERMISSION_STATUS_DENIED);
}
} else if (permission == PermissionConstants.PERMISSION_GROUP_MANAGE_EXTERNAL_STORAGE) {
if (Build.VERSION.SDK_INT < Build.VERSION_CODES.R) {
permissionStatuses.add(PermissionConstants.PERMISSION_STATUS_RESTRICTED);
}
int status = Environment.isExternalStorageManager()
? PermissionConstants.PERMISSION_STATUS_GRANTED
: PermissionConstants.PERMISSION_STATUS_DENIED;
permissionStatuses.add(status);
} else if (permission == PermissionConstants.PERMISSION_GROUP_SYSTEM_ALERT_WINDOW) {
int status = Settings.canDrawOverlays(context)
? PermissionConstants.PERMISSION_STATUS_GRANTED
: PermissionConstants.PERMISSION_STATUS_DENIED;
permissionStatuses.add(status);
} else if (permission == PermissionConstants.PERMISSION_GROUP_REQUEST_INSTALL_PACKAGES) {
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.O) {
int status = context.getPackageManager().canRequestPackageInstalls()
? PermissionConstants.PERMISSION_STATUS_GRANTED
: PermissionConstants.PERMISSION_STATUS_DENIED;
permissionStatuses.add(status);
}
} else if (permission == PermissionConstants.PERMISSION_GROUP_ACCESS_NOTIFICATION_POLICY) {
NotificationManager notificationManager = (NotificationManager) context.getSystemService(Application.NOTIFICATION_SERVICE);
int status = notificationManager.isNotificationPolicyAccessGranted()
? PermissionConstants.PERMISSION_STATUS_GRANTED
: PermissionConstants.PERMISSION_STATUS_DENIED;
permissionStatuses.add(status);
} else if (permission == PermissionConstants.PERMISSION_GROUP_SCHEDULE_EXACT_ALARM) {
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.S) {
AlarmManager alarmManager = (AlarmManager) context.getSystemService(Context.ALARM_SERVICE);
int status = alarmManager.canScheduleExactAlarms()
? PermissionConstants.PERMISSION_STATUS_GRANTED
: PermissionConstants.PERMISSION_STATUS_DENIED;
permissionStatuses.add(status);
} else {
permissionStatuses.add(PermissionConstants.PERMISSION_STATUS_GRANTED);
}
} else {
final int permissionStatus = ContextCompat.checkSelfPermission(context, name);
if (permissionStatus != PackageManager.PERMISSION_GRANTED) {
permissionStatuses.add(PermissionUtils.determineDeniedVariant(activity, name));
}
}
}
if (!permissionStatuses.isEmpty()) {
return strictestStatus(permissionStatuses);
}
}
return PermissionConstants.PERMISSION_STATUS_GRANTED;
}
/**
* Launches a request for a <a href="https://developer.android.com/training/permissions/requesting-special">special permission</a>.
* <p>
* There is a special case for {@link Settings#ACTION_NOTIFICATION_POLICY_ACCESS_SETTINGS}. See
* <a href="https://github.com/Baseflow/flutter-permission-handler/pull/587#discussion_r649295489">this comment</a>
* for more details.
*
* @param permissionAction the action for launching the settings page for a particular permission.
* @param requestCode a request code to verify incoming results.
*/
private void launchSpecialPermission(String permissionAction, int requestCode) {
if (activity == null) {
return;
}
Intent intent = new Intent(permissionAction);
if (!permissionAction.equals(Settings.ACTION_NOTIFICATION_POLICY_ACCESS_SETTINGS)) {
String packageName = activity.getPackageName();
intent.setData(Uri.parse("package:" + packageName));
}
activity.startActivityForResult(intent, requestCode);
pendingRequestCount++;
}
void shouldShowRequestPermissionRationale(
int permission,
ShouldShowRequestPermissionRationaleSuccessCallback successCallback,
ErrorCallback errorCallback) {
if (activity == null) {
Log.d(PermissionConstants.LOG_TAG, "Unable to detect current Activity.");
errorCallback.onError(
"PermissionHandler.PermissionManager",
"Unable to detect current Android Activity.");
return;
}
List<String> names = PermissionUtils.getManifestNames(activity, permission);
// if isn't an android specific group then go ahead and return false;
if (names == null) {
Log.d(PermissionConstants.LOG_TAG, "No android specific permissions needed for: " + permission);
successCallback.onSuccess(false);
return;
}
if (names.isEmpty()) {
Log.d(PermissionConstants.LOG_TAG, "No permissions found in manifest for: " + permission + " no need to show request rationale");
successCallback.onSuccess(false);
return;
}
successCallback.onSuccess(ActivityCompat.shouldShowRequestPermissionRationale(activity, names.get(0)));
}
@PermissionConstants.PermissionStatus
private int checkNotificationPermissionStatus() {
if (Build.VERSION.SDK_INT < Build.VERSION_CODES.TIRAMISU) {
NotificationManagerCompat manager = NotificationManagerCompat.from(context);
final boolean isGranted = manager.areNotificationsEnabled();
if (isGranted) {
return PermissionConstants.PERMISSION_STATUS_GRANTED;
}
return PermissionConstants.PERMISSION_STATUS_DENIED;
}
final int status = context.checkSelfPermission(Manifest.permission.POST_NOTIFICATIONS);
if (status == PackageManager.PERMISSION_GRANTED) {
return PermissionConstants.PERMISSION_STATUS_GRANTED;
}
return PermissionUtils.determineDeniedVariant(activity, Manifest.permission.POST_NOTIFICATIONS);
}
@PermissionConstants.PermissionStatus
private int checkBluetoothPermissionStatus() {
List<String> names = PermissionUtils.getManifestNames(context, PermissionConstants.PERMISSION_GROUP_BLUETOOTH);
boolean missingInManifest = names == null || names.isEmpty();
if (missingInManifest) {
Log.d(PermissionConstants.LOG_TAG, "Bluetooth permission missing in manifest");
return PermissionConstants.PERMISSION_STATUS_DENIED;
}
return PermissionConstants.PERMISSION_STATUS_GRANTED;
}
/**
* Checks if the manifest contains both {@link Manifest.permission#WRITE_CALENDAR} and
* {@link Manifest.permission#READ_CALENDAR} permission declarations.
*/
private boolean isValidManifestForCalendarFullAccess() {
List<String> names = PermissionUtils.getManifestNames(context, PermissionConstants.PERMISSION_GROUP_CALENDAR_FULL_ACCESS);
final boolean writeInManifest = names != null && names.contains(Manifest.permission.WRITE_CALENDAR);
final boolean readInManifest = names != null && names.contains(Manifest.permission.READ_CALENDAR);
final boolean validManifest = writeInManifest && readInManifest;
if (!validManifest) {
if (!writeInManifest)
Log.d(PermissionConstants.LOG_TAG, Manifest.permission.WRITE_CALENDAR + " missing in manifest");
if (!readInManifest)
Log.d(PermissionConstants.LOG_TAG, Manifest.permission.READ_CALENDAR + " missing in manifest");
return false;
}
return true;
}
@FunctionalInterface
interface RequestPermissionsSuccessCallback {
void onSuccess(Map<Integer, Integer> results);
}
@FunctionalInterface
interface CheckPermissionsSuccessCallback {
void onSuccess(@PermissionConstants.PermissionStatus int permissionStatus);
}
@FunctionalInterface
interface ShouldShowRequestPermissionRationaleSuccessCallback {
void onSuccess(boolean shouldShowRequestPermissionRationale);
}
}
package com.baseflow.permissionhandler;
import android.Manifest;
import android.app.Activity;
import android.content.Context;
import android.content.SharedPreferences;
import android.content.pm.PackageInfo;
import android.content.pm.PackageManager;
import android.os.Build;
import android.os.Environment;
import android.util.Log;
import androidx.annotation.NonNull;
import androidx.annotation.Nullable;
import androidx.annotation.RequiresApi;
import androidx.core.app.ActivityCompat;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.Collection;
import java.util.HashSet;
import java.util.List;
public class PermissionUtils {
final static String SHARED_PREFERENCES_PERMISSION_WAS_DENIED_BEFORE_KEY = "sp_permission_handler_permission_was_denied_before";
@PermissionConstants.PermissionGroup
static int parseManifestName(String permission) {
switch (permission) {
case Manifest.permission.WRITE_CALENDAR:
case Manifest.permission.READ_CALENDAR:
return PermissionConstants.PERMISSION_GROUP_CALENDAR;
case Manifest.permission.CAMERA:
return PermissionConstants.PERMISSION_GROUP_CAMERA;
case Manifest.permission.READ_CONTACTS:
case Manifest.permission.WRITE_CONTACTS:
case Manifest.permission.GET_ACCOUNTS:
return PermissionConstants.PERMISSION_GROUP_CONTACTS;
case Manifest.permission.ACCESS_BACKGROUND_LOCATION:
return PermissionConstants.PERMISSION_GROUP_LOCATION_ALWAYS;
case Manifest.permission.ACCESS_COARSE_LOCATION:
case Manifest.permission.ACCESS_FINE_LOCATION:
return PermissionConstants.PERMISSION_GROUP_LOCATION;
case Manifest.permission.RECORD_AUDIO:
return PermissionConstants.PERMISSION_GROUP_MICROPHONE;
case Manifest.permission.READ_PHONE_STATE:
case Manifest.permission.READ_PHONE_NUMBERS:
case Manifest.permission.CALL_PHONE:
case Manifest.permission.READ_CALL_LOG:
case Manifest.permission.WRITE_CALL_LOG:
case Manifest.permission.ADD_VOICEMAIL:
case Manifest.permission.USE_SIP:
return PermissionConstants.PERMISSION_GROUP_PHONE;
case Manifest.permission.BODY_SENSORS:
return PermissionConstants.PERMISSION_GROUP_SENSORS;
case Manifest.permission.BODY_SENSORS_BACKGROUND:
return PermissionConstants.PERMISSION_GROUP_SENSORS_ALWAYS;
case Manifest.permission.SEND_SMS:
case Manifest.permission.RECEIVE_SMS:
case Manifest.permission.READ_SMS:
case Manifest.permission.RECEIVE_WAP_PUSH:
case Manifest.permission.RECEIVE_MMS:
return PermissionConstants.PERMISSION_GROUP_SMS;
case Manifest.permission.READ_EXTERNAL_STORAGE:
case Manifest.permission.WRITE_EXTERNAL_STORAGE:
return PermissionConstants.PERMISSION_GROUP_STORAGE;
case Manifest.permission.ACCESS_MEDIA_LOCATION:
return PermissionConstants.PERMISSION_GROUP_ACCESS_MEDIA_LOCATION;
case Manifest.permission.ACTIVITY_RECOGNITION:
return PermissionConstants.PERMISSION_GROUP_ACTIVITY_RECOGNITION;
case Manifest.permission.MANAGE_EXTERNAL_STORAGE:
return PermissionConstants.PERMISSION_GROUP_MANAGE_EXTERNAL_STORAGE;
case Manifest.permission.SYSTEM_ALERT_WINDOW:
return PermissionConstants.PERMISSION_GROUP_SYSTEM_ALERT_WINDOW;
case Manifest.permission.REQUEST_INSTALL_PACKAGES:
return PermissionConstants.PERMISSION_GROUP_REQUEST_INSTALL_PACKAGES;
case Manifest.permission.ACCESS_NOTIFICATION_POLICY:
return PermissionConstants.PERMISSION_GROUP_ACCESS_NOTIFICATION_POLICY;
case Manifest.permission.BLUETOOTH_SCAN:
return PermissionConstants.PERMISSION_GROUP_BLUETOOTH_SCAN;
case Manifest.permission.BLUETOOTH_ADVERTISE:
return PermissionConstants.PERMISSION_GROUP_BLUETOOTH_ADVERTISE;
case Manifest.permission.BLUETOOTH_CONNECT:
return PermissionConstants.PERMISSION_GROUP_BLUETOOTH_CONNECT;
case Manifest.permission.POST_NOTIFICATIONS:
return PermissionConstants.PERMISSION_GROUP_NOTIFICATION;
case Manifest.permission.NEARBY_WIFI_DEVICES:
return PermissionConstants.PERMISSION_GROUP_NEARBY_WIFI_DEVICES;
case Manifest.permission.READ_MEDIA_IMAGES:
return PermissionConstants.PERMISSION_GROUP_PHOTOS;
case Manifest.permission.READ_MEDIA_VIDEO:
return PermissionConstants.PERMISSION_GROUP_VIDEOS;
case Manifest.permission.READ_MEDIA_AUDIO:
return PermissionConstants.PERMISSION_GROUP_AUDIO;
case Manifest.permission.SCHEDULE_EXACT_ALARM:
return PermissionConstants.PERMISSION_GROUP_SCHEDULE_EXACT_ALARM;
default:
return PermissionConstants.PERMISSION_GROUP_UNKNOWN;
}
}
static List<String> getManifestNames(Context context, @PermissionConstants.PermissionGroup int permission) {
final ArrayList<String> permissionNames = new ArrayList<>();
switch (permission) {
case PermissionConstants.PERMISSION_GROUP_CALENDAR_WRITE_ONLY:
if (hasPermissionInManifest(context, permissionNames, Manifest.permission.WRITE_CALENDAR))
permissionNames.add(Manifest.permission.WRITE_CALENDAR);
break;
case PermissionConstants.PERMISSION_GROUP_CALENDAR_FULL_ACCESS:
case PermissionConstants.PERMISSION_GROUP_CALENDAR:
if (hasPermissionInManifest(context, permissionNames, Manifest.permission.WRITE_CALENDAR))
permissionNames.add(Manifest.permission.WRITE_CALENDAR);
if (hasPermissionInManifest(context, permissionNames, Manifest.permission.READ_CALENDAR))
permissionNames.add(Manifest.permission.READ_CALENDAR);
break;
case PermissionConstants.PERMISSION_GROUP_CAMERA:
if (hasPermissionInManifest(context, permissionNames, Manifest.permission.CAMERA))
permissionNames.add(Manifest.permission.CAMERA);
break;
case PermissionConstants.PERMISSION_GROUP_CONTACTS:
if (hasPermissionInManifest(context, permissionNames, Manifest.permission.READ_CONTACTS))
permissionNames.add(Manifest.permission.READ_CONTACTS);
if (hasPermissionInManifest(context, permissionNames, Manifest.permission.WRITE_CONTACTS))
permissionNames.add(Manifest.permission.WRITE_CONTACTS);
if (hasPermissionInManifest(context, permissionNames, Manifest.permission.GET_ACCOUNTS))
permissionNames.add(Manifest.permission.GET_ACCOUNTS);
break;
case PermissionConstants.PERMISSION_GROUP_LOCATION_ALWAYS:
case PermissionConstants.PERMISSION_GROUP_LOCATION_WHEN_IN_USE:
case PermissionConstants.PERMISSION_GROUP_LOCATION:
// Note that the LOCATION_ALWAYS will deliberately fallthrough to the LOCATION
// case on pre Android Q devices. The ACCESS_BACKGROUND_LOCATION permission was only
// introduced in Android Q, before it should be treated as the ACCESS_COARSE_LOCATION or
// ACCESS_FINE_LOCATION.
if (permission == PermissionConstants.PERMISSION_GROUP_LOCATION_ALWAYS && Build.VERSION.SDK_INT >= Build.VERSION_CODES.Q) {
if (hasPermissionInManifest(context, permissionNames, Manifest.permission.ACCESS_BACKGROUND_LOCATION))
permissionNames.add(Manifest.permission.ACCESS_BACKGROUND_LOCATION);
break;
}
if (hasPermissionInManifest(context, permissionNames, Manifest.permission.ACCESS_COARSE_LOCATION))
permissionNames.add(Manifest.permission.ACCESS_COARSE_LOCATION);
if (hasPermissionInManifest(context, permissionNames, Manifest.permission.ACCESS_FINE_LOCATION))
permissionNames.add(Manifest.permission.ACCESS_FINE_LOCATION);
break;
case PermissionConstants.PERMISSION_GROUP_SPEECH:
case PermissionConstants.PERMISSION_GROUP_MICROPHONE:
if (hasPermissionInManifest(context, permissionNames, Manifest.permission.RECORD_AUDIO))
permissionNames.add(Manifest.permission.RECORD_AUDIO);
break;
case PermissionConstants.PERMISSION_GROUP_PHONE:
if (hasPermissionInManifest(context, permissionNames, Manifest.permission.READ_PHONE_STATE))
permissionNames.add(Manifest.permission.READ_PHONE_STATE);
if (android.os.Build.VERSION.SDK_INT > Build.VERSION_CODES.Q && hasPermissionInManifest(context, permissionNames, Manifest.permission.READ_PHONE_NUMBERS))
permissionNames.add(Manifest.permission.READ_PHONE_NUMBERS);
if (hasPermissionInManifest(context, permissionNames, Manifest.permission.CALL_PHONE))
permissionNames.add(Manifest.permission.CALL_PHONE);
if (hasPermissionInManifest(context, permissionNames, Manifest.permission.READ_CALL_LOG))
permissionNames.add(Manifest.permission.READ_CALL_LOG);
if (hasPermissionInManifest(context, permissionNames, Manifest.permission.WRITE_CALL_LOG))
permissionNames.add(Manifest.permission.WRITE_CALL_LOG);
if (hasPermissionInManifest(context, permissionNames, Manifest.permission.ADD_VOICEMAIL))
permissionNames.add(Manifest.permission.ADD_VOICEMAIL);
if (hasPermissionInManifest(context, permissionNames, Manifest.permission.USE_SIP))
permissionNames.add(Manifest.permission.USE_SIP);
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.O && hasPermissionInManifest(context, permissionNames, Manifest.permission.ANSWER_PHONE_CALLS))
permissionNames.add(Manifest.permission.ANSWER_PHONE_CALLS);
break;
case PermissionConstants.PERMISSION_GROUP_SENSORS:
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.KITKAT_WATCH) {
if (hasPermissionInManifest(context, permissionNames, Manifest.permission.BODY_SENSORS)) {
permissionNames.add(Manifest.permission.BODY_SENSORS);
}
}
break;
case PermissionConstants.PERMISSION_GROUP_SENSORS_ALWAYS:
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.TIRAMISU) {
if (hasPermissionInManifest(context, permissionNames, Manifest.permission.BODY_SENSORS_BACKGROUND)) {
permissionNames.add(Manifest.permission.BODY_SENSORS_BACKGROUND);
}
}
break;
case PermissionConstants.PERMISSION_GROUP_SMS:
if (hasPermissionInManifest(context, permissionNames, Manifest.permission.SEND_SMS))
permissionNames.add(Manifest.permission.SEND_SMS);
if (hasPermissionInManifest(context, permissionNames, Manifest.permission.RECEIVE_SMS))
permissionNames.add(Manifest.permission.RECEIVE_SMS);
if (hasPermissionInManifest(context, permissionNames, Manifest.permission.READ_SMS))
permissionNames.add(Manifest.permission.READ_SMS);
if (hasPermissionInManifest(context, permissionNames, Manifest.permission.RECEIVE_WAP_PUSH))
permissionNames.add(Manifest.permission.RECEIVE_WAP_PUSH);
if (hasPermissionInManifest(context, permissionNames, Manifest.permission.RECEIVE_MMS))
permissionNames.add(Manifest.permission.RECEIVE_MMS);
break;
case PermissionConstants.PERMISSION_GROUP_STORAGE:
if (hasPermissionInManifest(context, permissionNames, Manifest.permission.READ_EXTERNAL_STORAGE))
permissionNames.add(Manifest.permission.READ_EXTERNAL_STORAGE);
if (Build.VERSION.SDK_INT < Build.VERSION_CODES.Q || (Build.VERSION.SDK_INT == Build.VERSION_CODES.Q && Environment.isExternalStorageLegacy())) {
if (hasPermissionInManifest(context, permissionNames, Manifest.permission.WRITE_EXTERNAL_STORAGE))
permissionNames.add(Manifest.permission.WRITE_EXTERNAL_STORAGE);
break;
}
break;
case PermissionConstants.PERMISSION_GROUP_IGNORE_BATTERY_OPTIMIZATIONS:
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.M && hasPermissionInManifest(context, permissionNames, Manifest.permission.REQUEST_IGNORE_BATTERY_OPTIMIZATIONS))
permissionNames.add(Manifest.permission.REQUEST_IGNORE_BATTERY_OPTIMIZATIONS);
break;
case PermissionConstants.PERMISSION_GROUP_ACCESS_MEDIA_LOCATION:
// The ACCESS_MEDIA_LOCATION permission is introduced in Android Q, meaning we should
// not handle permissions on pre Android Q devices.
if (Build.VERSION.SDK_INT < Build.VERSION_CODES.Q) return null;
if (hasPermissionInManifest(context, permissionNames, Manifest.permission.ACCESS_MEDIA_LOCATION))
permissionNames.add(Manifest.permission.ACCESS_MEDIA_LOCATION);
break;
case PermissionConstants.PERMISSION_GROUP_ACTIVITY_RECOGNITION:
// The ACTIVITY_RECOGNITION permission is introduced in Android Q, meaning we should
// not handle permissions on pre Android Q devices.
if (Build.VERSION.SDK_INT < Build.VERSION_CODES.Q) return null;
if (hasPermissionInManifest(context, permissionNames, Manifest.permission.ACTIVITY_RECOGNITION))
permissionNames.add(Manifest.permission.ACTIVITY_RECOGNITION);
break;
case PermissionConstants.PERMISSION_GROUP_BLUETOOTH:
if (hasPermissionInManifest(context, permissionNames, Manifest.permission.BLUETOOTH))
permissionNames.add(Manifest.permission.BLUETOOTH);
break;
case PermissionConstants.PERMISSION_GROUP_MANAGE_EXTERNAL_STORAGE:
// The MANAGE_EXTERNAL_STORAGE permission is introduced in Android R, meaning we should
// not handle permissions on pre Android R devices.
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.R && hasPermissionInManifest(context, permissionNames, Manifest.permission.MANAGE_EXTERNAL_STORAGE))
permissionNames.add(Manifest.permission.MANAGE_EXTERNAL_STORAGE);
break;
case PermissionConstants.PERMISSION_GROUP_SYSTEM_ALERT_WINDOW:
if (hasPermissionInManifest(context, permissionNames, Manifest.permission.SYSTEM_ALERT_WINDOW))
permissionNames.add(Manifest.permission.SYSTEM_ALERT_WINDOW);
break;
case PermissionConstants.PERMISSION_GROUP_REQUEST_INSTALL_PACKAGES:
// The REQUEST_INSTALL_PACKAGES permission is introduced in Android M, meaning we should
// not handle permissions on pre Android M devices.
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.M && hasPermissionInManifest(context, permissionNames, Manifest.permission.REQUEST_INSTALL_PACKAGES))
permissionNames.add(Manifest.permission.REQUEST_INSTALL_PACKAGES);
break;
case PermissionConstants.PERMISSION_GROUP_ACCESS_NOTIFICATION_POLICY:
// The REQUEST_NOTIFICATION_POLICY permission is introduced in Android M, meaning we should
// not handle permissions on pre Android M devices.
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.M && hasPermissionInManifest(context, permissionNames, Manifest.permission.ACCESS_NOTIFICATION_POLICY))
permissionNames.add(Manifest.permission.ACCESS_NOTIFICATION_POLICY);
break;
case PermissionConstants.PERMISSION_GROUP_BLUETOOTH_SCAN: {
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.S) {
// The BLUETOOTH_SCAN permission is introduced in Android S, meaning we should
// not handle permissions on pre Android S devices.
String result = determineBluetoothPermission(context, Manifest.permission.BLUETOOTH_SCAN);
if (result != null) {
permissionNames.add(result);
}
}
break;
}
case PermissionConstants.PERMISSION_GROUP_BLUETOOTH_ADVERTISE: {
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.S) {
// The BLUETOOTH_ADVERTISE permission is introduced in Android S, meaning we should
// not handle permissions on pre Android S devices.
String result = determineBluetoothPermission(context, Manifest.permission.BLUETOOTH_ADVERTISE);
if (result != null) {
permissionNames.add(result);
}
}
break;
}
case PermissionConstants.PERMISSION_GROUP_BLUETOOTH_CONNECT: {
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.S) {
// The BLUETOOTH_CONNECT permission is introduced in Android S, meaning we should
// not handle permissions on pre Android S devices.
String result = determineBluetoothPermission(context, Manifest.permission.BLUETOOTH_CONNECT);
if (result != null) {
permissionNames.add(result);
}
}
break;
}
case PermissionConstants.PERMISSION_GROUP_NOTIFICATION:
// The POST_NOTIFICATIONS permission is introduced in Android TIRAMISU, meaning we should
// not handle permissions on pre Android TIRAMISU devices.
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.TIRAMISU && hasPermissionInManifest(context, permissionNames, Manifest.permission.POST_NOTIFICATIONS))
permissionNames.add(Manifest.permission.POST_NOTIFICATIONS);
break;
case PermissionConstants.PERMISSION_GROUP_NEARBY_WIFI_DEVICES:
// The NEARBY_WIFI_DEVICES permission is introduced in Android TIRAMISU, meaning we should
// not handle permissions on pre Android TIRAMISU devices.
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.TIRAMISU && hasPermissionInManifest(context, permissionNames, Manifest.permission.NEARBY_WIFI_DEVICES))
permissionNames.add(Manifest.permission.NEARBY_WIFI_DEVICES);
break;
case PermissionConstants.PERMISSION_GROUP_PHOTOS:
// The READ_MEDIA_IMAGES permission is introduced in Android TIRAMISU, meaning we should
// not handle permissions on pre Android TIRAMISU devices.
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.TIRAMISU && hasPermissionInManifest(context, permissionNames, Manifest.permission.READ_MEDIA_IMAGES))
permissionNames.add(Manifest.permission.READ_MEDIA_IMAGES);
break;
case PermissionConstants.PERMISSION_GROUP_VIDEOS:
// The READ_MEDIA_VIDEOS permission is introduced in Android TIRAMISU, meaning we should
// not handle permissions on pre Android TIRAMISU devices.
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.TIRAMISU && hasPermissionInManifest(context, permissionNames, Manifest.permission.READ_MEDIA_VIDEO))
permissionNames.add(Manifest.permission.READ_MEDIA_VIDEO);
break;
case PermissionConstants.PERMISSION_GROUP_AUDIO:
// The READ_MEDIA_AUDIO permission is introduced in Android TIRAMISU, meaning we should
// not handle permissions on pre Android TIRAMISU devices.
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.TIRAMISU && hasPermissionInManifest(context, permissionNames, Manifest.permission.READ_MEDIA_AUDIO))
permissionNames.add(Manifest.permission.READ_MEDIA_AUDIO);
break;
case PermissionConstants.PERMISSION_GROUP_SCHEDULE_EXACT_ALARM:
// The SCHEDULE_EXACT_ALARM permission is introduced in Android S, before Android 31 it should alway return Granted
if (hasPermissionInManifest(context, permissionNames, Manifest.permission.SCHEDULE_EXACT_ALARM))
permissionNames.add(Manifest.permission.SCHEDULE_EXACT_ALARM);
break;
case PermissionConstants.PERMISSION_GROUP_MEDIA_LIBRARY:
case PermissionConstants.PERMISSION_GROUP_REMINDERS:
case PermissionConstants.PERMISSION_GROUP_UNKNOWN:
return null;
}
return permissionNames;
}
private static boolean hasPermissionInManifest(Context context, ArrayList<String> confirmedPermissions, String permission) {
try {
if (confirmedPermissions != null) {
for (String r : confirmedPermissions) {
if (r.equals(permission)) {
return true;
}
}
}
if (context == null) {
Log.d(PermissionConstants.LOG_TAG, "Unable to detect current Activity or App Context.");
return false;
}
PackageInfo info = getPackageInfo(context);
if (info == null) {
Log.d(PermissionConstants.LOG_TAG, "Unable to get Package info, will not be able to determine permissions to request.");
return false;
}
confirmedPermissions = new ArrayList<>(Arrays.asList(info.requestedPermissions));
for (String r : confirmedPermissions) {
if (r.equals(permission)) {
return true;
}
}
} catch (Exception ex) {
Log.d(PermissionConstants.LOG_TAG, "Unable to check manifest for permission: ", ex);
}
return false;
}
/**
* Returns a {@link PermissionConstants} for a given permission.
* <p>
* When {@link PackageManager#PERMISSION_DENIED} is received, we do not know if the permission was
* denied permanently. The OS does not tell us whether the user dismissed the dialog or pressed
* 'deny'. Therefore, we need a more sophisticated (read: hacky) approach to determine whether the
* permission status is {@link PermissionConstants#PERMISSION_STATUS_DENIED} or
* {@link PermissionConstants#PERMISSION_STATUS_NEVER_ASK_AGAIN}.
* <p>
* The OS behavior has been researched experimentally and is displayed in the following diagrams:
* <p>
* State machine diagram:
* <p>
* Dismissed
* ┌┐
* ┌──┘▼─────┐ Granted ┌───────┐
* │Not asked├──────────►Granted│
* └─┬───────┘ └─▲─────┘
* │ Granted │
* │Denied ┌───────────┘
* │ │
* ┌─▼────────┴┐ ┌────────────────────────────────┐
* │Denied once├────────►Denied twice(permanently denied)│
* └──▲┌───────┘ Denied └────────────────────────────────┘
* └┘
* Dismissed
* <p>
* Scenario table listing output of
* {@link ActivityCompat#shouldShowRequestPermissionRationale(Activity, String)}:
* ┌────────────┬────────────────┬─────────┬───────────────────────────────────┬─────────────────────────┐
* │ Scenario # │ Previous state │ Action │ New state │ 'Show rationale' output │
* ├────────────┼────────────────┼─────────┼───────────────────────────────────┼─────────────────────────┤
* │ 1. │ Not asked │ Dismiss │ Not asked │ false │
* │ 2. │ Not asked │ Deny │ Denied once │ true │
* │ 3. │ Denied once │ Dismiss │ Denied once │ true │
* │ 4. │ Denied once │ Deny │ Denied twice (permanently denied) │ false │
* └────────────┴────────────────┴─────────┴───────────────────────────────────┴─────────────────────────┘
* <p>
* To distinguish between scenarios, we can use
* {@link ActivityCompat#shouldShowRequestPermissionRationale(Activity, String)}. If it returns
* true, we can safely return {@link PermissionConstants#PERMISSION_STATUS_DENIED}. To distinguish
* between scenarios 1 and 4, however, we need an extra mechanism. We opt to store a boolean
* stating whether permission has been requested before. Using a combination of checking for
* showing the permission rationale and the boolean, we can distinguish all scenarios and return
* the appropriate permission status.
* <p>
* Changing permissions via the app info screen, so outside of the application, changes the
* permission state to 'Granted' if the permission is allowed, or 'Denied once' if denied. This
* behavior should not require any additional logic.
*
* @param activity the activity for context
* @param permissionName the name of the permission
* @param grantResult the result of the permission intent. Either
* {@link PackageManager#PERMISSION_DENIED} or {@link PackageManager#PERMISSION_GRANTED}.
* @return {@link PermissionConstants#PERMISSION_STATUS_GRANTED},
* {@link PermissionConstants#PERMISSION_STATUS_DENIED}, or
* {@link PermissionConstants#PERMISSION_STATUS_NEVER_ASK_AGAIN}.
*/
@PermissionConstants.PermissionStatus
static int toPermissionStatus(
final @Nullable Activity activity,
final String permissionName,
int grantResult) {
if (grantResult == PackageManager.PERMISSION_DENIED) {
return determineDeniedVariant(activity, permissionName);
}
return PermissionConstants.PERMISSION_STATUS_GRANTED;
}
@NonNull
@PermissionConstants.PermissionStatus
static Integer strictestStatus(final @NonNull Collection<@PermissionConstants.PermissionStatus Integer> statuses) {
if (statuses.contains(PermissionConstants.PERMISSION_STATUS_NEVER_ASK_AGAIN))
return PermissionConstants.PERMISSION_STATUS_NEVER_ASK_AGAIN;
if (statuses.contains(PermissionConstants.PERMISSION_STATUS_RESTRICTED))
return PermissionConstants.PERMISSION_STATUS_RESTRICTED;
if (statuses.contains(PermissionConstants.PERMISSION_STATUS_DENIED))
return PermissionConstants.PERMISSION_STATUS_DENIED;
if (statuses.contains(PermissionConstants.PERMISSION_STATUS_LIMITED))
return PermissionConstants.PERMISSION_STATUS_LIMITED;
return PermissionConstants.PERMISSION_STATUS_GRANTED;
}
@NonNull
@PermissionConstants.PermissionStatus
static Integer strictestStatus(
final @Nullable @PermissionConstants.PermissionStatus Integer statusA,
final @Nullable @PermissionConstants.PermissionStatus Integer statusB) {
final Collection<@PermissionConstants.PermissionStatus Integer> statuses = new HashSet<>();
statuses.add(statusA);
statuses.add(statusB);
return strictestStatus(statuses);
}
/**
* Determines whether a permission was either 'denied' or 'permanently denied'.
* <p>
* To distinguish between these two variants, the method needs access to an {@link Activity}.
* If the provided activity is null, the result will always be resolved to 'denied'.
*
* @param activity the activity needed to resolve the permission status.
* @param permissionName the name of the permission.
* @return either {@link PermissionConstants#PERMISSION_STATUS_DENIED} or
* {@link PermissionConstants#PERMISSION_STATUS_NEVER_ASK_AGAIN}.
*/
@PermissionConstants.PermissionStatus
static int determineDeniedVariant(
final @Nullable Activity activity,
final String permissionName) {
if (activity == null) {
return PermissionConstants.PERMISSION_STATUS_DENIED;
}
if (Build.VERSION.SDK_INT < Build.VERSION_CODES.M) {
return PermissionConstants.PERMISSION_STATUS_DENIED;
}
final boolean wasDeniedBefore = PermissionUtils.wasPermissionDeniedBefore(activity, permissionName);
final boolean shouldShowRational = !PermissionUtils.isNeverAskAgainSelected(activity, permissionName);
//noinspection SimplifiableConditionalExpression
final boolean isDenied = wasDeniedBefore ? !shouldShowRational : shouldShowRational;
if (!wasDeniedBefore && isDenied) {
setPermissionDenied(activity, permissionName);
}
if (wasDeniedBefore && isDenied) {
return PermissionConstants.PERMISSION_STATUS_NEVER_ASK_AGAIN;
}
return PermissionConstants.PERMISSION_STATUS_DENIED;
}
@RequiresApi(api = Build.VERSION_CODES.M)
static boolean isNeverAskAgainSelected(
@NonNull final Activity activity,
final String name) {
final boolean shouldShowRequestPermissionRationale = ActivityCompat.shouldShowRequestPermissionRationale(activity, name);
return !shouldShowRequestPermissionRationale;
}
private static String determineBluetoothPermission(Context context, String permission) {
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.S && hasPermissionInManifest(context, null, permission)) {
return permission;
} else if (Build.VERSION.SDK_INT < Build.VERSION_CODES.Q) {
if (hasPermissionInManifest(context, null, Manifest.permission.ACCESS_FINE_LOCATION)) {
return Manifest.permission.ACCESS_FINE_LOCATION;
} else if (hasPermissionInManifest(context, null, Manifest.permission.ACCESS_COARSE_LOCATION)) {
return Manifest.permission.ACCESS_COARSE_LOCATION;
}
return null;
} else if (hasPermissionInManifest(context, null, Manifest.permission.ACCESS_FINE_LOCATION)) {
return Manifest.permission.ACCESS_FINE_LOCATION;
}
return null;
}
// Suppress deprecation warnings since its purpose is to support to be backwards compatible with
// pre TIRAMISU versions of Android
@SuppressWarnings("deprecation")
private static PackageInfo getPackageInfo(Context context) throws PackageManager.NameNotFoundException {
final PackageManager pm = context.getPackageManager();
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.TIRAMISU) {
return pm.getPackageInfo(context.getPackageName(), PackageManager.PackageInfoFlags.of(PackageManager.GET_PERMISSIONS));
} else {
return pm.getPackageInfo(context.getPackageName(), PackageManager.GET_PERMISSIONS);
}
}
/**
* Checks if permission was denied in the past by reading
* {@link PermissionUtils#SHARED_PREFERENCES_PERMISSION_WAS_DENIED_BEFORE_KEY} from
* {@link SharedPreferences}.
* <p>
* Because the state is red from shared preferences, it is persistent across application
* sessions.
*
* @param context context needed for accessing shared preferences
* @param permissionName the name of the permission
* @return whether the permission was denied in the past
*/
private static boolean wasPermissionDeniedBefore(final Context context, final String permissionName) {
final SharedPreferences sharedPreferences = context.getSharedPreferences(permissionName, Context.MODE_PRIVATE);
return sharedPreferences.getBoolean(SHARED_PREFERENCES_PERMISSION_WAS_DENIED_BEFORE_KEY, false);
}
/**
* Stores a boolean in {@link SharedPreferences} indicating the provided permission has been
* denied.
* <p>
* Because the state is stored in shared preferences, it is persistent across application
* sessions.
*
* @param context context needed for accessing shared preferences.
* @param permissionName the name of the permission
*/
private static void setPermissionDenied(final Context context, final String permissionName) {
final SharedPreferences sharedPreferences = context.getSharedPreferences(permissionName, Context.MODE_PRIVATE);
sharedPreferences.edit().putBoolean(SHARED_PREFERENCES_PERMISSION_WAS_DENIED_BEFORE_KEY, true).apply();
}
}
package com.baseflow.permissionhandler;
import static android.content.Context.BLUETOOTH_SERVICE;
import android.bluetooth.BluetoothAdapter;
import android.bluetooth.BluetoothManager;
import android.content.Context;
import android.content.Intent;
import android.content.pm.PackageManager;
import android.content.pm.ResolveInfo;
import android.location.LocationManager;
import android.net.Uri;
import android.os.Build;
import android.os.Build.VERSION;
import android.os.Build.VERSION_CODES;
import android.provider.Settings;
import android.telephony.TelephonyManager;
import android.text.TextUtils;
import android.util.Log;
import java.util.List;
final class ServiceManager {
@FunctionalInterface
interface SuccessCallback {
void onSuccess(@PermissionConstants.ServiceStatus int serviceStatus);
}
void checkServiceStatus(
int permission,
Context context,
SuccessCallback successCallback,
ErrorCallback errorCallback) {
if(context == null) {
Log.d(PermissionConstants.LOG_TAG, "Context cannot be null.");
errorCallback.onError("PermissionHandler.ServiceManager", "Android context cannot be null.");
return;
}
if (permission == PermissionConstants.PERMISSION_GROUP_LOCATION ||
permission == PermissionConstants.PERMISSION_GROUP_LOCATION_ALWAYS ||
permission == PermissionConstants.PERMISSION_GROUP_LOCATION_WHEN_IN_USE) {
final int serviceStatus = isLocationServiceEnabled(context)
? PermissionConstants.SERVICE_STATUS_ENABLED
: PermissionConstants.SERVICE_STATUS_DISABLED;
successCallback.onSuccess(serviceStatus);
return;
}
if(permission == PermissionConstants.PERMISSION_GROUP_BLUETOOTH){
final int serviceStatus = isBluetoothServiceEnabled(context)
? PermissionConstants.SERVICE_STATUS_ENABLED
: PermissionConstants.SERVICE_STATUS_DISABLED;
successCallback.onSuccess(serviceStatus);
return;
}
if (permission == PermissionConstants.PERMISSION_GROUP_PHONE) {
PackageManager pm = context.getPackageManager();
if (!pm.hasSystemFeature(PackageManager.FEATURE_TELEPHONY)) {
successCallback.onSuccess(PermissionConstants.SERVICE_STATUS_NOT_APPLICABLE);
return;
}
TelephonyManager telephonyManager = (TelephonyManager) context
.getSystemService(Context.TELEPHONY_SERVICE);
if (telephonyManager == null || telephonyManager.getPhoneType() == TelephonyManager.PHONE_TYPE_NONE) {
successCallback.onSuccess(PermissionConstants.SERVICE_STATUS_NOT_APPLICABLE);
return;
}
List<ResolveInfo> callAppsList = getCallAppsList(pm);
if (callAppsList.isEmpty()) {
successCallback.onSuccess(PermissionConstants.SERVICE_STATUS_NOT_APPLICABLE);
return;
}
if (telephonyManager.getSimState() != TelephonyManager.SIM_STATE_READY) {
successCallback.onSuccess(PermissionConstants.SERVICE_STATUS_DISABLED);
return;
}
successCallback.onSuccess(PermissionConstants.SERVICE_STATUS_ENABLED);
return;
}
if (permission == PermissionConstants.PERMISSION_GROUP_IGNORE_BATTERY_OPTIMIZATIONS) {
final int serviceStatus = Build.VERSION.SDK_INT >= Build.VERSION_CODES.M
? PermissionConstants.SERVICE_STATUS_ENABLED
: PermissionConstants.SERVICE_STATUS_NOT_APPLICABLE;
successCallback.onSuccess(serviceStatus);
return;
}
successCallback.onSuccess(PermissionConstants.SERVICE_STATUS_NOT_APPLICABLE);
}
private boolean isLocationServiceEnabled(Context context) {
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.P) {
final LocationManager locationManager = context.getSystemService(LocationManager.class);
if (locationManager == null) {
return false;
}
return locationManager.isLocationEnabled();
} else if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.KITKAT) {
return isLocationServiceEnabledKitKat(context);
} else {
return isLocationServiceEnablePreKitKat(context);
}
}
// Suppress deprecation warnings since its purpose is to support to be backwards compatible with
// pre Pie versions of Android.
@SuppressWarnings("deprecation")
private static boolean isLocationServiceEnabledKitKat(Context context)
{
if (Build.VERSION.SDK_INT < VERSION_CODES.KITKAT) {
return false;
}
final int locationMode;
try {
locationMode = Settings.Secure.getInt(
context.getContentResolver(),
Settings.Secure.LOCATION_MODE);
} catch (Settings.SettingNotFoundException e) {
e.printStackTrace();
return false;
}
return locationMode != Settings.Secure.LOCATION_MODE_OFF;
}
// Suppress deprecation warnings since its purpose is to support to be backwards compatible with
// pre KitKat versions of Android.
@SuppressWarnings("deprecation")
private static boolean isLocationServiceEnablePreKitKat(Context context)
{
if (VERSION.SDK_INT >= VERSION_CODES.KITKAT)
return false;
final String locationProviders = Settings.Secure.getString(
context.getContentResolver(),
Settings.Secure.LOCATION_PROVIDERS_ALLOWED);
return !TextUtils.isEmpty(locationProviders);
}
// Suppress deprecation warnings since its purpose is to support to be backwards compatible with
// pre S versions of Android
@SuppressWarnings("deprecation")
private boolean isBluetoothServiceEnabled(Context context) {
if (android.os.Build.VERSION.SDK_INT < android.os.Build.VERSION_CODES.JELLY_BEAN_MR2) {
return BluetoothAdapter.getDefaultAdapter().isEnabled();
}
BluetoothManager manager = (BluetoothManager) context.getSystemService(BLUETOOTH_SERVICE);
final BluetoothAdapter adapter = manager.getAdapter();
return adapter.isEnabled();
}
// Suppress deprecation warnings since its purpose is to support to be backwards compatible with
// pre TIRAMISU versions of Android
@SuppressWarnings("deprecation")
private List<ResolveInfo> getCallAppsList(PackageManager pm) {
Intent callIntent = new Intent(Intent.ACTION_CALL);
callIntent.setData(Uri.parse("tel:123123"));
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.TIRAMISU) {
return pm.queryIntentActivities(callIntent, PackageManager.ResolveInfoFlags.of(0));
} else {
return pm.queryIntentActivities(callIntent, 0);
}
}
}
# Miscellaneous
*.class
*.log
*.pyc
*.swp
.DS_Store
.atom/
.buildlog/
.history
.svn/
# IntelliJ related
*.iml
*.ipr
*.iws
.idea/
# Visual Studio Code related
.vscode/
# Flutter/Dart/Pub related
**/doc/api/
.dart_tool/
.flutter-plugins
.flutter-plugins-dependencies
.packages
.pub-cache/
.pub/
build/
# Android related
**/android/**/gradle-wrapper.jar
**/android/.gradle
**/android/captures/
**/android/gradlew
**/android/gradlew.bat
**/android/local.properties
**/android/**/GeneratedPluginRegistrant.java
# iOS/XCode related
**/ios/**/*.mode1v3
**/ios/**/*.mode2v3
**/ios/**/*.moved-aside
**/ios/**/*.pbxuser
**/ios/**/*.perspectivev3
**/ios/**/*sync/
**/ios/**/.sconsign.dblite
**/ios/**/.tags*
**/ios/**/.vagrant/
**/ios/**/DerivedData/
**/ios/**/Icon?
**/ios/**/Pods/
**/ios/**/.symlinks/
**/ios/**/profile
**/ios/**/xcuserdata
**/ios/.generated/
**/ios/Flutter/App.framework
**/ios/Flutter/Flutter.framework
**/ios/Flutter/Generated.xcconfig
**/ios/Flutter/app.flx
**/ios/Flutter/app.zip
**/ios/Flutter/flutter_assets/
**/ios/ServiceDefinitions.json
**/ios/Runner/GeneratedPluginRegistrant.*
# Exceptions to above rules.
!**/ios/**/default.mode1v3
!**/ios/**/default.mode2v3
!**/ios/**/default.pbxuser
!**/ios/**/default.perspectivev3
!/packages/flutter_tools/test/data/dart_dependencies_test/**/.packages
# This file tracks properties of this Flutter project.
# Used by Flutter tool to assess capabilities and perform upgrades etc.
#
# This file should be version controlled and should not be manually edited.
version:
revision: 06b979c4d5e1b499745422269f01a00341257058
channel: master
project_type: app
# permission_handler_example
Demonstrates how to use the permission_handler plugin.
## Getting Started
This project is a starting point for a Flutter application.
A few resources to get you started if this is your first Flutter project:
- [Lab: Write your first Flutter app](https://flutter.io/docs/get-started/codelab)
- [Cookbook: Useful Flutter samples](https://flutter.io/docs/cookbook)
For help getting started with Flutter, view our
[online documentation](https://flutter.io/docs), which offers tutorials,
samples, guidance on mobile development, and a full API reference.
gradle-wrapper.jar
/.gradle
/captures/
/gradlew
/gradlew.bat
/local.properties
GeneratedPluginRegistrant.java
# Remember to never publicly share your keystore.
# See https://flutter.dev/docs/deployment/android#reference-the-keystore-from-the-app
key.properties
arguments=
auto.sync=false
build.scans.enabled=false
connection.gradle.distribution=GRADLE_DISTRIBUTION(WRAPPER)
connection.project.dir=
eclipse.preferences.version=1
gradle.user.home=
java.home=/Library/Java/JavaVirtualMachines/adoptopenjdk-11.jdk/Contents/Home
jvm.arguments=
offline.mode=false
override.workspace.settings=true
show.console.view=true
show.executions.view=true
def localProperties = new Properties()
def localPropertiesFile = rootProject.file('local.properties')
if (localPropertiesFile.exists()) {
localPropertiesFile.withReader('UTF-8') { reader ->
localProperties.load(reader)
}
}
def flutterRoot = localProperties.getProperty('flutter.sdk')
if (flutterRoot == null) {
throw new GradleException("Flutter SDK not found. Define location with flutter.sdk in the local.properties file.")
}
def flutterVersionCode = localProperties.getProperty('flutter.versionCode')
if (flutterVersionCode == null) {
flutterVersionCode = '1'
}
def flutterVersionName = localProperties.getProperty('flutter.versionName')
if (flutterVersionName == null) {
flutterVersionName = '1.0'
}
apply plugin: 'com.android.application'
apply from: "$flutterRoot/packages/flutter_tools/gradle/flutter.gradle"
android {
namespace 'com.baseflow.permissionhandler.example'
compileSdk 33
defaultConfig {
// TODO: Specify your own unique Application ID (https://developer.android.com/studio/build/application-id.html).
applicationId "com.baseflow.permissionhandler.example"
minSdkVersion flutter.minSdkVersion
targetSdkVersion flutter.targetSdkVersion
versionCode flutterVersionCode.toInteger()
versionName flutterVersionName
}
buildTypes {
release {
// TODO: Add your own signing config for the release build.
// Signing with the debug keys for now, so `flutter run --release` works.
signingConfig signingConfigs.debug
}
}
}
flutter {
source '../..'
}
<manifest xmlns:android="http://schemas.android.com/apk/res/android"
package="com.baseflow.permissionhandler.example">
<!-- Flutter needs it to communicate with the running application
to allow setting breakpoints, to provide hot reload, etc.
-->
<uses-permission android:name="android.permission.INTERNET"/>
</manifest>
<manifest xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:tools="http://schemas.android.com/tools"
package="com.baseflow.permissionhandler.example">
<uses-feature
android:name="android.hardware.telephony"
android:required="false" />
<uses-feature
android:name="android.hardware.camera"
android:required="false" />
<!--
Internet permissions do not affect the `permission_handler` plugin, but are required if your app needs access to
the internet.
-->
<uses-permission android:name="android.permission.INTERNET"/>
<!-- Permissions options for the `contacts` group -->
<uses-permission android:name="android.permission.READ_CONTACTS"/>
<uses-permission android:name="android.permission.WRITE_CONTACTS"/>
<uses-permission android:name="android.permission.GET_ACCOUNTS"/>
<!-- Permissions options for the `storage` group -->
<uses-permission android:name="android.permission.READ_EXTERNAL_STORAGE"/>
<uses-permission android:name="android.permission.WRITE_EXTERNAL_STORAGE"/>
<uses-permission android:name="android.permission.READ_MEDIA_IMAGES" />
<uses-permission android:name="android.permission.READ_MEDIA_VIDEO" />
<uses-permission android:name="android.permission.READ_MEDIA_AUDIO" />
<!-- Permissions options for the `camera` group -->
<uses-permission android:name="android.permission.CAMERA"/>
<!-- Permissions options for the `sms` group -->
<uses-permission android:name="android.permission.SEND_SMS"/>
<uses-permission android:name="android.permission.RECEIVE_SMS"/>
<uses-permission android:name="android.permission.READ_SMS"/>
<uses-permission android:name="android.permission.RECEIVE_WAP_PUSH"/>
<uses-permission android:name="android.permission.RECEIVE_MMS"/>
<!-- Permissions options for the `phone` group -->
<uses-permission android:name="android.permission.READ_PHONE_STATE"/>
<uses-permission android:name="android.permission.CALL_PHONE"/>
<uses-permission android:name="android.permission.ADD_VOICEMAIL"/>
<uses-permission android:name="android.permission.USE_SIP"/>
<uses-permission android:name="android.permission.READ_CALL_LOG"/>
<uses-permission android:name="android.permission.WRITE_CALL_LOG"/>
<!-- Permissions options for the `calendar` group -->
<uses-permission android:name="android.permission.READ_CALENDAR" />
<uses-permission android:name="android.permission.WRITE_CALENDAR" />
<!-- Permissions options for the `location` group -->
<uses-permission android:name="android.permission.ACCESS_FINE_LOCATION" />
<uses-permission android:name="android.permission.ACCESS_COARSE_LOCATION" />
<uses-permission android:name="android.permission.ACCESS_BACKGROUND_LOCATION" />
<!-- Permissions options for the `microphone` or `speech` group -->
<uses-permission android:name="android.permission.RECORD_AUDIO" />
<!-- Permissions options for the `sensors` group -->
<uses-permission android:name="android.permission.BODY_SENSORS" />
<uses-permission android:name="android.permission.BODY_SENSORS_BACKGROUND" />
<!-- Permissions options for the `accessMediaLocation` group -->
<uses-permission android:name="android.permission.ACCESS_MEDIA_LOCATION" />
<!-- Permissions options for the `activityRecognition` group -->
<uses-permission android:name="android.permission.ACTIVITY_RECOGNITION" />
<!-- Permissions options for the `ignoreBatteryOptimizations` group -->
<uses-permission android:name="android.permission.REQUEST_IGNORE_BATTERY_OPTIMIZATIONS" />
<!-- Permissions options for the `nearby devices` group -->
<uses-permission android:name="android.permission.BLUETOOTH" />
<uses-permission android:name="android.permission.BLUETOOTH_SCAN" />
<uses-permission android:name="android.permission.BLUETOOTH_ADVERTISE" />
<uses-permission android:name="android.permission.BLUETOOTH_CONNECT" />
<uses-permission android:name="android.permission.NEARBY_WIFI_DEVICES" />
<!-- Permissions options for the `manage external storage` group -->
<uses-permission android:name="android.permission.MANAGE_EXTERNAL_STORAGE" />
<!-- Permissions options for the `system alert windows` group -->
<uses-permission android:name="android.permission.SYSTEM_ALERT_WINDOW" />
<!-- Permissions options for the `request install packages` group -->
<uses-permission android:name="android.permission.REQUEST_INSTALL_PACKAGES" />
<!-- Permissions options for the `access notification policy` group -->
<uses-permission android:name="android.permission.ACCESS_NOTIFICATION_POLICY"/>
<!-- Permissions options for the `notification` group -->
<uses-permission android:name="android.permission.POST_NOTIFICATIONS"/>
<!-- Permissions options for the `alarm` group -->
<uses-permission android:name="android.permission.SCHEDULE_EXACT_ALARM" />
<application
android:name="${applicationName}"
android:icon="@mipmap/ic_launcher"
android:label="permission_handler_example"
tools:ignore="AllowBackup,GoogleAppIndexingWarning">
<activity android:name="io.flutter.embedding.android.FlutterActivity"
android:launchMode="singleTop"
android:theme="@android:style/Theme.Black.NoTitleBar"
android:configChanges="orientation|keyboardHidden|keyboard|screenSize|locale|layoutDirection"
android:hardwareAccelerated="true"
android:windowSoftInputMode="adjustResize"
android:exported="true">
<intent-filter>
<action android:name="android.intent.action.MAIN"/>
<category android:name="android.intent.category.LAUNCHER"/>
</intent-filter>
</activity>
<meta-data
android:name="flutterEmbedding"
android:value="2" />
</application>
</manifest>
package com.example.example
import io.flutter.embedding.android.FlutterActivity
class MainActivity: FlutterActivity() {
}
<?xml version="1.0" encoding="utf-8"?>
<!-- Modify this file to customize your launch splash screen -->
<layer-list xmlns:android="http://schemas.android.com/apk/res/android">
<item android:drawable="?android:colorBackground" />
<!-- You can insert your own image assets here -->
<!-- <item>
<bitmap
android:gravity="center"
android:src="@mipmap/launch_image" />
</item> -->
</layer-list>
<?xml version="1.0" encoding="utf-8"?>
<!-- Modify this file to customize your launch splash screen -->
<layer-list xmlns:android="http://schemas.android.com/apk/res/android">
<item android:drawable="@android:color/white" />
<!-- You can insert your own image assets here -->
<!-- <item>
<bitmap
android:gravity="center"
android:src="@mipmap/launch_image" />
</item> -->
</layer-list>
<?xml version="1.0" encoding="utf-8"?>
<resources>
<!-- Theme applied to the Android Window while the process is starting when the OS's Dark Mode setting is on -->
<style name="LaunchTheme" parent="@android:style/Theme.Black.NoTitleBar">
<!-- Show a splash screen on the activity. Automatically removed when
Flutter draws its first frame -->
<item name="android:windowBackground">@drawable/launch_background</item>
</style>
<!-- Theme applied to the Android Window as soon as the process has started.
This theme determines the color of the Android Window while your
Flutter UI initializes, as well as behind your Flutter UI while its
running.
This Theme is only used starting with V2 of Flutter's Android embedding. -->
<style name="NormalTheme" parent="@android:style/Theme.Black.NoTitleBar">
<item name="android:windowBackground">?android:colorBackground</item>
</style>
</resources>
<?xml version="1.0" encoding="utf-8"?>
<resources>
<style name="LaunchTheme" parent="@android:style/Theme.Black.NoTitleBar">
<!-- Show a splash screen on the activity. Automatically removed when
Flutter draws its first frame -->
<item name="android:windowBackground">@drawable/launch_background</item>
</style>
</resources>
<manifest xmlns:android="http://schemas.android.com/apk/res/android"
package="com.example.permissionhandlerexample">
<!-- Flutter needs it to communicate with the running application
to allow setting breakpoints, to provide hot reload, etc.
-->
<uses-permission android:name="android.permission.INTERNET"/>
<!-- Permissions options for the `contacts` group -->
<uses-permission android:name="android.permission.READ_CONTACTS"/>
<uses-permission android:name="android.permission.WRITE_CONTACTS"/>
<uses-permission android:name="android.permission.GET_ACCOUNTS"/>
<!-- Permissions options for the `storage` group -->
<uses-permission android:name="android.permission.READ_EXTERNAL_STORAGE"/>
<uses-permission android:name="android.permission.WRITE_EXTERNAL_STORAGE"/>
<!-- Permissions options for the `camera` group -->
<uses-permission android:name="android.permission.CAMERA"/>
<!-- Permissions options for the `sms` group -->
<uses-permission android:name="android.permission.SEND_SMS"/>
<uses-permission android:name="android.permission.RECEIVE_SMS"/>
<uses-permission android:name="android.permission.READ_SMS"/>
<uses-permission android:name="android.permission.RECEIVE_WAP_PUSH"/>
<uses-permission android:name="android.permission.RECEIVE_MMS"/>
<!-- Permissions options for the `phone` group -->
<uses-permission android:name="android.permission.READ_PHONE_STATE"/>
<uses-permission android:name="android.permission.CALL_PHONE"/>
<uses-permission android:name="android.permission.ADD_VOICEMAIL"/>
<uses-permission android:name="android.permission.USE_SIP"/>
<uses-permission android:name="android.permission.READ_CALL_LOG"/>
<uses-permission android:name="android.permission.WRITE_CALL_LOG"/>
<uses-permission android:name="android.permission.PROCESS_OUTGOING_CALLS"/>
<!-- Permissions options for the `calendar` group -->
<uses-permission android:name="android.permission.READ_CALENDAR" />
<uses-permission android:name="android.permission.WRITE_CALENDAR" />
<!-- Permissions options for the `location` group -->
<uses-permission android:name="android.permission.ACCESS_FINE_LOCATION" />
<uses-permission android:name="android.permission.ACCESS_COARSE_LOCATION" />
<!-- Permissions options for the `microphone` or `speech` group -->
<uses-permission android:name="android.permission.RECORD_AUDIO" />
<!-- Permissions options for the `sensors` group -->
<uses-permission android:name="android.permission.BODY_SENSORS" />
<uses-permission android:name="android.permission.BODY_SENSORS_BACKGROUND" />
<!-- Permissions options for the `access notification policy` group -->
<uses-permission android:name="android.permission.ACCESS_NOTIFICATION_POLICY"/>
</manifest>
buildscript {
repositories {
google()
mavenCentral()
}
dependencies {
classpath 'com.android.tools.build:gradle:7.4.2'
}
}
allprojects {
repositories {
google()
mavenCentral()
}
}
rootProject.buildDir = '../build'
subprojects {
project.buildDir = "${rootProject.buildDir}/${project.name}"
project.evaluationDependsOn(':app')
}
tasks.register("clean", Delete) {
delete rootProject.buildDir
}
// Build the plugin project with warnings enabled. This is here rather than
// in the plugin itself to avoid breaking clients that have different
// warnings (e.g., deprecation warnings from a newer SDK than this project
// builds with).
gradle.projectsEvaluated {
project(":permission_handler_android") {
tasks.withType(JavaCompile) {
options.compilerArgs << "-Xlint:all" << "-Werror"
}
}
}
org.gradle.jvmargs=-Xmx4G
android.useAndroidX=true
android.enableJetifier=true
#Fri Jun 23 08:50:38 CEST 2017
distributionBase=GRADLE_USER_HOME
distributionPath=wrapper/dists
zipStoreBase=GRADLE_USER_HOME
zipStorePath=wrapper/dists
distributionUrl=https\://services.gradle.org/distributions/gradle-7.6.3-all.zip
include ':app'
def flutterProjectRoot = rootProject.projectDir.parentFile.toPath()
def plugins = new Properties()
def pluginsFile = new File(flutterProjectRoot.toFile(), '.flutter-plugins')
if (pluginsFile.exists()) {
pluginsFile.withReader('UTF-8') { reader -> plugins.load(reader) }
}
plugins.each { name, path ->
def pluginDirectory = flutterProjectRoot.resolve(path).resolve('android').toFile()
include ":$name"
project(":$name").projectDir = pluginDirectory
}
import 'package:baseflow_plugin_template/baseflow_plugin_template.dart';
import 'package:flutter/material.dart';
import 'package:permission_handler_platform_interface/permission_handler_platform_interface.dart';
void main() {
runApp(BaseflowPluginExample(
pluginName: 'Permission Handler',
githubURL: 'https://github.com/Baseflow/flutter-permission-handler',
pubDevURL: 'https://pub.dev/packages/permission_handler',
pages: [PermissionHandlerWidget.createPage()]));
}
///Defines the main theme color
final MaterialColor themeMaterialColor =
BaseflowPluginExample.createMaterialColor(
const Color.fromRGBO(48, 49, 60, 1));
/// A Flutter application demonstrating the functionality of this plugin
class PermissionHandlerWidget extends StatefulWidget {
/// Create a page containing the functionality of this plugin
static ExamplePage createPage() {
return ExamplePage(
Icons.location_on, (context) => PermissionHandlerWidget());
}
@override
_PermissionHandlerWidgetState createState() =>
_PermissionHandlerWidgetState();
}
class _PermissionHandlerWidgetState extends State<PermissionHandlerWidget> {
@override
Widget build(BuildContext context) {
return Center(
child: ListView(
children: Permission.values
.where((permission) {
return permission != Permission.unknown &&
permission != Permission.mediaLibrary &&
permission != Permission.photosAddOnly &&
permission != Permission.reminders &&
permission != Permission.bluetooth &&
permission != Permission.appTrackingTransparency &&
permission != Permission.criticalAlerts &&
permission != Permission.assistant &&
permission != Permission.backgroundRefresh;
})
.map((permission) => PermissionWidget(permission))
.toList()),
);
}
}
/// Permission widget containing information about the passed [Permission]
class PermissionWidget extends StatefulWidget {
/// Constructs a [PermissionWidget] for the supplied [Permission]
const PermissionWidget(this._permission);
final Permission _permission;
@override
_PermissionState createState() => _PermissionState(_permission);
}
class _PermissionState extends State<PermissionWidget> {
_PermissionState(this._permission);
final Permission _permission;
final PermissionHandlerPlatform _permissionHandler =
PermissionHandlerPlatform.instance;
PermissionStatus _permissionStatus = PermissionStatus.denied;
@override
void initState() {
super.initState();
_listenForPermissionStatus();
}
void _listenForPermissionStatus() async {
final status = await _permissionHandler.checkPermissionStatus(_permission);
setState(() => _permissionStatus = status);
}
Color getPermissionColor() {
switch (_permissionStatus) {
case PermissionStatus.denied:
return Colors.red;
case PermissionStatus.granted:
return Colors.green;
case PermissionStatus.limited:
return Colors.orange;
default:
return Colors.grey;
}
}
@override
Widget build(BuildContext context) {
return ListTile(
title: Text(
_permission.toString(),
style: Theme.of(context).textTheme.bodyLarge,
),
subtitle: Text(
_permissionStatus.toString(),
style: TextStyle(color: getPermissionColor()),
),
trailing: (_permission is PermissionWithService)
? IconButton(
icon: const Icon(
Icons.info,
color: Colors.white,
),
onPressed: () {
checkServiceStatus(
context, _permission as PermissionWithService);
})
: null,
onTap: () {
requestPermission(_permission);
},
);
}
void checkServiceStatus(
BuildContext context, PermissionWithService permission) async {
ScaffoldMessenger.of(context).showSnackBar(SnackBar(
content: Text(
(await _permissionHandler.checkServiceStatus(permission)).toString()),
));
}
Future<void> requestPermission(Permission permission) async {
final status = await _permissionHandler.requestPermissions([permission]);
setState(() {
print(status);
_permissionStatus = status[permission] ?? PermissionStatus.denied;
print(_permissionStatus);
});
}
}
name: permission_handler_android_example
description: Demonstrates how to use the permission_handler_android plugin.
environment:
sdk: ">=2.15.0 <3.0.0"
dependencies:
baseflow_plugin_template: ^2.1.2
flutter:
sdk: flutter
dev_dependencies:
flutter_test:
sdk: flutter
permission_handler_android:
# When depending on this package from a real application you should use:
# permission_handler_android: ^x.y.z
# See https://dart.dev/tools/pub/dependencies#version-constraints
# The example app is bundled with the plugin so we use a path dependency on
# the parent directory to use the current plugin's version.
path: ../
url_launcher: ^6.0.12
flutter:
uses-material-design: true
assets:
- res/images/baseflow_logo_def_light-02.png
- res/images/poweredByBaseflowLogoLight@3x.png
name: permission_handler_android
description: Permission plugin for Flutter. This plugin provides the Android API to request and check permissions.
homepage: https://github.com/baseflow/flutter-permission-handler
version: 12.0.7
environment:
sdk: ">=2.15.0 <4.0.0"
flutter: ">=2.8.0"
flutter:
plugin:
implements: permission_handler
platforms:
android:
package: com.baseflow.permissionhandler
pluginClass: PermissionHandlerPlugin
dependencies:
flutter:
sdk: flutter
permission_handler_platform_interface: ^4.2.0
dev_dependencies:
flutter_lints: ^1.0.4
plugin_platform_interface: ^2.0.0
# Below is a list of people and organizations that have contributed
# to the Flutter project. Names should be added to the list like so:
#
# Name/Organization <email address>
Baseflow <hello@baseflow.com>
Maurits van Beusekom <maurits@baseflow.com>
Lukas Kurz <me@lukaskurz.com>
## 9.4.5
* Fixes issue #1002, Xcode warning of the unresponsive of main thread when checking isLocationEnabled.
## 9.4.4
* Fixes potentially-nil return type of EventPermissionStrategy#getEntityType.
* * Fixes typo in comment for full calendar access.
## 9.4.3
* Adds the `PERMISSION_LOCATION_WHENINUSE` macro, which can be used instead of
the `PERMISSION_LOCATION` macro, and exclusively enables the `requestWhenInUseAuthorization`
and remove the `requestAlwaysAuthorization` when requesting location permission.
* Improves error handling when `Info.plist` doesn't contain the correct declarations.
* Adds support for the `NSLocationAlwaysAndWhenInUseUsageDescription` property list
key.
## 9.4.2
* Updates the privacy manifest to include the use of the `NSUserDefaults` API.
The permission_handler stores a boolean value to track if permission to always
access the device location has been requested.
## 9.4.1
* Adds empty privacy manifest.
## 9.4.0
* Adds a new permission `Permission.backgroundRefresh` to check the background refresh permission status.
## 9.3.1
* Updates plist key from `NSPhotoLibraryUsageDescription` to `NSPhotoLibraryAddUsageDescription`.
## 9.3.0
* Adds support to request authorization to access SiriKit via the `Permission.assistant` permission.
## 9.2.0
* Adds the support for `Permission.calendarWriteOnly` and `Permission.calendarFullAccess` permissions which are introduced in iOS 17+.
## 9.1.4
* Adds checking whether Bluetooth service is enabled through `Permission.bluetooth.serviceStatus`.
## 9.1.3
* Fixes an issue where the `Permission.location.request()`, `Permission.locationWhenInUse.request()` and `Permission.locationAlways.request()` calls returned `PermissionStatus.denied` regardless of the actual permission status.
## 9.1.2
* Fixes an issue where the `Permission.locationAlways.request()` call hangs when the application was granted "Allow once" permissions for fetching location coordinates.
## 9.1.1
* Adds the new Android 13 permission "BODY_SENSORS_BACKGROUND" to PermissionHandlerEnums.h.
## 9.1.0
* Adds the "Provisional" permission status which is introduced in iOS 12+.
## 9.0.8
* Adds missing return statement causing the permission_handler to freeze when already requesting permissions.
## 9.0.7
* Adds new Android 13 permissions "SCHEDULE_EXACT_ALARM, READ_MEDIA_IMAGES, READ_MEDIA_VIDEO and READ_MEDIA_AUDIO" to PermissionHandlerEnums.h
## 9.0.6
* Prevents appearing popup that asks to turn on Bluetooth on iOS
## 9.0.5
* Adds new Android 13 NEARBY_WIFI_DEVICES permission to PermissionHandlerEnums.h
## 9.0.4
* Adds flag inside `UserDefaults` to save whether `locationAlways` has already been requested and prevent further requests, which would be left unanswered by the system.
## 9.0.3
* Ensures a request for `locationAlways` permission returns a result unblocking the permission request and preventing the `ERROR_ALREADY_REQUESTING_PERMISSIONS` error for subsequent permission requests.
## 9.0.2
* Moves Apple implementation into its own package.
MIT License
Copyright (c) 2018 Baseflow
Permission is hereby granted, free of charge, to any person obtaining a copy
of this software and associated documentation files (the "Software"), to deal
in the Software without restriction, including without limitation the rights
to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
copies of the Software, and to permit persons to whom the Software is
furnished to do so, subject to the following conditions:
The above copyright notice and this permission notice shall be included in all
copies or substantial portions of the Software.
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
SOFTWARE.
# permission_handler_apple
[![pub package](https://img.shields.io/pub/v/permission_handler_apple.svg)](https://pub.dartlang.org/packages/permission_handler_apple) ![Build status](https://github.com/Baseflow/flutter-permission-handler/workflows/permission_handler_apple/badge.svg?branch=master) [![style: flutter lints](https://img.shields.io/badge/style-flutter_lints-40c4ff.svg)](https://pub.dev/packages/flutter_lints)
The official iOS implementation of the [permission_handler](https://pub.dev/packages/permission_handler) plugin by [Baseflow](https://baseflow.com).
## Usage
Since version 9.1.0 of the [permission_handler](https://pub.dev/packages/permission_handler) plugin this is the endorsed iOS implementation. This means it will automatically be added to your dependencies when you depend on `permission_handler: ^9.1.0` in your applications pubspec.yaml.
More detailed instructions on using the API can be found in the [README.md](../permission_handler/README.md) of the [permission_handler](https://pub.dev/packages/permission_handler) package.
## Issues
Please file any issues, bugs, or feature requests as an issue on our [GitHub](https://github.com/Baseflow/flutter-permission-handler/issues) page. Commercial support is available, you can contact us at <hello@baseflow.com>.
## Want to contribute
If you would like to contribute to the plugin (e.g. by improving the documentation, solving a bug, or adding a cool new feature), please carefully review our [contribution guide](../CONTRIBUTING.md) and send us your [pull request](https://github.com/Baseflow/flutter-permission-handler/pulls).
## Author
This permission_handler plugin for Flutter is developed by [Baseflow](https://baseflow.com).
# Miscellaneous
*.class
*.log
*.pyc
*.swp
.DS_Store
.atom/
.buildlog/
.history
.svn/
# IntelliJ related
*.iml
*.ipr
*.iws
.idea/
# Visual Studio Code related
.vscode/
# Flutter/Dart/Pub related
**/doc/api/
.dart_tool/
.flutter-plugins
.flutter-plugins-dependencies
.packages
.pub-cache/
.pub/
build/
# Android related
**/android/**/gradle-wrapper.jar
**/android/.gradle
**/android/captures/
**/android/gradlew
**/android/gradlew.bat
**/android/local.properties
**/android/**/GeneratedPluginRegistrant.java
# iOS/XCode related
**/ios/**/*.mode1v3
**/ios/**/*.mode2v3
**/ios/**/*.moved-aside
**/ios/**/*.pbxuser
**/ios/**/*.perspectivev3
**/ios/**/*sync/
**/ios/**/.sconsign.dblite
**/ios/**/.tags*
**/ios/**/.vagrant/
**/ios/**/DerivedData/
**/ios/**/Icon?
**/ios/**/Pods/
**/ios/**/.symlinks/
**/ios/**/profile
**/ios/**/xcuserdata
**/ios/.generated/
**/ios/Flutter/App.framework
**/ios/Flutter/Flutter.framework
**/ios/Flutter/Generated.xcconfig
**/ios/Flutter/app.flx
**/ios/Flutter/app.zip
**/ios/Flutter/flutter_assets/
**/ios/ServiceDefinitions.json
**/ios/Runner/GeneratedPluginRegistrant.*
# Exceptions to above rules.
!**/ios/**/default.mode1v3
!**/ios/**/default.mode2v3
!**/ios/**/default.pbxuser
!**/ios/**/default.perspectivev3
!/packages/flutter_tools/test/data/dart_dependencies_test/**/.packages
# This file tracks properties of this Flutter project.
# Used by Flutter tool to assess capabilities and perform upgrades etc.
#
# This file should be version controlled and should not be manually edited.
version:
revision: 06b979c4d5e1b499745422269f01a00341257058
channel: master
project_type: app
# permission_handler_example
Demonstrates how to use the permission_handler plugin.
## Getting Started
This project is a starting point for a Flutter application.
A few resources to get you started if this is your first Flutter project:
- [Lab: Write your first Flutter app](https://flutter.io/docs/get-started/codelab)
- [Cookbook: Useful Flutter samples](https://flutter.io/docs/cookbook)
For help getting started with Flutter, view our
[online documentation](https://flutter.io/docs), which offers tutorials,
samples, guidance on mobile development, and a full API reference.
*.mode1v3
*.mode2v3
*.moved-aside
*.pbxuser
*.perspectivev3
**/*sync/
.sconsign.dblite
.tags*
**/.vagrant/
**/DerivedData/
Icon?
**/Pods/
**/.symlinks/
profile
xcuserdata
**/.generated/
Flutter/App.framework
Flutter/Flutter.framework
Flutter/Flutter.podspec
Flutter/Generated.xcconfig
Flutter/app.flx
Flutter/app.zip
Flutter/flutter_assets/
Flutter/flutter_export_environment.sh
ServiceDefinitions.json
Runner/GeneratedPluginRegistrant.*
# Exceptions to above rules.
!default.mode1v3
!default.mode2v3
!default.pbxuser
!default.perspectivev3
<?xml version="1.0" encoding="UTF-8"?>
<!DOCTYPE plist PUBLIC "-//Apple//DTD PLIST 1.0//EN" "http://www.apple.com/DTDs/PropertyList-1.0.dtd">
<plist version="1.0">
<dict>
<key>CFBundleDevelopmentRegion</key>
<string>en</string>
<key>CFBundleExecutable</key>
<string>App</string>
<key>CFBundleIdentifier</key>
<string>io.flutter.flutter.app</string>
<key>CFBundleInfoDictionaryVersion</key>
<string>6.0</string>
<key>CFBundleName</key>
<string>App</string>
<key>CFBundlePackageType</key>
<string>FMWK</string>
<key>CFBundleShortVersionString</key>
<string>1.0</string>
<key>CFBundleSignature</key>
<string>????</string>
<key>CFBundleVersion</key>
<string>1.0</string>
<key>MinimumOSVersion</key>
<string>12.0</string>
</dict>
</plist>
#include? "Pods/Target Support Files/Pods-Runner/Pods-Runner.debug.xcconfig"
#include "Generated.xcconfig"
#include? "Pods/Target Support Files/Pods-Runner/Pods-Runner.release.xcconfig"
#include "Generated.xcconfig"
# Uncomment this line to define a global platform for your project
# platform :ios, '12.0'
# CocoaPods analytics sends network stats synchronously affecting flutter build latency.
ENV['COCOAPODS_DISABLE_STATS'] = 'true'
project 'Runner', {
'Debug' => :debug,
'Profile' => :release,
'Release' => :release,
}
def flutter_root
generated_xcode_build_settings_path = File.expand_path(File.join('..', 'Flutter', 'Generated.xcconfig'), __FILE__)
unless File.exist?(generated_xcode_build_settings_path)
raise "#{generated_xcode_build_settings_path} must exist. If you're running pod install manually, make sure flutter pub get is executed first"
end
File.foreach(generated_xcode_build_settings_path) do |line|
matches = line.match(/FLUTTER_ROOT\=(.*)/)
return matches[1].strip if matches
end
raise "FLUTTER_ROOT not found in #{generated_xcode_build_settings_path}. Try deleting Generated.xcconfig, then run flutter pub get"
end
require File.expand_path(File.join('packages', 'flutter_tools', 'bin', 'podhelper'), flutter_root)
flutter_ios_podfile_setup
target 'Runner' do
use_frameworks!
use_modular_headers!
flutter_install_all_ios_pods File.dirname(File.realpath(__FILE__))
end
post_install do |installer|
installer.pods_project.targets.each do |target|
flutter_additional_ios_build_settings(target)
target.build_configurations.each do |config|
# You can remove unused permissions here
# for more information: https://github.com/BaseflowIT/flutter-permission-handler/blob/master/permission_handler/ios/Classes/PermissionHandlerEnums.h
# e.g. when you don't need camera permission, just add 'PERMISSION_CAMERA=0'
config.build_settings['GCC_PREPROCESSOR_DEFINITIONS'] ||= [
'$(inherited)',
## dart: PermissionGroup.calendar
'PERMISSION_EVENTS=1',
## dart: PermissionGroup.calendarFullAccess
'PERMISSION_EVENTS_FULL_ACCESS=1',
## dart: PermissionGroup.reminders
'PERMISSION_REMINDERS=1',
## dart: PermissionGroup.contacts
'PERMISSION_CONTACTS=1',
## dart: PermissionGroup.camera
'PERMISSION_CAMERA=1',
## dart: PermissionGroup.microphone
'PERMISSION_MICROPHONE=1',
## dart: PermissionGroup.speech
'PERMISSION_SPEECH_RECOGNIZER=1',
## dart: PermissionGroup.photos
'PERMISSION_PHOTOS=1',
## The 'PERMISSION_LOCATION' macro enables the `locationWhenInUse` and `locationAlways` permission. If
## the application only requires `locationWhenInUse`, only specify the `PERMISSION_LOCATION_WHENINUSE`
## macro.
##
## dart: [PermissionGroup.location, PermissionGroup.locationAlways, PermissionGroup.locationWhenInUse]
'PERMISSION_LOCATION=1',
'PERMISSION_LOCATION_WHENINUSE=0',
## dart: PermissionGroup.notification
'PERMISSION_NOTIFICATIONS=1',
## dart: PermissionGroup.mediaLibrary
'PERMISSION_MEDIA_LIBRARY=1',
## dart: PermissionGroup.sensors
'PERMISSION_SENSORS=1',
## dart: PermissionGroup.bluetooth
'PERMISSION_BLUETOOTH=1',
## dart: PermissionGroup.appTrackingTransparency
'PERMISSION_APP_TRACKING_TRANSPARENCY=1',
## dart: PermissionGroup.criticalAlerts
'PERMISSION_CRITICAL_ALERTS=1',
## dart: PermissionGroup.criticalAlerts
'PERMISSION_ASSISTANT=1',
]
end
end
end
// !$*UTF8*$!
{
archiveVersion = 1;
classes = {
};
objectVersion = 54;
objects = {
/* Begin PBXBuildFile section */
1498D2341E8E89220040F4C2 /* GeneratedPluginRegistrant.m in Sources */ = {isa = PBXBuildFile; fileRef = 1498D2331E8E89220040F4C2 /* GeneratedPluginRegistrant.m */; };
3B3967161E833CAA004F5970 /* AppFrameworkInfo.plist in Resources */ = {isa = PBXBuildFile; fileRef = 3B3967151E833CAA004F5970 /* AppFrameworkInfo.plist */; };
74858FAF1ED2DC5600515810 /* AppDelegate.swift in Sources */ = {isa = PBXBuildFile; fileRef = 74858FAE1ED2DC5600515810 /* AppDelegate.swift */; };
97C146FC1CF9000F007C117D /* Main.storyboard in Resources */ = {isa = PBXBuildFile; fileRef = 97C146FA1CF9000F007C117D /* Main.storyboard */; };
97C146FE1CF9000F007C117D /* Assets.xcassets in Resources */ = {isa = PBXBuildFile; fileRef = 97C146FD1CF9000F007C117D /* Assets.xcassets */; };
97C147011CF9000F007C117D /* LaunchScreen.storyboard in Resources */ = {isa = PBXBuildFile; fileRef = 97C146FF1CF9000F007C117D /* LaunchScreen.storyboard */; };
B501E7F22BA22C455255CE2E /* Pods_Runner.framework in Frameworks */ = {isa = PBXBuildFile; fileRef = C446183715B92022DDB68882 /* Pods_Runner.framework */; };
/* End PBXBuildFile section */
/* Begin PBXCopyFilesBuildPhase section */
9705A1C41CF9048500538489 /* Embed Frameworks */ = {
isa = PBXCopyFilesBuildPhase;
buildActionMask = 2147483647;
dstPath = "";
dstSubfolderSpec = 10;
files = (
);
name = "Embed Frameworks";
runOnlyForDeploymentPostprocessing = 0;
};
/* End PBXCopyFilesBuildPhase section */
/* Begin PBXFileReference section */
1498D2321E8E86230040F4C2 /* GeneratedPluginRegistrant.h */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.c.h; path = GeneratedPluginRegistrant.h; sourceTree = "<group>"; };
1498D2331E8E89220040F4C2 /* GeneratedPluginRegistrant.m */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.c.objc; path = GeneratedPluginRegistrant.m; sourceTree = "<group>"; };
3B3967151E833CAA004F5970 /* AppFrameworkInfo.plist */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = text.plist.xml; name = AppFrameworkInfo.plist; path = Flutter/AppFrameworkInfo.plist; sourceTree = "<group>"; };
74858FAD1ED2DC5600515810 /* Runner-Bridging-Header.h */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.c.h; path = "Runner-Bridging-Header.h"; sourceTree = "<group>"; };
74858FAE1ED2DC5600515810 /* AppDelegate.swift */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.swift; path = AppDelegate.swift; sourceTree = "<group>"; };
7AFA3C8E1D35360C0083082E /* Release.xcconfig */ = {isa = PBXFileReference; lastKnownFileType = text.xcconfig; name = Release.xcconfig; path = Flutter/Release.xcconfig; sourceTree = "<group>"; };
862A53EA392D32566500E869 /* Pods-Runner.release.xcconfig */ = {isa = PBXFileReference; includeInIndex = 1; lastKnownFileType = text.xcconfig; name = "Pods-Runner.release.xcconfig"; path = "Target Support Files/Pods-Runner/Pods-Runner.release.xcconfig"; sourceTree = "<group>"; };
9740EEB21CF90195004384FC /* Debug.xcconfig */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = text.xcconfig; name = Debug.xcconfig; path = Flutter/Debug.xcconfig; sourceTree = "<group>"; };
9740EEB31CF90195004384FC /* Generated.xcconfig */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = text.xcconfig; name = Generated.xcconfig; path = Flutter/Generated.xcconfig; sourceTree = "<group>"; };
97C146EE1CF9000F007C117D /* Runner.app */ = {isa = PBXFileReference; explicitFileType = wrapper.application; includeInIndex = 0; path = Runner.app; sourceTree = BUILT_PRODUCTS_DIR; };
97C146FB1CF9000F007C117D /* Base */ = {isa = PBXFileReference; lastKnownFileType = file.storyboard; name = Base; path = Base.lproj/Main.storyboard; sourceTree = "<group>"; };
97C146FD1CF9000F007C117D /* Assets.xcassets */ = {isa = PBXFileReference; lastKnownFileType = folder.assetcatalog; path = Assets.xcassets; sourceTree = "<group>"; };
97C147001CF9000F007C117D /* Base */ = {isa = PBXFileReference; lastKnownFileType = file.storyboard; name = Base; path = Base.lproj/LaunchScreen.storyboard; sourceTree = "<group>"; };
97C147021CF9000F007C117D /* Info.plist */ = {isa = PBXFileReference; lastKnownFileType = text.plist.xml; path = Info.plist; sourceTree = "<group>"; };
C446183715B92022DDB68882 /* Pods_Runner.framework */ = {isa = PBXFileReference; explicitFileType = wrapper.framework; includeInIndex = 0; path = Pods_Runner.framework; sourceTree = BUILT_PRODUCTS_DIR; };
CEA40B36DE135D81D16B7399 /* Pods-Runner.debug.xcconfig */ = {isa = PBXFileReference; includeInIndex = 1; lastKnownFileType = text.xcconfig; name = "Pods-Runner.debug.xcconfig"; path = "Target Support Files/Pods-Runner/Pods-Runner.debug.xcconfig"; sourceTree = "<group>"; };
DA7CB50DE8057A7A8D126AC9 /* Pods-Runner.profile.xcconfig */ = {isa = PBXFileReference; includeInIndex = 1; lastKnownFileType = text.xcconfig; name = "Pods-Runner.profile.xcconfig"; path = "Target Support Files/Pods-Runner/Pods-Runner.profile.xcconfig"; sourceTree = "<group>"; };
F6BD02742B56D78D00C59EAA /* RunnerDebug.entitlements */ = {isa = PBXFileReference; lastKnownFileType = text.plist.entitlements; path = RunnerDebug.entitlements; sourceTree = "<group>"; };
/* End PBXFileReference section */
/* Begin PBXFrameworksBuildPhase section */
97C146EB1CF9000F007C117D /* Frameworks */ = {
isa = PBXFrameworksBuildPhase;
buildActionMask = 2147483647;
files = (
B501E7F22BA22C455255CE2E /* Pods_Runner.framework in Frameworks */,
);
runOnlyForDeploymentPostprocessing = 0;
};
/* End PBXFrameworksBuildPhase section */
/* Begin PBXGroup section */
2982F40ECD3DD26A4434B596 /* Pods */ = {
isa = PBXGroup;
children = (
CEA40B36DE135D81D16B7399 /* Pods-Runner.debug.xcconfig */,
862A53EA392D32566500E869 /* Pods-Runner.release.xcconfig */,
DA7CB50DE8057A7A8D126AC9 /* Pods-Runner.profile.xcconfig */,
);
path = Pods;
sourceTree = "<group>";
};
7EF8E4A69F95E4BF7F747BE9 /* Frameworks */ = {
isa = PBXGroup;
children = (
C446183715B92022DDB68882 /* Pods_Runner.framework */,
);
name = Frameworks;
sourceTree = "<group>";
};
9740EEB11CF90186004384FC /* Flutter */ = {
isa = PBXGroup;
children = (
3B3967151E833CAA004F5970 /* AppFrameworkInfo.plist */,
9740EEB21CF90195004384FC /* Debug.xcconfig */,
7AFA3C8E1D35360C0083082E /* Release.xcconfig */,
9740EEB31CF90195004384FC /* Generated.xcconfig */,
);
name = Flutter;
sourceTree = "<group>";
};
97C146E51CF9000F007C117D = {
isa = PBXGroup;
children = (
9740EEB11CF90186004384FC /* Flutter */,
97C146F01CF9000F007C117D /* Runner */,
97C146EF1CF9000F007C117D /* Products */,
2982F40ECD3DD26A4434B596 /* Pods */,
7EF8E4A69F95E4BF7F747BE9 /* Frameworks */,
);
sourceTree = "<group>";
};
97C146EF1CF9000F007C117D /* Products */ = {
isa = PBXGroup;
children = (
97C146EE1CF9000F007C117D /* Runner.app */,
);
name = Products;
sourceTree = "<group>";
};
97C146F01CF9000F007C117D /* Runner */ = {
isa = PBXGroup;
children = (
F6BD02742B56D78D00C59EAA /* RunnerDebug.entitlements */,
97C146FA1CF9000F007C117D /* Main.storyboard */,
97C146FD1CF9000F007C117D /* Assets.xcassets */,
97C146FF1CF9000F007C117D /* LaunchScreen.storyboard */,
97C147021CF9000F007C117D /* Info.plist */,
1498D2321E8E86230040F4C2 /* GeneratedPluginRegistrant.h */,
1498D2331E8E89220040F4C2 /* GeneratedPluginRegistrant.m */,
74858FAE1ED2DC5600515810 /* AppDelegate.swift */,
74858FAD1ED2DC5600515810 /* Runner-Bridging-Header.h */,
);
path = Runner;
sourceTree = "<group>";
};
/* End PBXGroup section */
/* Begin PBXNativeTarget section */
97C146ED1CF9000F007C117D /* Runner */ = {
isa = PBXNativeTarget;
buildConfigurationList = 97C147051CF9000F007C117D /* Build configuration list for PBXNativeTarget "Runner" */;
buildPhases = (
5CF31A8C72B66ABB365E813D /* [CP] Check Pods Manifest.lock */,
9740EEB61CF901F6004384FC /* Run Script */,
97C146EA1CF9000F007C117D /* Sources */,
97C146EB1CF9000F007C117D /* Frameworks */,
97C146EC1CF9000F007C117D /* Resources */,
9705A1C41CF9048500538489 /* Embed Frameworks */,
3B06AD1E1E4923F5004D2608 /* Thin Binary */,
D38B08CB85942E5D11545EE3 /* [CP] Embed Pods Frameworks */,
A7B07F67421488A414C73AAD /* [CP] Copy Pods Resources */,
);
buildRules = (
);
dependencies = (
);
name = Runner;
productName = Runner;
productReference = 97C146EE1CF9000F007C117D /* Runner.app */;
productType = "com.apple.product-type.application";
};
/* End PBXNativeTarget section */
/* Begin PBXProject section */
97C146E61CF9000F007C117D /* Project object */ = {
isa = PBXProject;
attributes = {
LastUpgradeCheck = 1510;
ORGANIZATIONNAME = "";
TargetAttributes = {
97C146ED1CF9000F007C117D = {
CreatedOnToolsVersion = 7.3.1;
LastSwiftMigration = 1100;
};
};
};
buildConfigurationList = 97C146E91CF9000F007C117D /* Build configuration list for PBXProject "Runner" */;
compatibilityVersion = "Xcode 9.3";
developmentRegion = en;
hasScannedForEncodings = 0;
knownRegions = (
en,
Base,
);
mainGroup = 97C146E51CF9000F007C117D;
productRefGroup = 97C146EF1CF9000F007C117D /* Products */;
projectDirPath = "";
projectRoot = "";
targets = (
97C146ED1CF9000F007C117D /* Runner */,
);
};
/* End PBXProject section */
/* Begin PBXResourcesBuildPhase section */
97C146EC1CF9000F007C117D /* Resources */ = {
isa = PBXResourcesBuildPhase;
buildActionMask = 2147483647;
files = (
97C147011CF9000F007C117D /* LaunchScreen.storyboard in Resources */,
3B3967161E833CAA004F5970 /* AppFrameworkInfo.plist in Resources */,
97C146FE1CF9000F007C117D /* Assets.xcassets in Resources */,
97C146FC1CF9000F007C117D /* Main.storyboard in Resources */,
);
runOnlyForDeploymentPostprocessing = 0;
};
/* End PBXResourcesBuildPhase section */
/* Begin PBXShellScriptBuildPhase section */
3B06AD1E1E4923F5004D2608 /* Thin Binary */ = {
isa = PBXShellScriptBuildPhase;
alwaysOutOfDate = 1;
buildActionMask = 2147483647;
files = (
);
inputPaths = (
"${TARGET_BUILD_DIR}/${INFOPLIST_PATH}",
);
name = "Thin Binary";
outputPaths = (
);
runOnlyForDeploymentPostprocessing = 0;
shellPath = /bin/sh;
shellScript = "/bin/sh \"$FLUTTER_ROOT/packages/flutter_tools/bin/xcode_backend.sh\" embed_and_thin";
};
5CF31A8C72B66ABB365E813D /* [CP] Check Pods Manifest.lock */ = {
isa = PBXShellScriptBuildPhase;
buildActionMask = 2147483647;
files = (
);
inputFileListPaths = (
);
inputPaths = (
"${PODS_PODFILE_DIR_PATH}/Podfile.lock",
"${PODS_ROOT}/Manifest.lock",
);
name = "[CP] Check Pods Manifest.lock";
outputFileListPaths = (
);
outputPaths = (
"$(DERIVED_FILE_DIR)/Pods-Runner-checkManifestLockResult.txt",
);
runOnlyForDeploymentPostprocessing = 0;
shellPath = /bin/sh;
shellScript = "diff \"${PODS_PODFILE_DIR_PATH}/Podfile.lock\" \"${PODS_ROOT}/Manifest.lock\" > /dev/null\nif [ $? != 0 ] ; then\n # print error to STDERR\n echo \"error: The sandbox is not in sync with the Podfile.lock. Run 'pod install' or update your CocoaPods installation.\" >&2\n exit 1\nfi\n# This output is used by Xcode 'outputs' to avoid re-running this script phase.\necho \"SUCCESS\" > \"${SCRIPT_OUTPUT_FILE_0}\"\n";
showEnvVarsInLog = 0;
};
9740EEB61CF901F6004384FC /* Run Script */ = {
isa = PBXShellScriptBuildPhase;
alwaysOutOfDate = 1;
buildActionMask = 2147483647;
files = (
);
inputPaths = (
);
name = "Run Script";
outputPaths = (
);
runOnlyForDeploymentPostprocessing = 0;
shellPath = /bin/sh;
shellScript = "/bin/sh \"$FLUTTER_ROOT/packages/flutter_tools/bin/xcode_backend.sh\" build";
};
A7B07F67421488A414C73AAD /* [CP] Copy Pods Resources */ = {
isa = PBXShellScriptBuildPhase;
buildActionMask = 2147483647;
files = (
);
inputFileListPaths = (
"${PODS_ROOT}/Target Support Files/Pods-Runner/Pods-Runner-resources-${CONFIGURATION}-input-files.xcfilelist",
);
name = "[CP] Copy Pods Resources";
outputFileListPaths = (
"${PODS_ROOT}/Target Support Files/Pods-Runner/Pods-Runner-resources-${CONFIGURATION}-output-files.xcfilelist",
);
runOnlyForDeploymentPostprocessing = 0;
shellPath = /bin/sh;
shellScript = "\"${PODS_ROOT}/Target Support Files/Pods-Runner/Pods-Runner-resources.sh\"\n";
showEnvVarsInLog = 0;
};
D38B08CB85942E5D11545EE3 /* [CP] Embed Pods Frameworks */ = {
isa = PBXShellScriptBuildPhase;
buildActionMask = 2147483647;
files = (
);
inputFileListPaths = (
"${PODS_ROOT}/Target Support Files/Pods-Runner/Pods-Runner-frameworks-${CONFIGURATION}-input-files.xcfilelist",
);
name = "[CP] Embed Pods Frameworks";
outputFileListPaths = (
"${PODS_ROOT}/Target Support Files/Pods-Runner/Pods-Runner-frameworks-${CONFIGURATION}-output-files.xcfilelist",
);
runOnlyForDeploymentPostprocessing = 0;
shellPath = /bin/sh;
shellScript = "\"${PODS_ROOT}/Target Support Files/Pods-Runner/Pods-Runner-frameworks.sh\"\n";
showEnvVarsInLog = 0;
};
/* End PBXShellScriptBuildPhase section */
/* Begin PBXSourcesBuildPhase section */
97C146EA1CF9000F007C117D /* Sources */ = {
isa = PBXSourcesBuildPhase;
buildActionMask = 2147483647;
files = (
74858FAF1ED2DC5600515810 /* AppDelegate.swift in Sources */,
1498D2341E8E89220040F4C2 /* GeneratedPluginRegistrant.m in Sources */,
);
runOnlyForDeploymentPostprocessing = 0;
};
/* End PBXSourcesBuildPhase section */
/* Begin PBXVariantGroup section */
97C146FA1CF9000F007C117D /* Main.storyboard */ = {
isa = PBXVariantGroup;
children = (
97C146FB1CF9000F007C117D /* Base */,
);
name = Main.storyboard;
sourceTree = "<group>";
};
97C146FF1CF9000F007C117D /* LaunchScreen.storyboard */ = {
isa = PBXVariantGroup;
children = (
97C147001CF9000F007C117D /* Base */,
);
name = LaunchScreen.storyboard;
sourceTree = "<group>";
};
/* End PBXVariantGroup section */
/* Begin XCBuildConfiguration section */
249021D3217E4FDB00AE95B9 /* Profile */ = {
isa = XCBuildConfiguration;
buildSettings = {
ALWAYS_SEARCH_USER_PATHS = NO;
CLANG_ANALYZER_NONNULL = YES;
CLANG_CXX_LANGUAGE_STANDARD = "gnu++0x";
CLANG_CXX_LIBRARY = "libc++";
CLANG_ENABLE_MODULES = YES;
CLANG_ENABLE_OBJC_ARC = YES;
CLANG_WARN_BLOCK_CAPTURE_AUTORELEASING = YES;
CLANG_WARN_BOOL_CONVERSION = YES;
CLANG_WARN_COMMA = YES;
CLANG_WARN_CONSTANT_CONVERSION = YES;
CLANG_WARN_DEPRECATED_OBJC_IMPLEMENTATIONS = YES;
CLANG_WARN_DIRECT_OBJC_ISA_USAGE = YES_ERROR;
CLANG_WARN_EMPTY_BODY = YES;
CLANG_WARN_ENUM_CONVERSION = YES;
CLANG_WARN_INFINITE_RECURSION = YES;
CLANG_WARN_INT_CONVERSION = YES;
CLANG_WARN_NON_LITERAL_NULL_CONVERSION = YES;
CLANG_WARN_OBJC_IMPLICIT_RETAIN_SELF = YES;
CLANG_WARN_OBJC_LITERAL_CONVERSION = YES;
CLANG_WARN_OBJC_ROOT_CLASS = YES_ERROR;
CLANG_WARN_RANGE_LOOP_ANALYSIS = YES;
CLANG_WARN_STRICT_PROTOTYPES = YES;
CLANG_WARN_SUSPICIOUS_MOVE = YES;
CLANG_WARN_UNREACHABLE_CODE = YES;
CLANG_WARN__DUPLICATE_METHOD_MATCH = YES;
"CODE_SIGN_IDENTITY[sdk=iphoneos*]" = "iPhone Developer";
COPY_PHASE_STRIP = NO;
DEBUG_INFORMATION_FORMAT = "dwarf-with-dsym";
ENABLE_NS_ASSERTIONS = NO;
ENABLE_STRICT_OBJC_MSGSEND = YES;
GCC_C_LANGUAGE_STANDARD = gnu99;
GCC_NO_COMMON_BLOCKS = YES;
GCC_WARN_64_TO_32_BIT_CONVERSION = YES;
GCC_WARN_ABOUT_RETURN_TYPE = YES_ERROR;
GCC_WARN_UNDECLARED_SELECTOR = YES;
GCC_WARN_UNINITIALIZED_AUTOS = YES_AGGRESSIVE;
GCC_WARN_UNUSED_FUNCTION = YES;
GCC_WARN_UNUSED_VARIABLE = YES;
IPHONEOS_DEPLOYMENT_TARGET = 12.0;
MTL_ENABLE_DEBUG_INFO = NO;
SDKROOT = iphoneos;
SUPPORTED_PLATFORMS = iphoneos;
TARGETED_DEVICE_FAMILY = "1,2";
VALIDATE_PRODUCT = YES;
};
name = Profile;
};
249021D4217E4FDB00AE95B9 /* Profile */ = {
isa = XCBuildConfiguration;
baseConfigurationReference = 7AFA3C8E1D35360C0083082E /* Release.xcconfig */;
buildSettings = {
ASSETCATALOG_COMPILER_APPICON_NAME = AppIcon;
CLANG_ENABLE_MODULES = YES;
CURRENT_PROJECT_VERSION = "$(FLUTTER_BUILD_NUMBER)";
DEVELOPMENT_TEAM = 7624MWN53C;
ENABLE_BITCODE = NO;
FRAMEWORK_SEARCH_PATHS = (
"$(inherited)",
"$(PROJECT_DIR)/Flutter",
);
INFOPLIST_FILE = Runner/Info.plist;
LD_RUNPATH_SEARCH_PATHS = (
"$(inherited)",
"@executable_path/Frameworks",
);
LIBRARY_SEARCH_PATHS = (
"$(inherited)",
"$(PROJECT_DIR)/Flutter",
);
PRODUCT_BUNDLE_IDENTIFIER = com.example.example;
PRODUCT_NAME = "$(TARGET_NAME)";
SWIFT_OBJC_BRIDGING_HEADER = "Runner/Runner-Bridging-Header.h";
SWIFT_VERSION = 5.0;
VERSIONING_SYSTEM = "apple-generic";
};
name = Profile;
};
97C147031CF9000F007C117D /* Debug */ = {
isa = XCBuildConfiguration;
buildSettings = {
ALWAYS_SEARCH_USER_PATHS = NO;
CLANG_ANALYZER_NONNULL = YES;
CLANG_CXX_LANGUAGE_STANDARD = "gnu++0x";
CLANG_CXX_LIBRARY = "libc++";
CLANG_ENABLE_MODULES = YES;
CLANG_ENABLE_OBJC_ARC = YES;
CLANG_WARN_BLOCK_CAPTURE_AUTORELEASING = YES;
CLANG_WARN_BOOL_CONVERSION = YES;
CLANG_WARN_COMMA = YES;
CLANG_WARN_CONSTANT_CONVERSION = YES;
CLANG_WARN_DEPRECATED_OBJC_IMPLEMENTATIONS = YES;
CLANG_WARN_DIRECT_OBJC_ISA_USAGE = YES_ERROR;
CLANG_WARN_EMPTY_BODY = YES;
CLANG_WARN_ENUM_CONVERSION = YES;
CLANG_WARN_INFINITE_RECURSION = YES;
CLANG_WARN_INT_CONVERSION = YES;
CLANG_WARN_NON_LITERAL_NULL_CONVERSION = YES;
CLANG_WARN_OBJC_IMPLICIT_RETAIN_SELF = YES;
CLANG_WARN_OBJC_LITERAL_CONVERSION = YES;
CLANG_WARN_OBJC_ROOT_CLASS = YES_ERROR;
CLANG_WARN_RANGE_LOOP_ANALYSIS = YES;
CLANG_WARN_STRICT_PROTOTYPES = YES;
CLANG_WARN_SUSPICIOUS_MOVE = YES;
CLANG_WARN_UNREACHABLE_CODE = YES;
CLANG_WARN__DUPLICATE_METHOD_MATCH = YES;
"CODE_SIGN_IDENTITY[sdk=iphoneos*]" = "iPhone Developer";
COPY_PHASE_STRIP = NO;
DEBUG_INFORMATION_FORMAT = dwarf;
ENABLE_STRICT_OBJC_MSGSEND = YES;
ENABLE_TESTABILITY = YES;
GCC_C_LANGUAGE_STANDARD = gnu99;
GCC_DYNAMIC_NO_PIC = NO;
GCC_NO_COMMON_BLOCKS = YES;
GCC_OPTIMIZATION_LEVEL = 0;
GCC_PREPROCESSOR_DEFINITIONS = (
"DEBUG=1",
"$(inherited)",
);
GCC_WARN_64_TO_32_BIT_CONVERSION = YES;
GCC_WARN_ABOUT_RETURN_TYPE = YES_ERROR;
GCC_WARN_UNDECLARED_SELECTOR = YES;
GCC_WARN_UNINITIALIZED_AUTOS = YES_AGGRESSIVE;
GCC_WARN_UNUSED_FUNCTION = YES;
GCC_WARN_UNUSED_VARIABLE = YES;
IPHONEOS_DEPLOYMENT_TARGET = 12.0;
MTL_ENABLE_DEBUG_INFO = YES;
ONLY_ACTIVE_ARCH = YES;
SDKROOT = iphoneos;
TARGETED_DEVICE_FAMILY = "1,2";
};
name = Debug;
};
97C147041CF9000F007C117D /* Release */ = {
isa = XCBuildConfiguration;
buildSettings = {
ALWAYS_SEARCH_USER_PATHS = NO;
CLANG_ANALYZER_NONNULL = YES;
CLANG_CXX_LANGUAGE_STANDARD = "gnu++0x";
CLANG_CXX_LIBRARY = "libc++";
CLANG_ENABLE_MODULES = YES;
CLANG_ENABLE_OBJC_ARC = YES;
CLANG_WARN_BLOCK_CAPTURE_AUTORELEASING = YES;
CLANG_WARN_BOOL_CONVERSION = YES;
CLANG_WARN_COMMA = YES;
CLANG_WARN_CONSTANT_CONVERSION = YES;
CLANG_WARN_DEPRECATED_OBJC_IMPLEMENTATIONS = YES;
CLANG_WARN_DIRECT_OBJC_ISA_USAGE = YES_ERROR;
CLANG_WARN_EMPTY_BODY = YES;
CLANG_WARN_ENUM_CONVERSION = YES;
CLANG_WARN_INFINITE_RECURSION = YES;
CLANG_WARN_INT_CONVERSION = YES;
CLANG_WARN_NON_LITERAL_NULL_CONVERSION = YES;
CLANG_WARN_OBJC_IMPLICIT_RETAIN_SELF = YES;
CLANG_WARN_OBJC_LITERAL_CONVERSION = YES;
CLANG_WARN_OBJC_ROOT_CLASS = YES_ERROR;
CLANG_WARN_RANGE_LOOP_ANALYSIS = YES;
CLANG_WARN_STRICT_PROTOTYPES = YES;
CLANG_WARN_SUSPICIOUS_MOVE = YES;
CLANG_WARN_UNREACHABLE_CODE = YES;
CLANG_WARN__DUPLICATE_METHOD_MATCH = YES;
"CODE_SIGN_IDENTITY[sdk=iphoneos*]" = "iPhone Developer";
COPY_PHASE_STRIP = NO;
DEBUG_INFORMATION_FORMAT = "dwarf-with-dsym";
ENABLE_NS_ASSERTIONS = NO;
ENABLE_STRICT_OBJC_MSGSEND = YES;
GCC_C_LANGUAGE_STANDARD = gnu99;
GCC_NO_COMMON_BLOCKS = YES;
GCC_WARN_64_TO_32_BIT_CONVERSION = YES;
GCC_WARN_ABOUT_RETURN_TYPE = YES_ERROR;
GCC_WARN_UNDECLARED_SELECTOR = YES;
GCC_WARN_UNINITIALIZED_AUTOS = YES_AGGRESSIVE;
GCC_WARN_UNUSED_FUNCTION = YES;
GCC_WARN_UNUSED_VARIABLE = YES;
IPHONEOS_DEPLOYMENT_TARGET = 12.0;
MTL_ENABLE_DEBUG_INFO = NO;
SDKROOT = iphoneos;
SUPPORTED_PLATFORMS = iphoneos;
SWIFT_COMPILATION_MODE = wholemodule;
SWIFT_OPTIMIZATION_LEVEL = "-O";
TARGETED_DEVICE_FAMILY = "1,2";
VALIDATE_PRODUCT = YES;
};
name = Release;
};
97C147061CF9000F007C117D /* Debug */ = {
isa = XCBuildConfiguration;
baseConfigurationReference = 9740EEB21CF90195004384FC /* Debug.xcconfig */;
buildSettings = {
ASSETCATALOG_COMPILER_APPICON_NAME = AppIcon;
CLANG_ENABLE_MODULES = YES;
CODE_SIGN_ENTITLEMENTS = Runner/RunnerDebug.entitlements;
CURRENT_PROJECT_VERSION = "$(FLUTTER_BUILD_NUMBER)";
DEVELOPMENT_TEAM = 7624MWN53C;
ENABLE_BITCODE = NO;
FRAMEWORK_SEARCH_PATHS = (
"$(inherited)",
"$(PROJECT_DIR)/Flutter",
);
INFOPLIST_FILE = Runner/Info.plist;
LD_RUNPATH_SEARCH_PATHS = (
"$(inherited)",
"@executable_path/Frameworks",
);
LIBRARY_SEARCH_PATHS = (
"$(inherited)",
"$(PROJECT_DIR)/Flutter",
);
PRODUCT_BUNDLE_IDENTIFIER = com.example.example;
PRODUCT_NAME = "$(TARGET_NAME)";
SWIFT_OBJC_BRIDGING_HEADER = "Runner/Runner-Bridging-Header.h";
SWIFT_OPTIMIZATION_LEVEL = "-Onone";
SWIFT_VERSION = 5.0;
VERSIONING_SYSTEM = "apple-generic";
};
name = Debug;
};
97C147071CF9000F007C117D /* Release */ = {
isa = XCBuildConfiguration;
baseConfigurationReference = 7AFA3C8E1D35360C0083082E /* Release.xcconfig */;
buildSettings = {
ASSETCATALOG_COMPILER_APPICON_NAME = AppIcon;
CLANG_ENABLE_MODULES = YES;
CURRENT_PROJECT_VERSION = "$(FLUTTER_BUILD_NUMBER)";
DEVELOPMENT_TEAM = 7624MWN53C;
ENABLE_BITCODE = NO;
FRAMEWORK_SEARCH_PATHS = (
"$(inherited)",
"$(PROJECT_DIR)/Flutter",
);
INFOPLIST_FILE = Runner/Info.plist;
LD_RUNPATH_SEARCH_PATHS = (
"$(inherited)",
"@executable_path/Frameworks",
);
LIBRARY_SEARCH_PATHS = (
"$(inherited)",
"$(PROJECT_DIR)/Flutter",
);
PRODUCT_BUNDLE_IDENTIFIER = com.example.example;
PRODUCT_NAME = "$(TARGET_NAME)";
SWIFT_OBJC_BRIDGING_HEADER = "Runner/Runner-Bridging-Header.h";
SWIFT_VERSION = 5.0;
VERSIONING_SYSTEM = "apple-generic";
};
name = Release;
};
/* End XCBuildConfiguration section */
/* Begin XCConfigurationList section */
97C146E91CF9000F007C117D /* Build configuration list for PBXProject "Runner" */ = {
isa = XCConfigurationList;
buildConfigurations = (
97C147031CF9000F007C117D /* Debug */,
97C147041CF9000F007C117D /* Release */,
249021D3217E4FDB00AE95B9 /* Profile */,
);
defaultConfigurationIsVisible = 0;
defaultConfigurationName = Release;
};
97C147051CF9000F007C117D /* Build configuration list for PBXNativeTarget "Runner" */ = {
isa = XCConfigurationList;
buildConfigurations = (
97C147061CF9000F007C117D /* Debug */,
97C147071CF9000F007C117D /* Release */,
249021D4217E4FDB00AE95B9 /* Profile */,
);
defaultConfigurationIsVisible = 0;
defaultConfigurationName = Release;
};
/* End XCConfigurationList section */
};
rootObject = 97C146E61CF9000F007C117D /* Project object */;
}
<?xml version="1.0" encoding="UTF-8"?>
<Workspace
version = "1.0">
<FileRef
location = "self:">
</FileRef>
</Workspace>
<?xml version="1.0" encoding="UTF-8"?>
<!DOCTYPE plist PUBLIC "-//Apple//DTD PLIST 1.0//EN" "http://www.apple.com/DTDs/PropertyList-1.0.dtd">
<plist version="1.0">
<dict>
<key>IDEDidComputeMac32BitWarning</key>
<true/>
</dict>
</plist>
<?xml version="1.0" encoding="UTF-8"?>
<!DOCTYPE plist PUBLIC "-//Apple//DTD PLIST 1.0//EN" "http://www.apple.com/DTDs/PropertyList-1.0.dtd">
<plist version="1.0">
<dict>
<key>PreviewsEnabled</key>
<false/>
</dict>
</plist>
<?xml version="1.0" encoding="UTF-8"?>
<Scheme
LastUpgradeVersion = "1510"
version = "1.3">
<BuildAction
parallelizeBuildables = "YES"
buildImplicitDependencies = "YES">
<BuildActionEntries>
<BuildActionEntry
buildForTesting = "YES"
buildForRunning = "YES"
buildForProfiling = "YES"
buildForArchiving = "YES"
buildForAnalyzing = "YES">
<BuildableReference
BuildableIdentifier = "primary"
BlueprintIdentifier = "97C146ED1CF9000F007C117D"
BuildableName = "Runner.app"
BlueprintName = "Runner"
ReferencedContainer = "container:Runner.xcodeproj">
</BuildableReference>
</BuildActionEntry>
</BuildActionEntries>
</BuildAction>
<TestAction
buildConfiguration = "Debug"
selectedDebuggerIdentifier = "Xcode.DebuggerFoundation.Debugger.LLDB"
selectedLauncherIdentifier = "Xcode.DebuggerFoundation.Launcher.LLDB"
shouldUseLaunchSchemeArgsEnv = "YES">
<Testables>
</Testables>
<MacroExpansion>
<BuildableReference
BuildableIdentifier = "primary"
BlueprintIdentifier = "97C146ED1CF9000F007C117D"
BuildableName = "Runner.app"
BlueprintName = "Runner"
ReferencedContainer = "container:Runner.xcodeproj">
</BuildableReference>
</MacroExpansion>
<AdditionalOptions>
</AdditionalOptions>
</TestAction>
<LaunchAction
buildConfiguration = "Debug"
selectedDebuggerIdentifier = "Xcode.DebuggerFoundation.Debugger.LLDB"
selectedLauncherIdentifier = "Xcode.DebuggerFoundation.Launcher.LLDB"
launchStyle = "0"
useCustomWorkingDirectory = "NO"
ignoresPersistentStateOnLaunch = "NO"
debugDocumentVersioning = "YES"
debugServiceExtension = "internal"
allowLocationSimulation = "YES">
<BuildableProductRunnable
runnableDebuggingMode = "0">
<BuildableReference
BuildableIdentifier = "primary"
BlueprintIdentifier = "97C146ED1CF9000F007C117D"
BuildableName = "Runner.app"
BlueprintName = "Runner"
ReferencedContainer = "container:Runner.xcodeproj">
</BuildableReference>
</BuildableProductRunnable>
<AdditionalOptions>
</AdditionalOptions>
</LaunchAction>
<ProfileAction
buildConfiguration = "Profile"
shouldUseLaunchSchemeArgsEnv = "YES"
savedToolIdentifier = ""
useCustomWorkingDirectory = "NO"
debugDocumentVersioning = "YES">
<BuildableProductRunnable
runnableDebuggingMode = "0">
<BuildableReference
BuildableIdentifier = "primary"
BlueprintIdentifier = "97C146ED1CF9000F007C117D"
BuildableName = "Runner.app"
BlueprintName = "Runner"
ReferencedContainer = "container:Runner.xcodeproj">
</BuildableReference>
</BuildableProductRunnable>
</ProfileAction>
<AnalyzeAction
buildConfiguration = "Debug">
</AnalyzeAction>
<ArchiveAction
buildConfiguration = "Release"
revealArchiveInOrganizer = "YES">
</ArchiveAction>
</Scheme>
<?xml version="1.0" encoding="UTF-8"?>
<Workspace
version = "1.0">
<FileRef
location = "group:Runner.xcodeproj">
</FileRef>
<FileRef
location = "group:Pods/Pods.xcodeproj">
</FileRef>
</Workspace>
<?xml version="1.0" encoding="UTF-8"?>
<!DOCTYPE plist PUBLIC "-//Apple//DTD PLIST 1.0//EN" "http://www.apple.com/DTDs/PropertyList-1.0.dtd">
<plist version="1.0">
<dict>
<key>IDEDidComputeMac32BitWarning</key>
<true/>
</dict>
</plist>
<?xml version="1.0" encoding="UTF-8"?>
<!DOCTYPE plist PUBLIC "-//Apple//DTD PLIST 1.0//EN" "http://www.apple.com/DTDs/PropertyList-1.0.dtd">
<plist version="1.0">
<dict>
<key>PreviewsEnabled</key>
<false/>
</dict>
</plist>
import UIKit
import Flutter
@UIApplicationMain
@objc class AppDelegate: FlutterAppDelegate {
override func application(
_ application: UIApplication,
didFinishLaunchingWithOptions launchOptions: [UIApplication.LaunchOptionsKey: Any]?
) -> Bool {
GeneratedPluginRegistrant.register(with: self)
return super.application(application, didFinishLaunchingWithOptions: launchOptions)
}
}
{
"images" : [
{
"size" : "20x20",
"idiom" : "iphone",
"filename" : "Icon-App-20x20@2x.png",
"scale" : "2x"
},
{
"size" : "20x20",
"idiom" : "iphone",
"filename" : "Icon-App-20x20@3x.png",
"scale" : "3x"
},
{
"size" : "29x29",
"idiom" : "iphone",
"filename" : "Icon-App-29x29@1x.png",
"scale" : "1x"
},
{
"size" : "29x29",
"idiom" : "iphone",
"filename" : "Icon-App-29x29@2x.png",
"scale" : "2x"
},
{
"size" : "29x29",
"idiom" : "iphone",
"filename" : "Icon-App-29x29@3x.png",
"scale" : "3x"
},
{
"size" : "40x40",
"idiom" : "iphone",
"filename" : "Icon-App-40x40@2x.png",
"scale" : "2x"
},
{
"size" : "40x40",
"idiom" : "iphone",
"filename" : "Icon-App-40x40@3x.png",
"scale" : "3x"
},
{
"size" : "60x60",
"idiom" : "iphone",
"filename" : "Icon-App-60x60@2x.png",
"scale" : "2x"
},
{
"size" : "60x60",
"idiom" : "iphone",
"filename" : "Icon-App-60x60@3x.png",
"scale" : "3x"
},
{
"size" : "20x20",
"idiom" : "ipad",
"filename" : "Icon-App-20x20@1x.png",
"scale" : "1x"
},
{
"size" : "20x20",
"idiom" : "ipad",
"filename" : "Icon-App-20x20@2x.png",
"scale" : "2x"
},
{
"size" : "29x29",
"idiom" : "ipad",
"filename" : "Icon-App-29x29@1x.png",
"scale" : "1x"
},
{
"size" : "29x29",
"idiom" : "ipad",
"filename" : "Icon-App-29x29@2x.png",
"scale" : "2x"
},
{
"size" : "40x40",
"idiom" : "ipad",
"filename" : "Icon-App-40x40@1x.png",
"scale" : "1x"
},
{
"size" : "40x40",
"idiom" : "ipad",
"filename" : "Icon-App-40x40@2x.png",
"scale" : "2x"
},
{
"size" : "76x76",
"idiom" : "ipad",
"filename" : "Icon-App-76x76@1x.png",
"scale" : "1x"
},
{
"size" : "76x76",
"idiom" : "ipad",
"filename" : "Icon-App-76x76@2x.png",
"scale" : "2x"
},
{
"size" : "83.5x83.5",
"idiom" : "ipad",
"filename" : "Icon-App-83.5x83.5@2x.png",
"scale" : "2x"
},
{
"size" : "1024x1024",
"idiom" : "ios-marketing",
"filename" : "Icon-App-1024x1024@1x.png",
"scale" : "1x"
}
],
"info" : {
"version" : 1,
"author" : "xcode"
}
}
{
"images" : [
{
"idiom" : "universal",
"filename" : "LaunchImage.png",
"scale" : "1x"
},
{
"idiom" : "universal",
"filename" : "LaunchImage@2x.png",
"scale" : "2x"
},
{
"idiom" : "universal",
"filename" : "LaunchImage@3x.png",
"scale" : "3x"
}
],
"info" : {
"version" : 1,
"author" : "xcode"
}
}
# Launch Screen Assets
You can customize the launch screen with your own desired assets by replacing the image files in this directory.
You can also do it by opening your Flutter project's Xcode project with `open ios/Runner.xcworkspace`, selecting `Runner/Assets.xcassets` in the Project Navigator and dropping in the desired images.
\ No newline at end of file
<?xml version="1.0" encoding="UTF-8" standalone="no"?>
<document type="com.apple.InterfaceBuilder3.CocoaTouch.Storyboard.XIB" version="3.0" toolsVersion="12121" systemVersion="16G29" targetRuntime="iOS.CocoaTouch" propertyAccessControl="none" useAutolayout="YES" launchScreen="YES" colorMatched="YES" initialViewController="01J-lp-oVM">
<dependencies>
<deployment identifier="iOS"/>
<plugIn identifier="com.apple.InterfaceBuilder.IBCocoaTouchPlugin" version="12089"/>
</dependencies>
<scenes>
<!--View Controller-->
<scene sceneID="EHf-IW-A2E">
<objects>
<viewController id="01J-lp-oVM" sceneMemberID="viewController">
<layoutGuides>
<viewControllerLayoutGuide type="top" id="Ydg-fD-yQy"/>
<viewControllerLayoutGuide type="bottom" id="xbc-2k-c8Z"/>
</layoutGuides>
<view key="view" contentMode="scaleToFill" id="Ze5-6b-2t3">
<autoresizingMask key="autoresizingMask" widthSizable="YES" heightSizable="YES"/>
<subviews>
<imageView opaque="NO" clipsSubviews="YES" multipleTouchEnabled="YES" contentMode="center" image="LaunchImage" translatesAutoresizingMaskIntoConstraints="NO" id="YRO-k0-Ey4">
</imageView>
</subviews>
<color key="backgroundColor" red="1" green="1" blue="1" alpha="1" colorSpace="custom" customColorSpace="sRGB"/>
<constraints>
<constraint firstItem="YRO-k0-Ey4" firstAttribute="centerX" secondItem="Ze5-6b-2t3" secondAttribute="centerX" id="1a2-6s-vTC"/>
<constraint firstItem="YRO-k0-Ey4" firstAttribute="centerY" secondItem="Ze5-6b-2t3" secondAttribute="centerY" id="4X2-HB-R7a"/>
</constraints>
</view>
</viewController>
<placeholder placeholderIdentifier="IBFirstResponder" id="iYj-Kq-Ea1" userLabel="First Responder" sceneMemberID="firstResponder"/>
</objects>
<point key="canvasLocation" x="53" y="375"/>
</scene>
</scenes>
<resources>
<image name="LaunchImage" width="168" height="185"/>
</resources>
</document>
<?xml version="1.0" encoding="UTF-8" standalone="no"?>
<document type="com.apple.InterfaceBuilder3.CocoaTouch.Storyboard.XIB" version="3.0" toolsVersion="10117" systemVersion="15F34" targetRuntime="iOS.CocoaTouch" propertyAccessControl="none" useAutolayout="YES" useTraitCollections="YES" initialViewController="BYZ-38-t0r">
<dependencies>
<deployment identifier="iOS"/>
<plugIn identifier="com.apple.InterfaceBuilder.IBCocoaTouchPlugin" version="10085"/>
</dependencies>
<scenes>
<!--Flutter View Controller-->
<scene sceneID="tne-QT-ifu">
<objects>
<viewController id="BYZ-38-t0r" customClass="FlutterViewController" sceneMemberID="viewController">
<layoutGuides>
<viewControllerLayoutGuide type="top" id="y3c-jy-aDJ"/>
<viewControllerLayoutGuide type="bottom" id="wfy-db-euE"/>
</layoutGuides>
<view key="view" contentMode="scaleToFill" id="8bC-Xf-vdC">
<rect key="frame" x="0.0" y="0.0" width="600" height="600"/>
<autoresizingMask key="autoresizingMask" widthSizable="YES" heightSizable="YES"/>
<color key="backgroundColor" white="1" alpha="1" colorSpace="custom" customColorSpace="calibratedWhite"/>
</view>
</viewController>
<placeholder placeholderIdentifier="IBFirstResponder" id="dkx-z0-nzr" sceneMemberID="firstResponder"/>
</objects>
</scene>
</scenes>
</document>
<?xml version="1.0" encoding="UTF-8"?>
<!DOCTYPE plist PUBLIC "-//Apple//DTD PLIST 1.0//EN" "http://www.apple.com/DTDs/PropertyList-1.0.dtd">
<plist version="1.0">
<dict>
<key>CFBundleDevelopmentRegion</key>
<string>$(DEVELOPMENT_LANGUAGE)</string>
<key>CFBundleExecutable</key>
<string>$(EXECUTABLE_NAME)</string>
<key>CFBundleIdentifier</key>
<string>$(PRODUCT_BUNDLE_IDENTIFIER)</string>
<key>CFBundleInfoDictionaryVersion</key>
<string>6.0</string>
<key>CFBundleName</key>
<string>example</string>
<key>CFBundlePackageType</key>
<string>APPL</string>
<key>CFBundleShortVersionString</key>
<string>$(FLUTTER_BUILD_NAME)</string>
<key>CFBundleSignature</key>
<string>????</string>
<key>CFBundleVersion</key>
<string>$(FLUTTER_BUILD_NUMBER)</string>
<key>LSRequiresIPhoneOS</key>
<true/>
<key>UILaunchStoryboardName</key>
<string>LaunchScreen</string>
<key>UIMainStoryboardFile</key>
<string>Main</string>
<key>UISupportedInterfaceOrientations</key>
<array>
<string>UIInterfaceOrientationPortrait</string>
<string>UIInterfaceOrientationLandscapeLeft</string>
<string>UIInterfaceOrientationLandscapeRight</string>
</array>
<key>UISupportedInterfaceOrientations~ipad</key>
<array>
<string>UIInterfaceOrientationPortrait</string>
<string>UIInterfaceOrientationPortraitUpsideDown</string>
<string>UIInterfaceOrientationLandscapeLeft</string>
<string>UIInterfaceOrientationLandscapeRight</string>
</array>
<key>UIViewControllerBasedStatusBarAppearance</key>
<false/>
<!-- Permission options for the `location` group -->
<key>NSLocationWhenInUseUsageDescription</key>
<string>Need location when in use</string>
<key>NSLocationAlwaysAndWhenInUseUsageDescription</key>
<string>Always and when in use!</string>
<key>NSLocationUsageDescription</key>
<string>Older devices need location.</string>
<key>NSLocationAlwaysUsageDescription</key>
<string>Can I have location always?</string>
<!-- Permission options for the `mediaLibrary` group -->
<key>NSAppleMusicUsageDescription</key>
<string>Music!</string>
<key>kTCCServiceMediaLibrary</key>
<string>media</string>
<!-- Permission options for the `calendar` group -->
<key>NSCalendarsUsageDescription</key>
<string>Calendars</string>
<key>NSCalendarsFullAccessUsageDescription</key>
<string>Calendar full access</string>
<!-- Permission options for the `camera` group -->
<key>NSCameraUsageDescription</key>
<string>camera</string>
<!-- Permission options for the `contacts` group -->
<key>NSContactsUsageDescription</key>
<string>contacts</string>
<!-- Permission options for the `microphone` group -->
<key>NSMicrophoneUsageDescription</key>
<string>microphone</string>
<!-- Permission options for the `speech` group -->
<key>NSSpeechRecognitionUsageDescription</key>
<string>speech</string>
<!-- Permission options for the `sensors` group -->
<key>NSMotionUsageDescription</key>
<string>motion</string>
<!-- Permission options for the `photos` group -->
<key>NSPhotoLibraryUsageDescription</key>
<string>photos</string>
<!-- Permission options for the `reminder` group -->
<key>NSRemindersUsageDescription</key>
<string>reminders</string>
<!-- Permission options for the `bluetooth` -->
<key>NSBluetoothAlwaysUsageDescription</key>
<string>bluetooth</string>
<key>NSBluetoothPeripheralUsageDescription</key>
<string>bluetooth</string>
<!-- Permission options for the `appTrackingTransparency` -->
<key>NSUserTrackingUsageDescription</key>
<string>appTrackingTransparency</string>
<!-- Permission options for the `assistant` group -->
<key>NSSiriUsageDescription</key>
<string>The example app would like access to Siri Kit to demonstrate requesting authorization.</string>
<key>CADisableMinimumFrameDurationOnPhone</key>
<true/>
<key>UIApplicationSupportsIndirectInputEvents</key>
<true/>
</dict>
</plist>
<?xml version="1.0" encoding="UTF-8"?>
<!DOCTYPE plist PUBLIC "-//Apple//DTD PLIST 1.0//EN" "http://www.apple.com/DTDs/PropertyList-1.0.dtd">
<plist version="1.0">
<dict>
<key>com.apple.developer.siri</key>
<true/>
</dict>
</plist>
import 'package:baseflow_plugin_template/baseflow_plugin_template.dart';
import 'package:flutter/material.dart';
import 'package:permission_handler_platform_interface/permission_handler_platform_interface.dart';
void main() {
runApp(BaseflowPluginExample(
pluginName: 'Permission Handler',
githubURL: 'https://github.com/Baseflow/flutter-permission-handler',
pubDevURL: 'https://pub.dev/packages/permission_handler',
pages: [PermissionHandlerWidget.createPage()]));
}
///Defines the main theme color
final MaterialColor themeMaterialColor =
BaseflowPluginExample.createMaterialColor(
const Color.fromRGBO(48, 49, 60, 1));
/// A Flutter application demonstrating the functionality of this plugin
class PermissionHandlerWidget extends StatefulWidget {
/// Create a page containing the functionality of this plugin
static ExamplePage createPage() {
return ExamplePage(
Icons.location_on, (context) => PermissionHandlerWidget());
}
@override
_PermissionHandlerWidgetState createState() =>
_PermissionHandlerWidgetState();
}
class _PermissionHandlerWidgetState extends State<PermissionHandlerWidget> {
@override
Widget build(BuildContext context) {
return Center(
child: ListView(
children: Permission.values
.where((permission) {
return permission != Permission.unknown &&
permission != Permission.phone &&
permission != Permission.sms &&
permission != Permission.ignoreBatteryOptimizations &&
permission != Permission.accessMediaLocation &&
permission != Permission.activityRecognition &&
permission != Permission.manageExternalStorage &&
permission != Permission.systemAlertWindow &&
permission != Permission.requestInstallPackages &&
permission != Permission.accessNotificationPolicy &&
permission != Permission.bluetoothScan &&
permission != Permission.bluetoothAdvertise &&
permission != Permission.bluetoothConnect &&
permission != Permission.nearbyWifiDevices &&
permission != Permission.videos &&
permission != Permission.audio &&
permission != Permission.scheduleExactAlarm &&
permission != Permission.sensorsAlways;
})
.map((permission) => PermissionWidget(permission))
.toList()),
);
}
}
/// Permission widget containing information about the passed [Permission]
class PermissionWidget extends StatefulWidget {
/// Constructs a [PermissionWidget] for the supplied [Permission]
const PermissionWidget(this._permission);
final Permission _permission;
@override
State<PermissionWidget> createState() => _PermissionState(_permission);
}
class _PermissionState extends State<PermissionWidget> {
_PermissionState(this._permission);
final Permission _permission;
final PermissionHandlerPlatform _permissionHandler =
PermissionHandlerPlatform.instance;
PermissionStatus _permissionStatus = PermissionStatus.denied;
@override
void initState() {
super.initState();
_listenForPermissionStatus();
}
void _listenForPermissionStatus() async {
final status = await _permissionHandler.checkPermissionStatus(_permission);
setState(() => _permissionStatus = status);
}
Color getPermissionColor() {
switch (_permissionStatus) {
case PermissionStatus.denied:
return Colors.red;
case PermissionStatus.granted:
return Colors.green;
case PermissionStatus.limited:
return Colors.orange;
default:
return Colors.grey;
}
}
@override
Widget build(BuildContext context) {
return ListTile(
title: Text(
_permission.toString(),
style: Theme.of(context).textTheme.bodyLarge,
),
subtitle: Text(
_permissionStatus.toString(),
style: TextStyle(color: getPermissionColor()),
),
trailing: (_permission is PermissionWithService)
? IconButton(
icon: const Icon(
Icons.info,
color: Colors.white,
),
onPressed: () {
checkServiceStatus(
context, _permission as PermissionWithService);
})
: null,
onTap: () {
requestPermission(_permission);
},
);
}
void checkServiceStatus(
BuildContext context, PermissionWithService permission) async {
ScaffoldMessenger.of(context).showSnackBar(SnackBar(
content: Text(
(await _permissionHandler.checkServiceStatus(permission)).toString()),
));
}
Future<void> requestPermission(Permission permission) async {
final status = await _permissionHandler.requestPermissions([permission]);
setState(() {
print(status);
_permissionStatus = status[permission] ?? PermissionStatus.denied;
print(_permissionStatus);
});
}
}
name: permission_handler_apple_example
description: Demonstrates how to use the permission_handler_apple plugin.
environment:
sdk: ">=2.15.0 <3.0.0"
dependencies:
baseflow_plugin_template: ^2.1.1
flutter:
sdk: flutter
dev_dependencies:
flutter_test:
sdk: flutter
permission_handler_apple:
# When depending on this package from a real application you should use:
# permission_handler: ^x.y.z
# See https://dart.dev/tools/pub/dependencies#version-constraints
# The example app is bundled with the plugin so we use a path dependency on
# the parent directory to use the current plugin's version.
path: ../
url_launcher: ^6.0.12
flutter:
uses-material-design: true
assets:
- res/images/baseflow_logo_def_light-02.png
- res/images/poweredByBaseflowLogoLight@3x.png
.idea/
.vagrant/
.sconsign.dblite
.svn/
.DS_Store
*.swp
profile
DerivedData/
build/
GeneratedPluginRegistrant.h
GeneratedPluginRegistrant.m
.generated/
*.pbxuser
*.mode1v3
*.mode2v3
*.perspectivev3
!default.pbxuser
!default.mode1v3
!default.mode2v3
!default.perspectivev3
xcuserdata
*.moved-aside
*.pyc
*sync/
Icon?
.tags*
/Flutter/Generated.xcconfig
//
// PermissionHandlerEnums.h
// permission_handler
//
// Created by Razvan Lung on 15/02/2019.
//
// ios: [PermissionGroupCalendar, PermissionGroupCalendarWriteOnly]
// Info.plist: [NSCalendarsUsageDescription, NSCalendarWriteOnlyAccessUsageDescription]
// dart: PermissionGroup.calendar
#ifndef PERMISSION_EVENTS
#define PERMISSION_EVENTS 0
#endif
// ios: PermissionGroupReminders
// Info.plist: NSRemindersFullAccessUsageDescription
// dart: PermissionGroup.reminders
#ifndef PERMISSION_REMINDERS
#define PERMISSION_REMINDERS 0
#endif
// ios: PermissionGroupContacts
// Info.plist: NSContactsUsageDescription
// dart: PermissionGroup.contacts
#ifndef PERMISSION_CONTACTS
#define PERMISSION_CONTACTS 0
#endif
// ios: PermissionGroupCamera
// Info.plist: NSCameraUsageDescription
// dart: PermissionGroup.camera
#ifndef PERMISSION_CAMERA
#define PERMISSION_CAMERA 0
#endif
// ios: PermissionGroupMicrophone
// Info.plist: NSMicrophoneUsageDescription
// dart: PermissionGroup.microphone
#ifndef PERMISSION_MICROPHONE
#define PERMISSION_MICROPHONE 0
#endif
// ios: PermissionGroupSpeech
// Info.plist: NSSpeechRecognitionUsageDescription
// dart: PermissionGroup.speech
#ifndef PERMISSION_SPEECH_RECOGNIZER
#define PERMISSION_SPEECH_RECOGNIZER 0
#endif
// ios: PermissionGroupPhotos
// Info.plist: NSPhotoLibraryUsageDescription
// dart: PermissionGroup.photos
#ifndef PERMISSION_PHOTOS
#define PERMISSION_PHOTOS 0
#endif
// ios: PermissionGroupPhotosAddOnly
// Info.plist: NSPhotoLibraryAddUsageDescription
// dart: PermissionGroup.photosAddOnly
#ifndef PERMISSION_PHOTOS_ADD_ONLY
#define PERMISSION_PHOTOS_ADD_ONLY 0
#endif
// ios: [PermissionGroupLocation, PermissionGroupLocationAlways, PermissionGroupLocationWhenInUse]
// Info.plist: [NSLocationUsageDescription, NSLocationAlwaysAndWhenInUseUsageDescription, NSLocationWhenInUseUsageDescription]
// dart: [PermissionGroup.location, PermissionGroup.locationAlways, PermissionGroup.locationWhenInUse]
#ifndef PERMISSION_LOCATION
#define PERMISSION_LOCATION 0
#endif
// ios: PermissionGroupNotification
// dart: PermissionGroup.notification
#ifndef PERMISSION_NOTIFICATIONS
#define PERMISSION_NOTIFICATIONS 0
#endif
// ios: PermissionGroupMediaLibrary
// Info.plist: [NSAppleMusicUsageDescription, kTCCServiceMediaLibrary]
// dart: PermissionGroup.mediaLibrary
#ifndef PERMISSION_MEDIA_LIBRARY
#define PERMISSION_MEDIA_LIBRARY 0
#endif
// ios: PermissionGroupSensors
// Info.plist: NSMotionUsageDescription
// dart: PermissionGroup.sensors
#ifndef PERMISSION_SENSORS
#define PERMISSION_SENSORS 0
#endif
// ios: PermissionGroupBluetooth
// Info.plist: [NSBluetoothAlwaysUsageDescription, NSBluetoothPeripheralUsageDescription]
// dart: PermissionGroup.bluetooth
#ifndef PERMISSION_BLUETOOTH
#define PERMISSION_BLUETOOTH 0
#endif
// ios: PermissionGroupAppTrackingTransparency
// Info.plist: [NSUserTrackingUsageDescription]
// dart: PermissionGroup.appTrackingTransparency
#ifndef PERMISSION_APP_TRACKING_TRANSPARENCY
#define PERMISSION_APP_TRACKING_TRANSPARENCY 0
#endif
// ios: PermissionGroupCriticalAlerts
// Info.plist: UNAuthorizationOptionCriticalAlert
// dart: PermissionGroup.criticalAlerts
#ifndef PERMISSION_CRITICAL_ALERTS
#define PERMISSION_CRITICAL_ALERTS 0
#endif
// ios: PermissionGroupAssistant
// Info.plist: [NSSiriUsageDescription]
// dart: PermissionGroup.assistant
#ifndef PERMISSION_ASSISTANT
#define PERMISSION_ASSISTANT 0
#endif
// ios: PermissionGroupCalendarFullAccess
// Info.plist: [NSCalendarsFullAccessUsageDescription]
// dart: PermissionGroup.calendarFullAccess
#ifndef PERMISSION_EVENTS_FULL_ACCESS
#define PERMISSION_EVENTS_FULL_ACCESS 0
#endif
typedef NS_ENUM(int, PermissionGroup) {
PermissionGroupCalendar = 0,
PermissionGroupCamera,
PermissionGroupContacts,
PermissionGroupLocation,
PermissionGroupLocationAlways,
PermissionGroupLocationWhenInUse,
PermissionGroupMediaLibrary,
PermissionGroupMicrophone,
PermissionGroupPhone,
PermissionGroupPhotos,
PermissionGroupPhotosAddOnly,
PermissionGroupReminders,
PermissionGroupSensors,
PermissionGroupSms,
PermissionGroupSpeech,
PermissionGroupStorage,
PermissionGroupIgnoreBatteryOptimizations,
PermissionGroupNotification,
PermissionGroupAccessMediaLocation,
PermissionGroupActivityRecognition,
PermissionGroupUnknown,
PermissionGroupBluetooth,
PermissionGroupManageExternalStorage,
PermissionGroupSystemAlertWindow,
PermissionGroupRequestInstallPackages,
PermissionGroupAppTrackingTransparency,
PermissionGroupCriticalAlerts,
PermissionGroupAccessNotificationPolicy,
PermissionGroupBluetoothScan,
PermissionGroupBluetoothAdvertise,
PermissionGroupBluetoothConnect,
PermissionGroupNearbyWifiDevices,
PermissiongroupVideos,
PermissionGroupAudio,
PermissionGroupScheduleExactAlarm,
PermissionGroupSensorsAlways,
PermissionGroupCalendarWriteOnly,
PermissionGroupCalendarFullAccess,
PermissionGroupAssistant,
PermissionGroupBackgroundRefresh
};
typedef NS_ENUM(int, PermissionStatus) {
PermissionStatusDenied = 0,
PermissionStatusGranted = 1,
PermissionStatusRestricted = 2,
PermissionStatusLimited = 3,
PermissionStatusPermanentlyDenied = 4,
PermissionStatusProvisional = 5,
};
typedef NS_ENUM(int, ServiceStatus) {
ServiceStatusDisabled = 0,
ServiceStatusEnabled,
ServiceStatusNotApplicable,
};
#import <Flutter/Flutter.h>
#import "PermissionManager.h"
@interface PermissionHandlerPlugin : NSObject<FlutterPlugin>
- (instancetype)initWithPermissionManager:(PermissionManager *)permissionManager;
@end
#import "PermissionHandlerPlugin.h"
@implementation PermissionHandlerPlugin {
PermissionManager *_Nonnull _permissionManager;
_Nullable FlutterResult _methodResult;
}
- (instancetype)initWithPermissionManager:(PermissionManager *)permissionManager {
self = [super init];
if (self) {
_permissionManager = permissionManager;
}
return self;
}
+ (void)registerWithRegistrar:(NSObject <FlutterPluginRegistrar> *)registrar {
FlutterMethodChannel *channel = [FlutterMethodChannel
methodChannelWithName:@"flutter.baseflow.com/permissions/methods"
binaryMessenger:[registrar messenger]];
PermissionManager *permissionManager = [[PermissionManager alloc] initWithStrategyInstances];
PermissionHandlerPlugin *instance = [[PermissionHandlerPlugin alloc] initWithPermissionManager:permissionManager];
[registrar addMethodCallDelegate:instance channel:channel];
}
- (void)handleMethodCall:(FlutterMethodCall *)call result:(FlutterResult)result {
if ([@"checkPermissionStatus" isEqualToString:call.method]) {
PermissionGroup permission = [Codec decodePermissionGroupFrom:call.arguments];
[PermissionManager checkPermissionStatus:permission result:result];
} else if ([@"checkServiceStatus" isEqualToString:call.method]) {
PermissionGroup permission = [Codec decodePermissionGroupFrom:call.arguments];
[PermissionManager checkServiceStatus:permission result:result];
} else if ([@"requestPermissions" isEqualToString:call.method]) {
if (_methodResult != nil) {
result([FlutterError errorWithCode:@"ERROR_ALREADY_REQUESTING_PERMISSIONS" message:@"A request for permissions is already running, please wait for it to finish before doing another request (note that you can request multiple permissions at the same time)." details:nil]);
return;
}
_methodResult = result;
NSArray *permissions = [Codec decodePermissionGroupsFrom:call.arguments];
[_permissionManager
requestPermissions:permissions completion:^(NSDictionary *permissionRequestResults) {
if (self->_methodResult != nil) {
self->_methodResult(permissionRequestResults);
}
self->_methodResult = nil;
} errorHandler:^(NSString *errorCode, NSString *errorDescription) {
self->_methodResult([FlutterError errorWithCode:errorCode message:errorDescription details:nil]);
self->_methodResult = nil;
}
];
} else if ([@"shouldShowRequestPermissionRationale" isEqualToString:call.method]) {
result(@false);
} else if ([@"openAppSettings" isEqualToString:call.method]) {
[PermissionManager openAppSettings:result];
} else {
result(FlutterMethodNotImplemented);
}
}
@end
//
// PermissionManager.h
// permission_handler
//
// Created by Razvan Lung on 15/02/2019.
//
#import <Flutter/Flutter.h>
#import <Foundation/Foundation.h>
#import <UIKit/UIKit.h>
#import "AudioVideoPermissionStrategy.h"
#import "AppTrackingTransparencyPermissionStrategy.h"
#import "BackgroundRefreshStrategy.h"
#import "BluetoothPermissionStrategy.h"
#import "ContactPermissionStrategy.h"
#import "EventPermissionStrategy.h"
#import "LocationPermissionStrategy.h"
#import "MediaLibraryPermissionStrategy.h"
#import "PermissionStrategy.h"
#import "PhonePermissionStrategy.h"
#import "PhotoPermissionStrategy.h"
#import "SensorPermissionStrategy.h"
#import "SpeechPermissionStrategy.h"
#import "StoragePermissionStrategy.h"
#import "UnknownPermissionStrategy.h"
#import "NotificationPermissionStrategy.h"
#import "CriticalAlertsPermissionStrategy.h"
#import "AssistantPermissionStrategy.h"
#import "PermissionHandlerEnums.h"
#import "Codec.h"
typedef void (^PermissionRequestCompletion)(NSDictionary *permissionRequestResults);
@interface PermissionManager : NSObject
- (instancetype)initWithStrategyInstances;
- (void)requestPermissions:(NSArray *)permissions completion:(PermissionRequestCompletion)completion errorHandler:(PermissionErrorHandler)errorHandler;
+ (void)checkPermissionStatus:(enum PermissionGroup)permission result:(FlutterResult)result;
+ (void)checkServiceStatus:(enum PermissionGroup)permission result:(FlutterResult)result;
+ (void)openAppSettings:(FlutterResult)result;
@end
//
// Created by Razvan Lung(long1eu) on 2019-02-15.
// Copyright (c) 2019 The Chromium Authors. All rights reserved.
//
#import "PermissionManager.h"
@implementation PermissionManager {
NSMutableArray <id <PermissionStrategy>> *_strategyInstances;
}
- (instancetype)initWithStrategyInstances {
self = [super init];
if (self) {
_strategyInstances = _strategyInstances = [[NSMutableArray alloc] init];
}
return self;
}
+ (void)checkPermissionStatus:(enum PermissionGroup)permission result:(FlutterResult)result {
id <PermissionStrategy> permissionStrategy = [PermissionManager createPermissionStrategy:permission];
PermissionStatus status = [permissionStrategy checkPermissionStatus:permission];
result([Codec encodePermissionStatus:status]);
}
+ (void)checkServiceStatus:(enum PermissionGroup)permission result:(FlutterResult)result {
__block id <PermissionStrategy> permissionStrategy = [PermissionManager createPermissionStrategy:permission];
[permissionStrategy checkServiceStatus:permission completionHandler:^(ServiceStatus serviceStatus) {
result([Codec encodeServiceStatus:serviceStatus]);
// Make sure `result` is called before cleaning up the reference
// otherwise the `result` block is also dereferenced on iOS 12 and
// below (this is most likely a bug in Objective-C which is solved in the
// later versions of the runtime).
permissionStrategy = nil;
}];
}
- (void)requestPermissions:(NSArray *)permissions completion:(PermissionRequestCompletion)completion errorHandler:(PermissionErrorHandler)errorHandler {
NSMutableDictionary *permissionStatusResult = [[NSMutableDictionary alloc] init];
if (permissions.count == 0) {
completion(permissionStatusResult);
return;
}
NSMutableSet *requestQueue = [[NSMutableSet alloc] initWithArray:permissions];
for (int i = 0; i < permissions.count; ++i) {
NSNumber *rawNumberValue = permissions[i];
int rawValue = rawNumberValue.intValue;
PermissionGroup permission = (PermissionGroup) rawValue;
__block id <PermissionStrategy> permissionStrategy = [PermissionManager createPermissionStrategy:permission];
[_strategyInstances addObject:permissionStrategy];
[permissionStrategy requestPermission:permission completionHandler:^(PermissionStatus permissionStatus) {
permissionStatusResult[@(permission)] = @(permissionStatus);
[requestQueue removeObject:@(permission)];
[self->_strategyInstances removeObject:permissionStrategy];
if (requestQueue.count == 0) {
completion(permissionStatusResult);
}
// Make sure `completion` is called before cleaning up the reference
// otherwise the `completion` block is also dereferenced on iOS 12 and
// below (this is most likely a bug in Objective-C which is solved in
// later versions of the runtime).
permissionStrategy = nil;
} errorHandler: ^(NSString* errorCode, NSString* errorDesciption) {
errorHandler(errorCode, errorDesciption);
permissionStrategy = nil;
}];
}
}
+ (void)openAppSettings:(FlutterResult)result {
if (@available(iOS 10, *)) {
[[UIApplication sharedApplication] openURL:[NSURL URLWithString:UIApplicationOpenSettingsURLString]
options:[[NSDictionary alloc] init]
completionHandler:^(BOOL success) {
result([[NSNumber alloc] initWithBool:success]);
}];
} else if (@available(iOS 8.0, *)) {
#pragma clang diagnostic push
#pragma clang diagnostic ignored "-Wdeprecated-declarations"
BOOL success = [[UIApplication sharedApplication] openURL:[NSURL URLWithString:UIApplicationOpenSettingsURLString]];
result([[NSNumber alloc] initWithBool:success]);
#pragma clang diagnostic pop
} else {
result(@false);
}
}
+ (id)createPermissionStrategy:(PermissionGroup)permission {
switch (permission) {
case PermissionGroupCalendar:
case PermissionGroupCalendarWriteOnly:
case PermissionGroupCalendarFullAccess:
return [EventPermissionStrategy new];
case PermissionGroupCamera:
return [AudioVideoPermissionStrategy new];
case PermissionGroupContacts:
return [ContactPermissionStrategy new];
case PermissionGroupLocation:
case PermissionGroupLocationAlways:
case PermissionGroupLocationWhenInUse:
#if PERMISSION_LOCATION || PERMISSION_LOCATION_WHENINUSE || PERMISSION_LOCATION_ALWAYS
return [[LocationPermissionStrategy alloc] initWithLocationManager];
#else
return [LocationPermissionStrategy new];
#endif
case PermissionGroupMediaLibrary:
return [MediaLibraryPermissionStrategy new];
case PermissionGroupMicrophone:
return [AudioVideoPermissionStrategy new];
case PermissionGroupPhone:
return [PhonePermissionStrategy new];
case PermissionGroupPhotos:
#if PERMISSION_PHOTOS
return [[PhotoPermissionStrategy alloc] initWithAccessAddOnly:false];
#else
return [PhotoPermissionStrategy new];
#endif
case PermissionGroupPhotosAddOnly:
#if PERMISSION_PHOTOS
return [[PhotoPermissionStrategy alloc] initWithAccessAddOnly:true];
#else
return [PhotoPermissionStrategy new];
#endif
case PermissionGroupReminders:
return [EventPermissionStrategy new];
case PermissionGroupSensors:
return [SensorPermissionStrategy new];
case PermissionGroupSpeech:
return [SpeechPermissionStrategy new];
case PermissionGroupNotification:
return [NotificationPermissionStrategy new];
case PermissionGroupStorage:
return [StoragePermissionStrategy new];
case PermissionGroupBluetooth:
return [BluetoothPermissionStrategy new];
case PermissionGroupAppTrackingTransparency:
return [AppTrackingTransparencyPermissionStrategy new];
case PermissionGroupCriticalAlerts:
return [CriticalAlertsPermissionStrategy new];
case PermissionGroupAssistant:
return [AssistantPermissionStrategy new];
case PermissionGroupBackgroundRefresh:
return [BackgroundRefreshStrategy new];
default:
return [UnknownPermissionStrategy new];
}
}
@end
//
// AppTrackingTransparency.h
// permission_handler
//
// Created by Jan-Derk on 21/05/2021.
//
#import <Foundation/Foundation.h>
#import "PermissionStrategy.h"
#if PERMISSION_APP_TRACKING_TRANSPARENCY
#import <AppTrackingTransparency/AppTrackingTransparency.h>
@interface AppTrackingTransparencyPermissionStrategy : NSObject <PermissionStrategy>
@end
#else
#import "UnknownPermissionStrategy.h"
@interface AppTrackingTransparencyPermissionStrategy : UnknownPermissionStrategy
@end
#endif
//
// AppTrackingTransparency.m
// permission_handler
//
// Created by Jan-Derk on 21/05/2021.
//
#import "AppTrackingTransparencyPermissionStrategy.h"
#if PERMISSION_APP_TRACKING_TRANSPARENCY
@implementation AppTrackingTransparencyPermissionStrategy
- (PermissionStatus)checkPermissionStatus:(PermissionGroup)permission {
if (@available(iOS 14, *)) {
ATTrackingManagerAuthorizationStatus attPermission = [ATTrackingManager trackingAuthorizationStatus];
return [AppTrackingTransparencyPermissionStrategy parsePermission:attPermission];
}
return PermissionStatusGranted;
}
- (void)checkServiceStatus:(PermissionGroup)permission completionHandler:(ServiceStatusHandler)completionHandler {
completionHandler(ServiceStatusNotApplicable);
}
- (void)requestPermission:(PermissionGroup)permission completionHandler:(PermissionStatusHandler)completionHandler errorHandler:(PermissionErrorHandler)errorHandler{
PermissionStatus status = [self checkPermissionStatus:permission];
if (status != PermissionStatusDenied) {
completionHandler(status);
return;
}
if (@available(iOS 14, *)){
[ATTrackingManager requestTrackingAuthorizationWithCompletionHandler:^(ATTrackingManagerAuthorizationStatus status) {
PermissionStatus permissionStatus = [AppTrackingTransparencyPermissionStrategy parsePermission:status];
completionHandler(permissionStatus);
}];
} else {
completionHandler(PermissionStatusGranted);
}
}
+ (PermissionStatus)parsePermission:(ATTrackingManagerAuthorizationStatus)attPermission API_AVAILABLE(ios(14)){
switch(attPermission){
case ATTrackingManagerAuthorizationStatusAuthorized:
return PermissionStatusGranted;
case ATTrackingManagerAuthorizationStatusRestricted:
return PermissionStatusRestricted;
case ATTrackingManagerAuthorizationStatusDenied:
return PermissionStatusPermanentlyDenied;
case ATTrackingManagerAuthorizationStatusNotDetermined:
return PermissionStatusDenied;
}
}
@end
#else
@implementation AppTrackingTransparencyPermissionStrategy
@end
#endif
//
// Created by Baptiste Dupuch(dupuchba) on 2023-09-04.
// Copyright (c) 2019 The Chromium Authors. All rights reserved.
//
#import <Foundation/Foundation.h>
#import "PermissionStrategy.h"
#if PERMISSION_ASSISTANT
#import <Intents/Intents.h>
@interface AssistantPermissionStrategy : NSObject <PermissionStrategy>
@end
#else
#import "UnknownPermissionStrategy.h"
@interface AssistantPermissionStrategy : UnknownPermissionStrategy
@end
#endif
//
// Assistant.m
// permission_handler
//
// Created by Baptiste Dupuch (dupuchba) on Tue Sep 5 08:50:04 2023
//
#import "AssistantPermissionStrategy.h"
#if PERMISSION_ASSISTANT
@implementation AssistantPermissionStrategy
- (PermissionStatus)checkPermissionStatus:(PermissionGroup)permission {
if (@available(iOS 10, *)) {
INSiriAuthorizationStatus assistantPermission = [INPreferences siriAuthorizationStatus];
return [AssistantPermissionStrategy parsePermission:assistantPermission];
}
return PermissionStatusGranted;
}
- (void)checkServiceStatus:(PermissionGroup)permission completionHandler:(ServiceStatusHandler)completionHandler {
completionHandler(ServiceStatusNotApplicable);
}
- (void)requestPermission:(PermissionGroup)permission completionHandler:(PermissionStatusHandler)completionHandler errorHandler:(PermissionErrorHandler)errorHandler {
PermissionStatus status = [self checkPermissionStatus:permission];
if (status != PermissionStatusDenied) {
completionHandler(status);
return;
}
if (@available(iOS 10, *)){
[INPreferences requestSiriAuthorization:^(INSiriAuthorizationStatus status) {
PermissionStatus permissionStatus = [AssistantPermissionStrategy parsePermission:status];
completionHandler(permissionStatus);
}];
} else {
completionHandler(PermissionStatusGranted);
}
}
+ (PermissionStatus)parsePermission:(INSiriAuthorizationStatus)assistantPermission API_AVAILABLE(ios(10)){
switch(assistantPermission){
case INSiriAuthorizationStatusAuthorized:
return PermissionStatusGranted;
case INSiriAuthorizationStatusRestricted:
return PermissionStatusRestricted;
case INSiriAuthorizationStatusDenied:
return PermissionStatusPermanentlyDenied;
case INSiriAuthorizationStatusNotDetermined:
return PermissionStatusDenied;
}
}
@end
#else
@implementation AssistantPermissionStrategy
@end
#endif
//
// Created by Razvan Lung(long1eu) on 2019-02-15.
// Copyright (c) 2019 The Chromium Authors. All rights reserved.
//
#import <Foundation/Foundation.h>
#import "PermissionStrategy.h"
#if PERMISSION_CAMERA | PERMISSION_MICROPHONE
#import <AVFoundation/AVFoundation.h>
@interface AudioVideoPermissionStrategy : NSObject <PermissionStrategy>
@end
#else
#import "UnknownPermissionStrategy.h"
@interface AudioVideoPermissionStrategy : UnknownPermissionStrategy
@end
#endif
//
// Created by Razvan Lung(long1eu) on 2019-02-15.
// Copyright (c) 2019 The Chromium Authors. All rights reserved.
//
#import "AudioVideoPermissionStrategy.h"
#if PERMISSION_CAMERA | PERMISSION_MICROPHONE
@implementation AudioVideoPermissionStrategy
- (PermissionStatus)checkPermissionStatus:(PermissionGroup)permission {
if (permission == PermissionGroupCamera) {
#if PERMISSION_CAMERA
return [AudioVideoPermissionStrategy permissionStatus:AVMediaTypeVideo];
#endif
} else if (permission == PermissionGroupMicrophone) {
#if PERMISSION_MICROPHONE
return [AudioVideoPermissionStrategy permissionStatus:AVMediaTypeAudio];
#endif
}
return PermissionStatusDenied;
}
- (void)checkServiceStatus:(PermissionGroup)permission completionHandler:(ServiceStatusHandler)completionHandler {
completionHandler(ServiceStatusNotApplicable);
}
- (void)requestPermission:(PermissionGroup)permission completionHandler:(PermissionStatusHandler)completionHandler errorHandler:(PermissionErrorHandler)errorHandler {
PermissionStatus status = [self checkPermissionStatus:permission];
if (status != PermissionStatusDenied) {
completionHandler(status);
return;
}
AVMediaType mediaType;
if (permission == PermissionGroupCamera) {
#if PERMISSION_CAMERA
mediaType = AVMediaTypeVideo;
#else
completionHandler(PermissionStatusDenied);
return;
#endif
} else if (permission == PermissionGroupMicrophone) {
#if PERMISSION_MICROPHONE
mediaType = AVMediaTypeAudio;
#else
completionHandler(PermissionStatusDenied);
return;
#endif
} else {
completionHandler(PermissionStatusDenied);
return;
}
[AVCaptureDevice requestAccessForMediaType:mediaType completionHandler:^(BOOL granted) {
if (granted) {
completionHandler(PermissionStatusGranted);
} else {
completionHandler(PermissionStatusPermanentlyDenied);
}
}];
}
+ (PermissionStatus)permissionStatus:(AVMediaType const)mediaType {
AVAuthorizationStatus status = [AVCaptureDevice authorizationStatusForMediaType:mediaType];
switch (status) {
case AVAuthorizationStatusNotDetermined:
return PermissionStatusDenied;
case AVAuthorizationStatusRestricted:
return PermissionStatusRestricted;
case AVAuthorizationStatusDenied:
return PermissionStatusPermanentlyDenied;
case AVAuthorizationStatusAuthorized:
return PermissionStatusGranted;
}
return PermissionStatusDenied;
}
@end
#else
@implementation AudioVideoPermissionStrategy
@end
#endif
//
// BackgroundRefreshStrategy.h
// permission_handler_apple
//
// Created by Sebastian Roth on 28/09/2023.
//
#import <Foundation/Foundation.h>
#import "PermissionStrategy.h"
NS_ASSUME_NONNULL_BEGIN
@interface BackgroundRefreshStrategy : NSObject<PermissionStrategy>
@end
NS_ASSUME_NONNULL_END
//
// BackgroundRefreshStrategy.m
// permission_handler_apple
//
// Created by Sebastian Roth on 28/09/2023.
//
#import "BackgroundRefreshStrategy.h"
@implementation BackgroundRefreshStrategy
- (PermissionStatus)checkPermissionStatus:(PermissionGroup)permission {
return [BackgroundRefreshStrategy permissionStatus];
}
- (void)checkServiceStatus:(PermissionGroup)permission completionHandler:(ServiceStatusHandler)completionHandler {
completionHandler(ServiceStatusNotApplicable);
}
- (void)requestPermission:(PermissionGroup)permission completionHandler:(PermissionStatusHandler)completionHandler errorHandler:(PermissionErrorHandler)errorHandler {
completionHandler([BackgroundRefreshStrategy permissionStatus]);
}
+ (PermissionStatus) permissionStatus {
UIBackgroundRefreshStatus status = UIApplication.sharedApplication.backgroundRefreshStatus;
switch (status) {
case UIBackgroundRefreshStatusDenied:
return PermissionStatusDenied;
case UIBackgroundRefreshStatusRestricted:
return PermissionStatusRestricted;
case UIBackgroundRefreshStatusAvailable:
return PermissionStatusGranted;
default:
return PermissionStatusDenied;
}
}
@end
//
// BluetoothPermissionStrategy.h
// permission_handler
//
// Created by Rene Floor on 12/03/2021.
//
#import <Foundation/Foundation.h>
#import "PermissionStrategy.h"
#if PERMISSION_BLUETOOTH
#import <CoreBluetooth/CoreBluetooth.h>
@interface BluetoothPermissionStrategy : NSObject <PermissionStrategy, CBCentralManagerDelegate>
- (void)initManagerIfNeeded;
@end
#else
#import "UnknownPermissionStrategy.h"
@interface BluetoothPermissionStrategy : UnknownPermissionStrategy
@end
#endif
//
// BluetoothPermissionStrategy.m
// permission_handler
//
// Created by Rene Floor on 12/03/2021.
//
#import "BluetoothPermissionStrategy.h"
#if PERMISSION_BLUETOOTH
@implementation BluetoothPermissionStrategy {
CBCentralManager *_centralManager;
PermissionGroup _requestedPermission;
PermissionStatusHandler _permissionStatusHandler;
ServiceStatusHandler _serviceStatusHandler;
}
- (void)initManagerIfNeeded {
if (_centralManager == nil) {
NSDictionary *options = @{CBCentralManagerOptionShowPowerAlertKey: @NO};
_centralManager = [[CBCentralManager alloc] initWithDelegate:self queue:nil options:options];
}
}
/// Reads the permission status of the Bluetooth service.
///
/// The behavior differs across iOS versions:
/// - Starting with iOS 13.1, this function returns the expected result.
/// - On iOS 13.0, applications are unable to check for the permission status without triggering a
/// permission request. Therefore, `PermissionStatusDenied` is always returned. To obtain the
/// actual permission status, the application should request permission using `requestPermission()`.
/// If the permission was already granted, no dialog will pop up.
/// - Below iOS 13.0, applications do not have to ask for permission to use Bluetooth. Therefore,
/// `PermissionStatusGranted` is always returned.
- (PermissionStatus)checkPermissionStatus:(PermissionGroup)permission {
if (@available(iOS 13.1, *)) {
CBManagerAuthorization blePermission = [CBCentralManager authorization];
return [BluetoothPermissionStrategy parsePermission:blePermission];
} else if (@available(iOS 13.0, *)) {
return PermissionStatusDenied;
}
return PermissionStatusGranted;
}
/// Asynchronously requests the status of the Bluetooth service.
///
/// The result will be fetched in `handleCheckServiceStatusCallback`, which will in turn call
/// `completionHandler` with either `ServiceStatusEnabled` or `ServiceStatusDisabled`.
///
/// If the Bluetooth permission has been requested and was denied, this will return `ServiceStatusDisabled`,
/// regardless of the actual state of the Bluetooth service.
/// If the Bluetooth permission has not been granted or denied yet, this call will trigger a permission dialog, asking
/// the user to give the application access to Bluetooth.
- (void)checkServiceStatus:(PermissionGroup)permission completionHandler:(ServiceStatusHandler)completionHandler {
[self initManagerIfNeeded];
_serviceStatusHandler = completionHandler;
_requestedPermission = permission;
}
- (void)handleCheckServiceStatusCallback:(CBCentralManager *)centralManager {
if (@available(iOS 10, *)) {
ServiceStatus serviceStatus = [centralManager state] == CBManagerStatePoweredOn ? ServiceStatusEnabled : ServiceStatusDisabled;
_serviceStatusHandler(serviceStatus);
}
#pragma clang diagnostic ignored "-Wdeprecated-declarations"
ServiceStatus serviceStatus = [centralManager state] == CBCentralManagerStatePoweredOn ? ServiceStatusEnabled : ServiceStatusDisabled;
_serviceStatusHandler(serviceStatus);
}
- (void)requestPermission:(PermissionGroup)permission completionHandler:(PermissionStatusHandler)completionHandler errorHandler:(PermissionErrorHandler)errorHandler {
[self initManagerIfNeeded];
PermissionStatus status = [self checkPermissionStatus:permission];
if (status != PermissionStatusDenied) {
completionHandler(status);
return;
}
_permissionStatusHandler = completionHandler;
_requestedPermission = permission;
}
- (void)handleRequestPermissionCallback:(CBCentralManager *)centralManager {
if (@available(iOS 13.0, *)) {
CBManagerAuthorization blePermission = [centralManager authorization];
PermissionStatus permissionStatus = [BluetoothPermissionStrategy parsePermission:blePermission];
_permissionStatusHandler(permissionStatus);
} else {
_permissionStatusHandler(PermissionStatusGranted);
}
}
+ (PermissionStatus)parsePermission:(CBManagerAuthorization)bluetoothPermission API_AVAILABLE(ios(13)) {
switch(bluetoothPermission){
case CBManagerAuthorizationNotDetermined:
return PermissionStatusDenied;
case CBManagerAuthorizationRestricted:
return PermissionStatusRestricted;
case CBManagerAuthorizationDenied:
return PermissionStatusPermanentlyDenied;
case CBManagerAuthorizationAllowedAlways:
return PermissionStatusGranted;
}
}
- (void)centralManagerDidUpdateState:(nonnull CBCentralManager *)centralManager {
if (_permissionStatusHandler != nil) {
[self handleRequestPermissionCallback:centralManager];
}
if (_serviceStatusHandler != nil) {
[self handleCheckServiceStatusCallback:centralManager];
}
}
@end
#else
@implementation BluetoothPermissionStrategy
@end
#endif
//
// Created by Razvan Lung(long1eu) on 2019-02-15.
// Copyright (c) 2019 The Chromium Authors. All rights reserved.
//
#import <Foundation/Foundation.h>
#import "PermissionStrategy.h"
#if PERMISSION_CONTACTS
#import <AddressBook/ABAddressBook.h>
#import <Contacts/Contacts.h>
@interface ContactPermissionStrategy : NSObject <PermissionStrategy>
@end
#else
#import "UnknownPermissionStrategy.h"
@interface ContactPermissionStrategy : UnknownPermissionStrategy
@end
#endif
//
// Created by Razvan Lung(long1eu) on 2019-02-15.
// Copyright (c) 2019 The Chromium Authors. All rights reserved.
//
#import "ContactPermissionStrategy.h"
#if PERMISSION_CONTACTS
@implementation ContactPermissionStrategy
- (PermissionStatus)checkPermissionStatus:(PermissionGroup)permission {
return [ContactPermissionStrategy permissionStatus];
}
- (void)checkServiceStatus:(PermissionGroup)permission completionHandler:(ServiceStatusHandler)completionHandler {
completionHandler(ServiceStatusNotApplicable);
}
- (void)requestPermission:(PermissionGroup)permission completionHandler:(PermissionStatusHandler)completionHandler errorHandler:(PermissionErrorHandler)errorHandler {
PermissionStatus status = [self checkPermissionStatus:permission];
if (status != PermissionStatusDenied) {
completionHandler(status);
return;
}
if (@available(iOS 9.0, *)) {
[ContactPermissionStrategy requestPermissionsFromContactStore:completionHandler];
} else {
[ContactPermissionStrategy requestPermissionsFromAddressBook:completionHandler];
}
}
+ (PermissionStatus)permissionStatus {
if (@available(iOS 9.0, *)) {
CNAuthorizationStatus status = [CNContactStore authorizationStatusForEntityType:CNEntityTypeContacts];
switch (status) {
case CNAuthorizationStatusNotDetermined:
return PermissionStatusDenied;
case CNAuthorizationStatusRestricted:
return PermissionStatusRestricted;
case CNAuthorizationStatusDenied:
return PermissionStatusPermanentlyDenied;
case CNAuthorizationStatusAuthorized:
return PermissionStatusGranted;
}
} else {
#pragma clang diagnostic push
#pragma clang diagnostic ignored "-Wdeprecated-declarations"
ABAuthorizationStatus status = ABAddressBookGetAuthorizationStatus();
switch (status) {
case kABAuthorizationStatusNotDetermined:
return PermissionStatusDenied;
case kABAuthorizationStatusRestricted:
return PermissionStatusRestricted;
case kABAuthorizationStatusDenied:
return PermissionStatusPermanentlyDenied;
case kABAuthorizationStatusAuthorized:
return PermissionStatusGranted;
#pragma clang diagnostic pop
}
}
return PermissionStatusDenied;
}
+ (void)requestPermissionsFromContactStore:(PermissionStatusHandler)completionHandler API_AVAILABLE(ios(9)) {
CNContactStore *contactStore = [CNContactStore new];
[contactStore requestAccessForEntityType:CNEntityTypeContacts completionHandler:^(BOOL granted, NSError *__nullable error) {
if (granted) {
completionHandler(PermissionStatusGranted);
} else {
completionHandler(PermissionStatusPermanentlyDenied);
}
}];
}
+ (void)requestPermissionsFromAddressBook:(PermissionStatusHandler)completionHandler {
#pragma clang diagnostic push
#pragma clang diagnostic ignored "-Wdeprecated-declarations"
ABAddressBookRequestAccessWithCompletion(ABAddressBookCreate(), ^(bool granted, CFErrorRef error) {
if (granted) {
completionHandler(PermissionStatusGranted);
} else {
completionHandler(PermissionStatusPermanentlyDenied);
}
});
#pragma clang diagnostic pop
}
@end
#else
@implementation ContactPermissionStrategy
@end
#endif
//
// CriticalAlertsPermissionStrategy.h
// permission_handler
//
// Created by Neal Soni on 2021/6/8.
//
#import <Foundation/Foundation.h>
#import "PermissionStrategy.h"
#if PERMISSION_CRITICAL_ALERTS
#import <UserNotifications/UserNotifications.h>
@interface CriticalAlertsPermissionStrategy : NSObject <PermissionStrategy>
@end
#else
#import "UnknownPermissionStrategy.h"
@interface CriticalAlertsPermissionStrategy : UnknownPermissionStrategy
@end
#endif
//
// CriticalAlertsPermissionStrategy.m
// permission_handler
//
// Created by Neal Soni on 2021/6/8.
//
#import "CriticalAlertsPermissionStrategy.h"
#if PERMISSION_CRITICAL_ALERTS
@implementation CriticalAlertsPermissionStrategy
- (PermissionStatus)checkPermissionStatus:(PermissionGroup)permission {
return [CriticalAlertsPermissionStrategy permissionStatus];
}
- (void)checkServiceStatus:(PermissionGroup)permission completionHandler:(ServiceStatusHandler)completionHandler {
completionHandler(ServiceStatusNotApplicable);
}
- (void)requestPermission:(PermissionGroup)permission completionHandler:(PermissionStatusHandler)completionHandler errorHandler:(PermissionErrorHandler)errorHandler {
PermissionStatus status = [self checkPermissionStatus:permission];
if (status != PermissionStatusDenied) {
completionHandler(status);
return;
}
dispatch_async(dispatch_get_main_queue(), ^{
if(@available(iOS 12.0, *)) {
UNUserNotificationCenter *center = [UNUserNotificationCenter currentNotificationCenter];
UNAuthorizationOptions authorizationOptions = 0;
authorizationOptions += UNAuthorizationOptionCriticalAlert;
[center requestAuthorizationWithOptions:(authorizationOptions) completionHandler:^(BOOL granted, NSError * _Nullable error) {
if (error != nil || !granted) {
completionHandler(PermissionStatusPermanentlyDenied);
return;
}
dispatch_async(dispatch_get_main_queue(), ^{
[[UIApplication sharedApplication] registerForRemoteNotifications];
completionHandler(PermissionStatusGranted);
});
}];
} else {
completionHandler(PermissionStatusPermanentlyDenied);
}
});
}
+ (PermissionStatus)permissionStatus {
__block PermissionStatus permissionStatus = PermissionStatusGranted;
if (@available(iOS 12 , *)) {
dispatch_semaphore_t sem = dispatch_semaphore_create(0);
[[UNUserNotificationCenter currentNotificationCenter] getNotificationSettingsWithCompletionHandler:^(UNNotificationSettings * _Nonnull settings) {
if (settings.criticalAlertSetting == UNAuthorizationStatusDenied) {
permissionStatus = PermissionStatusPermanentlyDenied;
} else if (settings.criticalAlertSetting == UNAuthorizationStatusNotDetermined) {
permissionStatus = PermissionStatusDenied;
}
dispatch_semaphore_signal(sem);
}];
dispatch_semaphore_wait(sem, DISPATCH_TIME_FOREVER);
} else {
permissionStatus = PermissionStatusPermanentlyDenied;
}
return permissionStatus;
}
@end
#else
@implementation CriticalAlertsPermissionStrategy
@end
#endif
//
// Created by Razvan Lung(long1eu) on 2019-02-15.
// Copyright (c) 2019 The Chromium Authors. All rights reserved.
//
#import <Foundation/Foundation.h>
#import "PermissionStrategy.h"
#if PERMISSION_EVENTS | PERMISSION_EVENTS_FULL_ACCESS | PERMISSION_REMINDERS
#import <EventKit/EventKit.h>
@interface EventPermissionStrategy : NSObject <PermissionStrategy>
@end
#else
#import "UnknownPermissionStrategy.h"
@interface EventPermissionStrategy : UnknownPermissionStrategy
@end
#endif
//
// Created by Razvan Lung(long1eu) on 2019-02-15.
// Copyright (c) 2019 The Chromium Authors. All rights reserved.
//
#import "EventPermissionStrategy.h"
#if PERMISSION_EVENTS | PERMISSION_EVENTS_FULL_ACCESS | PERMISSION_REMINDERS
@implementation EventPermissionStrategy
- (PermissionStatus)checkPermissionStatus:(PermissionGroup)permission {
return [EventPermissionStrategy permissionStatus:permission];
}
- (void)checkServiceStatus:(PermissionGroup)permission completionHandler:(ServiceStatusHandler)completionHandler {
completionHandler(ServiceStatusNotApplicable);
}
- (void)requestPermission:(PermissionGroup)permission completionHandler:(PermissionStatusHandler)completionHandler errorHandler:(PermissionErrorHandler)errorHandler {
PermissionStatus permissionStatus = [self checkPermissionStatus:permission];
if (permissionStatus != PermissionStatusDenied) {
completionHandler(permissionStatus);
return;
}
if (permission == PermissionGroupCalendar || permission == PermissionGroupCalendarFullAccess) {
if (@available(iOS 17.0, *)) {
#if !PERMISSION_EVENTS_FULL_ACCESS
completionHandler(PermissionStatusDenied);
return;
#endif
} else {
#if !PERMISSION_EVENTS
completionHandler(PermissionStatusDenied);
return;
#endif
}
} else if (permission == PermissionGroupCalendarWriteOnly) {
#if !PERMISSION_EVENTS && !PERMISSION_EVENTS_FULL_ACCESS
completionHandler(PermissionStatusDenied);
return;
#endif
} else if (permission == PermissionGroupReminders) {
#if !PERMISSION_REMINDERS
completionHandler(PermissionStatusDenied);
return;
#endif
}
EKEventStore *eventStore = [[EKEventStore alloc] init];
if (@available(iOS 17.0, *)) {
if (permission == PermissionGroupCalendar || permission == PermissionGroupCalendarFullAccess) {
[eventStore requestFullAccessToEventsWithCompletion:^(BOOL granted, NSError *error) {
if (granted) {
completionHandler(PermissionStatusGranted);
} else {
completionHandler(PermissionStatusPermanentlyDenied);
}
}];
} else if (permission == PermissionGroupCalendarWriteOnly) {
[eventStore requestWriteOnlyAccessToEventsWithCompletion:^(BOOL granted, NSError *error) {
if (granted) {
completionHandler(PermissionStatusGranted);
} else {
completionHandler(PermissionStatusPermanentlyDenied);
}
}];
} else if (permission == PermissionGroupReminders) {
[eventStore requestFullAccessToRemindersWithCompletion:^(BOOL granted, NSError *error) {
if (granted) {
completionHandler(PermissionStatusGranted);
} else {
completionHandler(PermissionStatusPermanentlyDenied);
}
}];
}
} else {
EKEntityType entityType = [EventPermissionStrategy getEntityType:permission];
[eventStore requestAccessToEntityType:entityType completion:^(BOOL granted, NSError *error) {
if (granted) {
completionHandler(PermissionStatusGranted);
} else {
completionHandler(PermissionStatusPermanentlyDenied);
}
}];
}
}
+ (PermissionStatus)permissionStatus:(PermissionGroup)permission {
EKEntityType entityType = [EventPermissionStrategy getEntityType:permission];
EKAuthorizationStatus status = [EKEventStore authorizationStatusForEntityType:entityType];
if (@available(iOS 17.0, *)) {
switch (status) {
case EKAuthorizationStatusNotDetermined:
return PermissionStatusDenied;
case EKAuthorizationStatusRestricted:
return PermissionStatusRestricted;
case EKAuthorizationStatusDenied:
return PermissionStatusPermanentlyDenied;
case EKAuthorizationStatusFullAccess:
return PermissionStatusGranted;
case EKAuthorizationStatusWriteOnly:
if (permission == PermissionGroupCalendarWriteOnly) {
return PermissionStatusGranted;
}
return PermissionStatusDenied;
}
} else {
switch (status) {
case EKAuthorizationStatusNotDetermined:
return PermissionStatusDenied;
case EKAuthorizationStatusRestricted:
return PermissionStatusRestricted;
case EKAuthorizationStatusDenied:
return PermissionStatusPermanentlyDenied;
case EKAuthorizationStatusAuthorized:
return PermissionStatusGranted;
case EKAuthorizationStatusWriteOnly:
//not available on iOS 16 and below
break;
}
}
return PermissionStatusDenied;
}
+ (EKEntityType)getEntityType:(PermissionGroup)permission {
if (permission == PermissionGroupReminders) {
return EKEntityTypeReminder;
}
return EKEntityTypeEvent;
}
@end
#else
@implementation EventPermissionStrategy
@end
#endif
//
// Created by Razvan Lung(long1eu) on 2019-02-15.
// Copyright (c) 2019 The Chromium Authors. All rights reserved.
//
#import <Foundation/Foundation.h>
#import "PermissionStrategy.h"
#if PERMISSION_LOCATION || PERMISSION_LOCATION_WHENINUSE || PERMISSION_LOCATION_ALWAYS
#import <CoreLocation/CoreLocation.h>
@interface LocationPermissionStrategy : NSObject <PermissionStrategy, CLLocationManagerDelegate>
- (instancetype)initWithLocationManager;
@end
#else
#import "UnknownPermissionStrategy.h"
@interface LocationPermissionStrategy : UnknownPermissionStrategy
@end
#endif
//
// Created by Razvan Lung(long1eu) on 2019-02-15.
// Copyright (c) 2019 The Chromium Authors. All rights reserved.
//
#import "LocationPermissionStrategy.h"
#if PERMISSION_LOCATION || PERMISSION_LOCATION_WHENINUSE || PERMISSION_LOCATION_ALWAYS
NSString *const UserDefaultPermissionRequestedKey = @"org.baseflow.permission_handler_apple.permission_requested";
@interface LocationPermissionStrategy ()
- (void) receiveActivityNotification:(NSNotification *)notification;
@end
@implementation LocationPermissionStrategy {
CLLocationManager *_locationManager;
PermissionStatusHandler _permissionStatusHandler;
PermissionGroup _requestedPermission;
BOOL _previousStatusWasNotDetermined;
}
- (instancetype)initWithLocationManager {
self = [super init];
if (self) {
_locationManager = [CLLocationManager new];
_locationManager.delegate = self;
_previousStatusWasNotDetermined = NO;
}
return self;
}
- (PermissionStatus)checkPermissionStatus:(PermissionGroup)permission {
return [LocationPermissionStrategy permissionStatus:permission];
}
- (void)checkServiceStatus:(PermissionGroup)permission completionHandler:(ServiceStatusHandler)completionHandler {
dispatch_async(dispatch_get_global_queue( DISPATCH_QUEUE_PRIORITY_DEFAULT, 0), ^{
BOOL isEnabled = [CLLocationManager locationServicesEnabled];
dispatch_async(dispatch_get_main_queue(), ^(void) {
completionHandler(isEnabled ? ServiceStatusEnabled : ServiceStatusDisabled);
});
});
}
- (void)requestPermission:(PermissionGroup)permission completionHandler:(PermissionStatusHandler)completionHandler errorHandler:(PermissionErrorHandler)errorHandler {
PermissionStatus status = [self checkPermissionStatus:permission];
if ([CLLocationManager authorizationStatus] == kCLAuthorizationStatusAuthorizedWhenInUse && permission == PermissionGroupLocationAlways) {
BOOL alreadyRequested = [[NSUserDefaults standardUserDefaults] boolForKey:UserDefaultPermissionRequestedKey]; // check if already requested the permantent permission
if(alreadyRequested) {
completionHandler(status);
return;
}
} else if (status != PermissionStatusDenied) { // handles undetermined always permission and denied whenInUse permission
completionHandler(status);
return;
}
_permissionStatusHandler = completionHandler;
_requestedPermission = permission;
if (permission == PermissionGroupLocation) {
#if PERMISSION_LOCATION
bool hasAlwaysInInfoPlist = ([[NSBundle mainBundle] objectForInfoDictionaryKey:@"NSLocationAlwaysUsageDescription"] != nil || [[NSBundle mainBundle] objectForInfoDictionaryKey:@"NSLocationAlwaysAndWhenInUseUsageDescription"] != nil);
if (hasAlwaysInInfoPlist && [CLLocationManager authorizationStatus] == kCLAuthorizationStatusAuthorizedWhenInUse) {
[_locationManager requestAlwaysAuthorization];
} else if ([[NSBundle mainBundle] objectForInfoDictionaryKey:@"NSLocationWhenInUseUsageDescription"] != nil) {
[_locationManager requestWhenInUseAuthorization];
} else {
errorHandler(@"MISSING_USAGE_DESCRIPTION", @"To use location from iOS8 you need to define at least NSLocationWhenInUseUsageDescription and optionally NSLocationAlwaysAndWhenInUseUsageDescription in the app bundle's Info.plist file");
return;
}
#else
if ([[NSBundle mainBundle] objectForInfoDictionaryKey:@"NSLocationWhenInUseUsageDescription"] != nil ) {
[_locationManager requestWhenInUseAuthorization];
} else {
errorHandler(@"MISSING_USAGE_DESCRIPTION", @"To use location from iOS8 you need to define at least NSLocationWhenInUseUsageDescription and optionally NSLocationAlwaysAndWhenInUseUsageDescription in the app bundle's Info.plist file");
return;
}
#endif
} else if (permission == PermissionGroupLocationAlways) {
#if PERMISSION_LOCATION
if ([CLLocationManager authorizationStatus] == kCLAuthorizationStatusNotDetermined) {
errorHandler(@"MISSING_WHENINUSE_PERMISSION", @"Must have \"When in use\" permission before it is allowed to request \"Always\" permission.");
return;
}
if ([[NSBundle mainBundle] objectForInfoDictionaryKey:@"NSLocationAlwaysUsageDescription"] != nil || [[NSBundle mainBundle] objectForInfoDictionaryKey:@"NSLocationAlwaysAndWhenInUseUsageDescription"] != nil ) {
[[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(receiveActivityNotification:) name:UIApplicationDidBecomeActiveNotification object:nil];
[_locationManager requestAlwaysAuthorization];
[[NSUserDefaults standardUserDefaults] setBool:TRUE forKey:UserDefaultPermissionRequestedKey];
} else {
errorHandler(@"MISSING_USAGE_DESCRIPTION", @"To always use location from iOS8 you need to define at least NSLocationWhenInUseUsageDescription and optionally NSLocationAlwaysAndWhenInUseUsageDescription in the app bundle's Info.plist file");
return;
}
#endif
} else if (permission == PermissionGroupLocationWhenInUse) {
if ([[NSBundle mainBundle] objectForInfoDictionaryKey:@"NSLocationWhenInUseUsageDescription"] != nil ) {
[_locationManager requestWhenInUseAuthorization];
} else {
errorHandler(@"MISSING_USAGE_DESCRIPTION", @"To use location from iOS8 you need to define at least NSLocationWhenInUseUsageDescription and optionally NSLocationAlwaysAndWhenInUseUsageDescription in the app bundle's Info.plist file");
return;
}
}
}
- (void) receiveActivityNotification:(NSNotification *) notification {
CLAuthorizationStatus status;
if(@available(iOS 14.0, *)){
status = _locationManager.authorizationStatus;
} else {
status = [CLLocationManager authorizationStatus];
}
if ((_requestedPermission == PermissionGroupLocationAlways && status != kCLAuthorizationStatusAuthorizedAlways)) {
PermissionStatus permissionStatus = [LocationPermissionStrategy determinePermissionStatus:_requestedPermission authorizationStatus:status];
_permissionStatusHandler(permissionStatus);
}
[[NSNotificationCenter defaultCenter] removeObserver:self name:UIApplicationDidBecomeActiveNotification object:nil];
}
// {WARNING}
// This is called when the location manager is first initialized and raises the following situations:
// 1. When we first request [PermissionGroupLocationWhenInUse] and then [PermissionGroupLocationAlways]
// this will be called when the [CLLocationManager] is first initialized with
// [kCLAuthorizationStatusAuthorizedWhenInUse]. As a consequence we send back the result too early.
// 2. When we first request [PermissionGroupLocationWhenInUse] and then [PermissionGroupLocationAlways]
// and the user doesn't allow for [kCLAuthorizationStatusAuthorizedAlways] this method is not called
// at all.
// 3. When the permission dialog is opened, this method is called with [kCLAuthorizationStatusNotDetermined].
// The method should not return at this point, but instead wait for the next [CLAuthorizationStatus] to
// determine what to send back. If the method is called with [kCLAuthorizationStatusNotDetermined] for a
// second time, assume that the permission was not granted. This might catch situations where the user
// dismisses the dialog without making a decision.
- (void)locationManager:(CLLocationManager *)manager didChangeAuthorizationStatus:(CLAuthorizationStatus)status {
if (_permissionStatusHandler == nil || @(_requestedPermission) == nil) {
return;
}
if (status == kCLAuthorizationStatusNotDetermined) {
if (_previousStatusWasNotDetermined) {
_permissionStatusHandler(PermissionStatusDenied);
}
_previousStatusWasNotDetermined = YES;
return;
}
_previousStatusWasNotDetermined = NO;
if ((_requestedPermission == PermissionGroupLocationAlways && status == kCLAuthorizationStatusAuthorizedWhenInUse)) {
_permissionStatusHandler(PermissionStatusDenied);
return;
}
PermissionStatus permissionStatus = [LocationPermissionStrategy
determinePermissionStatus:_requestedPermission authorizationStatus:status];
_permissionStatusHandler(permissionStatus);
}
+ (PermissionStatus)permissionStatus:(PermissionGroup)permission {
CLAuthorizationStatus authorizationStatus = [CLLocationManager authorizationStatus];
PermissionStatus status = [LocationPermissionStrategy
determinePermissionStatus:permission authorizationStatus:authorizationStatus];
return status;
}
+ (PermissionStatus)determinePermissionStatus:(PermissionGroup)permission authorizationStatus:(CLAuthorizationStatus)authorizationStatus {
if (@available(iOS 8.0, *)) {
if (permission == PermissionGroupLocationAlways) {
switch (authorizationStatus) {
case kCLAuthorizationStatusNotDetermined:
return PermissionStatusDenied;
case kCLAuthorizationStatusRestricted:
return PermissionStatusRestricted;
case kCLAuthorizationStatusAuthorizedWhenInUse:
case kCLAuthorizationStatusDenied:
return PermissionStatusPermanentlyDenied;
case kCLAuthorizationStatusAuthorizedAlways:
return PermissionStatusGranted;
}
}
switch (authorizationStatus) {
case kCLAuthorizationStatusNotDetermined:
return PermissionStatusDenied;
case kCLAuthorizationStatusRestricted:
return PermissionStatusRestricted;
case kCLAuthorizationStatusDenied:
return PermissionStatusPermanentlyDenied;
case kCLAuthorizationStatusAuthorizedWhenInUse:
case kCLAuthorizationStatusAuthorizedAlways:
return PermissionStatusGranted;
}
}
#pragma clang diagnostic push
#pragma clang diagnostic ignored "-Wdeprecated-declarations"
switch (authorizationStatus) {
case kCLAuthorizationStatusNotDetermined:
return PermissionStatusDenied;
case kCLAuthorizationStatusRestricted:
return PermissionStatusRestricted;
case kCLAuthorizationStatusDenied:
return PermissionStatusPermanentlyDenied;
case kCLAuthorizationStatusAuthorized:
return PermissionStatusGranted;
default:
return PermissionStatusDenied;
}
#pragma clang diagnostic pop
}
@end
#else
@implementation LocationPermissionStrategy
@end
#endif
//
// Created by Razvan Lung(long1eu) on 2019-02-15.
// Copyright (c) 2019 The Chromium Authors. All rights reserved.
//
#import <Foundation/Foundation.h>
#include "PermissionStrategy.h"
#if PERMISSION_MEDIA_LIBRARY
#import <MediaPlayer/MediaPlayer.h>
@interface MediaLibraryPermissionStrategy : NSObject <PermissionStrategy>
@end
#else
#import "UnknownPermissionStrategy.h"
@interface MediaLibraryPermissionStrategy : UnknownPermissionStrategy
@end
#endif
//
// Created by Razvan Lung(long1eu) on 2019-02-15.
// Copyright (c) 2019 The Chromium Authors. All rights reserved.
//
#import "MediaLibraryPermissionStrategy.h"
#if PERMISSION_MEDIA_LIBRARY
@implementation MediaLibraryPermissionStrategy
- (PermissionStatus)checkPermissionStatus:(PermissionGroup)permission {
return [MediaLibraryPermissionStrategy permissionStatus];
}
- (void)checkServiceStatus:(PermissionGroup)permission completionHandler:(ServiceStatusHandler)completionHandler {
completionHandler(ServiceStatusNotApplicable);
}
- (void)requestPermission:(PermissionGroup)permission completionHandler:(PermissionStatusHandler)completionHandler errorHandler:(PermissionErrorHandler)errorHandler {
PermissionStatus status = [self checkPermissionStatus:permission];
if (status != PermissionStatusDenied) {
completionHandler(status);
return;
}
if (@available(iOS 9.3, *)) {
[MPMediaLibrary requestAuthorization:^(MPMediaLibraryAuthorizationStatus status) {
completionHandler([MediaLibraryPermissionStrategy determinePermissionStatus:status]);
}];
} else {
completionHandler(PermissionStatusPermanentlyDenied);
return;
}
}
+ (PermissionStatus)permissionStatus {
if (@available(iOS 9.3, *)) {
MPMediaLibraryAuthorizationStatus status = [MPMediaLibrary authorizationStatus];
return [MediaLibraryPermissionStrategy determinePermissionStatus:status];
}
return PermissionStatusDenied;
}
+ (PermissionStatus)determinePermissionStatus:(MPMediaLibraryAuthorizationStatus)authorizationStatus API_AVAILABLE(ios(9.3)){
switch (authorizationStatus) {
case MPMediaLibraryAuthorizationStatusNotDetermined:
return PermissionStatusDenied;
case MPMediaLibraryAuthorizationStatusDenied:
return PermissionStatusPermanentlyDenied;
case MPMediaLibraryAuthorizationStatusRestricted:
return PermissionStatusRestricted;
case MPMediaLibraryAuthorizationStatusAuthorized:
return PermissionStatusGranted;
}
return PermissionStatusDenied;
}
@end
#else
@implementation MediaLibraryPermissionStrategy
@end
#endif
//
// NotificationPermissionStrategy.h
// permission_handler
//
// Created by Tong on 2019/10/21.
//
#import <Foundation/Foundation.h>
#import "PermissionStrategy.h"
#if PERMISSION_NOTIFICATIONS
#import <UserNotifications/UserNotifications.h>
@interface NotificationPermissionStrategy : NSObject <PermissionStrategy>
@end
#else
#import "UnknownPermissionStrategy.h"
@interface NotificationPermissionStrategy : UnknownPermissionStrategy
@end
#endif
//
// NotificationPermissionStrategy.m
// permission_handler
//
// Created by Tong on 2019/10/21.
//
#import "NotificationPermissionStrategy.h"
#if PERMISSION_NOTIFICATIONS
@implementation NotificationPermissionStrategy
- (PermissionStatus)checkPermissionStatus:(PermissionGroup)permission {
return [NotificationPermissionStrategy permissionStatus];
}
- (void)checkServiceStatus:(PermissionGroup)permission completionHandler:(ServiceStatusHandler)completionHandler {
completionHandler(ServiceStatusNotApplicable);
}
- (void)requestPermission:(PermissionGroup)permission completionHandler:(PermissionStatusHandler)completionHandler errorHandler:(PermissionErrorHandler)errorHandler {
PermissionStatus status = [self checkPermissionStatus:permission];
if (@available(iOS 12.0, *)) {
if (status != PermissionStatusDenied && status != PermissionStatusProvisional) {
completionHandler(status);
return;
}
} else if (status != PermissionStatusDenied) {
completionHandler(status);
return;
}
dispatch_async(dispatch_get_main_queue(), ^{
if(@available(iOS 10.0, *)) {
UNUserNotificationCenter *center = [UNUserNotificationCenter currentNotificationCenter];
UNAuthorizationOptions authorizationOptions = 0;
authorizationOptions += UNAuthorizationOptionSound;
authorizationOptions += UNAuthorizationOptionAlert;
authorizationOptions += UNAuthorizationOptionBadge;
[center requestAuthorizationWithOptions:(authorizationOptions) completionHandler:^(BOOL granted, NSError * _Nullable error) {
if (error != nil || !granted) {
completionHandler(PermissionStatusPermanentlyDenied);
return;
}
dispatch_async(dispatch_get_main_queue(), ^{
[[UIApplication sharedApplication] registerForRemoteNotifications];
completionHandler(PermissionStatusGranted);
});
}];
} else {
UIUserNotificationType notificationTypes = 0;
notificationTypes |= UIUserNotificationTypeSound;
notificationTypes |= UIUserNotificationTypeAlert;
notificationTypes |= UIUserNotificationTypeBadge;
UIUserNotificationSettings *settings = [UIUserNotificationSettings settingsForTypes:notificationTypes categories:nil];
[[UIApplication sharedApplication] registerUserNotificationSettings:settings];
[[UIApplication sharedApplication] registerForRemoteNotifications];
completionHandler(PermissionStatusGranted);
}
});
}
+ (PermissionStatus)permissionStatus {
__block PermissionStatus permissionStatus = PermissionStatusGranted;
if (@available(iOS 10 , *)) {
dispatch_semaphore_t sem = dispatch_semaphore_create(0);
[[UNUserNotificationCenter currentNotificationCenter] getNotificationSettingsWithCompletionHandler:^(UNNotificationSettings * _Nonnull settings) {
if (@available(iOS 12 , *) && settings.authorizationStatus == UNAuthorizationStatusProvisional) {
permissionStatus = PermissionStatusProvisional;
} else if (settings.authorizationStatus == UNAuthorizationStatusDenied) {
permissionStatus = PermissionStatusPermanentlyDenied;
} else if (settings.authorizationStatus == UNAuthorizationStatusNotDetermined) {
permissionStatus = PermissionStatusDenied;
}
dispatch_semaphore_signal(sem);
}];
dispatch_semaphore_wait(sem, DISPATCH_TIME_FOREVER);
} else if (@available(iOS 8 , *)) {
UIUserNotificationSettings * setting = [[UIApplication sharedApplication] currentUserNotificationSettings];
if (setting.types == UIUserNotificationTypeNone) permissionStatus = PermissionStatusDenied;
} else {
permissionStatus = PermissionStatusPermanentlyDenied;
}
return permissionStatus;
}
@end
#else
@implementation NotificationPermissionStrategy
@end
#endif
//
// Created by Razvan Lung(long1eu) on 2019-02-15.
// Copyright (c) 2019 The Chromium Authors. All rights reserved.
//
#import <Foundation/Foundation.h>
#import "PermissionHandlerEnums.h"
typedef void (^ServiceStatusHandler)(ServiceStatus serviceStatus);
typedef void (^PermissionStatusHandler)(PermissionStatus permissionStatus);
typedef void (^PermissionErrorHandler)(NSString* errorCode, NSString* errorDescription);
@protocol PermissionStrategy <NSObject>
- (PermissionStatus)checkPermissionStatus:(PermissionGroup)permission;
- (void)checkServiceStatus:(PermissionGroup)permission completionHandler:(ServiceStatusHandler)completionHandler;
- (void)requestPermission:(PermissionGroup)permission completionHandler:(PermissionStatusHandler)completionHandler errorHandler:(PermissionErrorHandler)errorHandler;
@end
//
// PhonePermissionStrategy.h
// permission_handler
//
// Created by Sebastian Roth on 5/20/19.
//
#import <Foundation/Foundation.h>
#import "PermissionStrategy.h"
NS_ASSUME_NONNULL_BEGIN
@interface PhonePermissionStrategy : NSObject<PermissionStrategy>
@end
NS_ASSUME_NONNULL_END
//
// PhonePermissionStrategy.m
// permission_handler
//
// Created by Sebastian Roth on 5/20/19.
//
#import <CoreTelephony/CTTelephonyNetworkInfo.h>
#import <CoreTelephony/CTCarrier.h>
#import "PhonePermissionStrategy.h"
@implementation PhonePermissionStrategy
- (PermissionStatus)checkPermissionStatus:(PermissionGroup)permission {
return PermissionStatusDenied;
}
- (void)checkServiceStatus:(PermissionGroup)permission completionHandler:(ServiceStatusHandler)completionHandler {
// https://stackoverflow.com/a/5095058
if (![[UIApplication sharedApplication] canOpenURL:[NSURL URLWithString:@"tel://"]]) {
completionHandler(ServiceStatusNotApplicable);
}
completionHandler([self canDevicePlaceAPhoneCall] ? ServiceStatusEnabled : ServiceStatusDisabled);
}
- (void)requestPermission:(PermissionGroup)permission completionHandler:(PermissionStatusHandler)completionHandler errorHandler:(PermissionErrorHandler)errorHandler {
completionHandler(PermissionStatusPermanentlyDenied);
}
/**
* Returns YES if the device can place a phone call.
*/
-(bool) canDevicePlaceAPhoneCall {
CTTelephonyNetworkInfo *netInfo = [[CTTelephonyNetworkInfo alloc] init];
if(@available(iOS 12.0, *)) {
NSDictionary<NSString *, CTCarrier *> *providers = [netInfo serviceSubscriberCellularProviders];
for (NSString *key in providers) {
CTCarrier *carrier = [providers objectForKey:key];
if ([self canPlacePhoneCallWithCarrier:carrier]) {
return YES;
}
}
return NO;
} else {
CTCarrier *carrier = [netInfo subscriberCellularProvider];
return [self canPlacePhoneCallWithCarrier:carrier];
}
}
-(bool)canPlacePhoneCallWithCarrier:(CTCarrier *)carrier {
// https://stackoverflow.com/a/11595365
NSString *mnc = [carrier mobileNetworkCode];
if (([mnc length] == 0) || ([mnc isEqualToString:@"65535"])) {
// Device cannot place a call at this time. SIM might be removed.
return NO;
} else {
// Device can place a phone call
return YES;
}
}
@end
//
// Created by Razvan Lung(long1eu) on 2019-02-15.
// Copyright (c) 2019 The Chromium Authors. All rights reserved.
//
#import <Foundation/Foundation.h>
#import "PermissionStrategy.h"
#if PERMISSION_PHOTOS
#import <Photos/Photos.h>
@interface PhotoPermissionStrategy : NSObject <PermissionStrategy>
-(instancetype)initWithAccessAddOnly:(BOOL) addOnly;
@end
#else
#import "UnknownPermissionStrategy.h"
@interface PhotoPermissionStrategy : UnknownPermissionStrategy
@end
#endif
//
// Created by Razvan Lung(long1eu) on 2019-02-15.
// Copyright (c) 2019 The Chromium Authors. All rights reserved.
//
#import "PhotoPermissionStrategy.h"
#if PERMISSION_PHOTOS
@implementation PhotoPermissionStrategy{
bool addOnlyAccessLevel;
}
- (instancetype)initWithAccessAddOnly:(BOOL)addOnly {
self = [super init];
if(self) {
addOnlyAccessLevel = addOnly;
}
return self;
}
- (PermissionStatus)checkPermissionStatus:(PermissionGroup)permission {
return [PhotoPermissionStrategy permissionStatus:addOnlyAccessLevel];
}
- (void)checkServiceStatus:(PermissionGroup)permission completionHandler:(ServiceStatusHandler)completionHandler {
completionHandler(ServiceStatusNotApplicable);
}
- (void)requestPermission:(PermissionGroup)permission completionHandler:(PermissionStatusHandler)completionHandler errorHandler:(PermissionErrorHandler)errorHandler {
PermissionStatus status = [self checkPermissionStatus:permission];
if (status != PermissionStatusDenied) {
completionHandler(status);
return;
}
if(@available(iOS 14, *)) {
[PHPhotoLibrary requestAuthorizationForAccessLevel:(addOnlyAccessLevel)?PHAccessLevelAddOnly:PHAccessLevelReadWrite handler:^(PHAuthorizationStatus authorizationStatus) {
completionHandler([PhotoPermissionStrategy determinePermissionStatus:authorizationStatus]);
}];
}else {
[PHPhotoLibrary requestAuthorization:^(PHAuthorizationStatus authorizationStatus) {
completionHandler([PhotoPermissionStrategy determinePermissionStatus:authorizationStatus]);
}];
}
}
+ (PermissionStatus)permissionStatus:(BOOL) addOnlyAccessLevel {
PHAuthorizationStatus status;
if(@available(iOS 14, *)){
status = [PHPhotoLibrary authorizationStatusForAccessLevel:(addOnlyAccessLevel)?PHAccessLevelAddOnly:PHAccessLevelReadWrite];
}else {
status = [PHPhotoLibrary authorizationStatus];
}
return [PhotoPermissionStrategy determinePermissionStatus:status];
}
+ (PermissionStatus)determinePermissionStatus:(PHAuthorizationStatus)authorizationStatus {
switch (authorizationStatus) {
case PHAuthorizationStatusNotDetermined:
return PermissionStatusDenied;
case PHAuthorizationStatusRestricted:
return PermissionStatusRestricted;
case PHAuthorizationStatusDenied:
return PermissionStatusPermanentlyDenied;
case PHAuthorizationStatusAuthorized:
return PermissionStatusGranted;
case PHAuthorizationStatusLimited:
return PermissionStatusLimited;
}
return PermissionStatusDenied;
}
@end
#else
@implementation PhotoPermissionStrategy
@end
#endif
//
// Created by Razvan Lung(long1eu) on 2019-02-15.
// Copyright (c) 2019 The Chromium Authors. All rights reserved.
//
#import <Foundation/Foundation.h>
#import "PermissionStrategy.h"
#if PERMISSION_SENSORS
#import <CoreMotion/CoreMotion.h>
@interface SensorPermissionStrategy : NSObject <PermissionStrategy>
@end
#else
#import "UnknownPermissionStrategy.h"
@interface SensorPermissionStrategy : UnknownPermissionStrategy
@end
#endif
//
// Created by Razvan Lung(long1eu) on 2019-02-15.
// Copyright (c) 2019 The Chromium Authors. All rights reserved.
//
#import "SensorPermissionStrategy.h"
#if PERMISSION_SENSORS
@implementation SensorPermissionStrategy
- (PermissionStatus)checkPermissionStatus:(PermissionGroup)permission {
return [SensorPermissionStrategy permissionStatus];
}
- (void)checkServiceStatus:(PermissionGroup)permission completionHandler:(ServiceStatusHandler)completionHandler {
if (@available(iOS 11.0, *)) {
completionHandler([CMMotionActivityManager isActivityAvailable]
? ServiceStatusEnabled
: ServiceStatusDisabled
);
}
completionHandler(ServiceStatusDisabled);
}
- (void)requestPermission:(PermissionGroup)permission completionHandler:(PermissionStatusHandler)completionHandler errorHandler:(PermissionErrorHandler)errorHandler {
PermissionStatus status = [self checkPermissionStatus:permission];
if (status != PermissionStatusDenied) {
completionHandler(status);
return;
}
if (@available(iOS 11.0, *)) {
CMMotionActivityManager *motionManager = [[CMMotionActivityManager alloc] init];
NSDate *today = [NSDate new];
[motionManager queryActivityStartingFromDate:today toDate:today toQueue:[NSOperationQueue mainQueue] withHandler:^(NSArray<CMMotionActivity *> *__nullable activities, NSError *__nullable error) {
PermissionStatus status = [SensorPermissionStrategy permissionStatus];
completionHandler(status);
}];
} else {
completionHandler(PermissionStatusDenied);
}
}
+ (PermissionStatus)permissionStatus {
if (@available(iOS 11.0, *)) {
CMAuthorizationStatus status = [CMMotionActivityManager authorizationStatus];
PermissionStatus permissionStatus;
switch (status) {
case CMAuthorizationStatusNotDetermined:
permissionStatus = PermissionStatusDenied;
break;
case CMAuthorizationStatusRestricted:
permissionStatus = PermissionStatusRestricted;
break;
case CMAuthorizationStatusDenied:
permissionStatus = PermissionStatusPermanentlyDenied;
break;
case CMAuthorizationStatusAuthorized:
permissionStatus = PermissionStatusGranted;
break;
default:
permissionStatus = PermissionStatusGranted;
}
return permissionStatus;
}
return PermissionStatusDenied;
}
@end
#else
@implementation SensorPermissionStrategy
@end
#endif
//
// Created by Razvan Lung(long1eu) on 2019-02-15.
// Copyright (c) 2019 The Chromium Authors. All rights reserved.
//
#import <Foundation/Foundation.h>
#import "PermissionStrategy.h"
#if PERMISSION_SPEECH_RECOGNIZER
#import <Speech/Speech.h>
@interface SpeechPermissionStrategy : NSObject <PermissionStrategy>
@end
#else
#import "UnknownPermissionStrategy.h"
@interface SpeechPermissionStrategy : UnknownPermissionStrategy
@end
#endif
//
// Created by Razvan Lung(long1eu) on 2019-02-15.
// Copyright (c) 2019 The Chromium Authors. All rights reserved.
//
#import "SpeechPermissionStrategy.h"
#if PERMISSION_SPEECH_RECOGNIZER
@implementation SpeechPermissionStrategy
- (PermissionStatus)checkPermissionStatus:(PermissionGroup)permission {
return [SpeechPermissionStrategy permissionStatus];
}
- (void)checkServiceStatus:(PermissionGroup)permission completionHandler:(ServiceStatusHandler)completionHandler {
completionHandler(ServiceStatusNotApplicable);
}
- (void)requestPermission:(PermissionGroup)permission completionHandler:(PermissionStatusHandler)completionHandler errorHandler:(PermissionErrorHandler)errorHandler {
PermissionStatus status = [self checkPermissionStatus:permission];
if (status != PermissionStatusDenied) {
completionHandler(status);
return;
}
if (@available(iOS 10.0, *)) {
[SFSpeechRecognizer requestAuthorization:^(SFSpeechRecognizerAuthorizationStatus authorizationStatus) {
completionHandler([SpeechPermissionStrategy determinePermissionStatus:authorizationStatus]);
}];
} else {
completionHandler(PermissionStatusDenied);
}
}
+ (PermissionStatus)permissionStatus {
if (@available(iOS 10.0, *)) {
SFSpeechRecognizerAuthorizationStatus status = [SFSpeechRecognizer authorizationStatus];
return [SpeechPermissionStrategy determinePermissionStatus:status];
}
return PermissionStatusDenied;
}
+ (PermissionStatus)determinePermissionStatus:(SFSpeechRecognizerAuthorizationStatus)authorizationStatus API_AVAILABLE(ios(10.0)){
switch (authorizationStatus) {
case SFSpeechRecognizerAuthorizationStatusNotDetermined:
return PermissionStatusDenied;
case SFSpeechRecognizerAuthorizationStatusDenied:
return PermissionStatusPermanentlyDenied;
case SFSpeechRecognizerAuthorizationStatusRestricted:
return PermissionStatusRestricted;
case SFSpeechRecognizerAuthorizationStatusAuthorized:
return PermissionStatusGranted;
}
return PermissionStatusDenied;
}
@end
#else
@implementation SpeechPermissionStrategy
@end
#endif
//
// StoragePermissionStrategy.h
// permission_handler
//
// Created by Frank Gregor on 06.11.19.
//
#import <Foundation/Foundation.h>
#import "PermissionStrategy.h"
NS_ASSUME_NONNULL_BEGIN
@interface StoragePermissionStrategy : NSObject <PermissionStrategy>
@end
NS_ASSUME_NONNULL_END
//
// StoragePermissionStrategy.m
// permission_handler
//
// Created by Frank Gregor on 06.11.19.
//
#import "StoragePermissionStrategy.h"
@implementation StoragePermissionStrategy
- (PermissionStatus)checkPermissionStatus:(PermissionGroup)permission {
return [StoragePermissionStrategy permissionStatus];
}
- (void)checkServiceStatus:(PermissionGroup)permission completionHandler:(ServiceStatusHandler)completionHandler {
completionHandler(ServiceStatusNotApplicable);
}
- (void)requestPermission:(PermissionGroup)permission completionHandler:(PermissionStatusHandler)completionHandler errorHandler:(PermissionErrorHandler)errorHandler {
completionHandler([StoragePermissionStrategy permissionStatus]);
}
+ (PermissionStatus)permissionStatus {
return PermissionStatusGranted;
}
@end
//
// Created by Razvan Lung(long1eu) on 2019-02-15.
// Copyright (c) 2019 The Chromium Authors. All rights reserved.
//
#import <Foundation/Foundation.h>
#import "PermissionStrategy.h"
@interface UnknownPermissionStrategy : NSObject <PermissionStrategy>
@end
\ No newline at end of file
//
// Created by Razvan Lung(long1eu) on 2019-02-15.
// Copyright (c) 2019 The Chromium Authors. All rights reserved.
//
#import "UnknownPermissionStrategy.h"
@implementation UnknownPermissionStrategy
- (PermissionStatus)checkPermissionStatus:(PermissionGroup)permission {
return PermissionStatusDenied;
}
- (void)checkServiceStatus:(PermissionGroup)permission completionHandler:(ServiceStatusHandler)completionHandler {
completionHandler(ServiceStatusDisabled);
}
- (void)requestPermission:(PermissionGroup)permission completionHandler:(PermissionStatusHandler)completionHandler errorHandler:(PermissionErrorHandler)errorHandler {
completionHandler(PermissionStatusPermanentlyDenied);
}
@end
//
// Created by Razvan Lung on 2019-02-15.
// Copyright (c) 2019 The Chromium Authors. All rights reserved.
//
#import <Foundation/Foundation.h>
#import "PermissionHandlerEnums.h"
@interface Codec : NSObject
+ (PermissionGroup)decodePermissionGroupFrom:(NSNumber *_Nonnull)event;
+ (NSArray*_Nullable)decodePermissionGroupsFrom:(NSArray<NSNumber *> *_Nullable)event;
+ (NSNumber *_Nullable)encodePermissionStatus:(enum PermissionStatus)permissionStatus;
+ (NSNumber *_Nullable)encodeServiceStatus:(enum ServiceStatus)serviceStatus;
@end
//
// Created by Razvan Lung on 2019-02-15.
// Copyright (c) 2019 The Chromium Authors. All rights reserved.
//
#import "Codec.h"
@implementation Codec
+ (PermissionGroup)decodePermissionGroupFrom:(NSNumber *)event {
return (PermissionGroup) event.intValue;
}
+ (NSArray *_Nullable)decodePermissionGroupsFrom:(NSArray<NSNumber *> *)event {
NSMutableArray *result = [[NSMutableArray alloc] init];
for (NSNumber *number in event) {
[result addObject:@([self decodePermissionGroupFrom:number])];
}
return [[NSArray alloc] initWithArray:result];
}
+ (NSNumber *_Nullable)encodePermissionStatus:(enum PermissionStatus)permissionStatus {
return [[NSNumber alloc] initWithInt:permissionStatus];
}
+ (NSNumber *_Nullable)encodeServiceStatus:(enum ServiceStatus)serviceStatus {
return [[NSNumber alloc] initWithInt:serviceStatus];
}
@end
<?xml version="1.0" encoding="UTF-8"?>
<!DOCTYPE plist PUBLIC "-//Apple//DTD PLIST 1.0//EN" "http://www.apple.com/DTDs/PropertyList-1.0.dtd">
<plist version="1.0">
<dict>
<key>NSPrivacyTrackingDomains</key>
<array/>
<key>NSPrivacyAccessedAPITypes</key>
<array>
<dict>
<key>NSPrivacyAccessedAPIType</key>
<string>NSPrivacyAccessedAPICategoryUserDefaults</string>
<key>NSPrivacyAccessedAPITypeReasons</key>
<array>
<string>1C8F.1</string>
</array>
</dict>
</array>
<key>NSPrivacyCollectedDataTypes</key>
<array/>
<key>NSPrivacyTracking</key>
<false/>
</dict>
</plist>
#
# To learn more about a Podspec see http://guides.cocoapods.org/syntax/podspec.html
#
Pod::Spec.new do |s|
s.name = 'permission_handler_apple'
s.version = '9.3.0'
s.summary = 'Permission plugin for Flutter.'
s.description = <<-DESC
Permission plugin for Flutter. This plugin provides a cross-platform (iOS, Android) API to request and check permissions.
DESC
s.homepage = 'https://github.com/baseflowit/flutter-permission-handler'
s.license = { :file => '../LICENSE' }
s.author = { 'Baseflow' => 'hello@baseflow.com' }
s.source = { :path => '.' }
s.source_files = 'Classes/**/*'
s.public_header_files = 'Classes/**/*.h'
s.dependency 'Flutter'
s.ios.deployment_target = '8.0'
s.static_framework = true
s.resource_bundles = {'permission_handler_apple_privacy' => ['Resources/PrivacyInfo.xcprivacy']}
end
name: permission_handler_apple
description: Permission plugin for Flutter. This plugin provides the iOS API to request and check permissions.
repository: https://github.com/baseflow/flutter-permission-handler
issue_tracker: https://github.com/Baseflow/flutter-permission-handler/issues
version: 9.4.5
environment:
sdk: ">=2.15.0 <4.0.0"
flutter: ">=2.8.0"
flutter:
plugin:
implements: permission_handler
platforms:
ios:
pluginClass: PermissionHandlerPlugin
dependencies:
flutter:
sdk: flutter
permission_handler_platform_interface: ^4.2.0
dev_dependencies:
flutter_lints: ^1.0.4
plugin_platform_interface: ^2.0.0
# This file tracks properties of this Flutter project.
# Used by Flutter tool to assess capabilities and perform upgrades etc.
#
# This file should be version controlled and should not be manually edited.
version:
revision: 796c8ef79279f9c774545b3771238c3098dbefab
channel: stable
project_type: package
## 0.1.1
* Updates the dependency on `permission_handler_platform_interface` to version 4.1.0 (SiriKit support is only available for iOS and macOS).
## 0.1.0+2
* Fixes plugin initialization for non-https web app.
* Fixes location permission name.
* Improves error handling in the example app.
## 0.1.0+1
* Updates `permission_handler_platform_interface` dependency to version `^4.0.2`.
## 0.1.0
* Adds an initial implementation of Web support for the permission_handler plugin with camera, notifications, and microphone permissions available.
MIT License
Copyright (c) 2018 Baseflow
Permission is hereby granted, free of charge, to any person obtaining a copy
of this software and associated documentation files (the "Software"), to deal
in the Software without restriction, including without limitation the rights
to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
copies of the Software, and to permit persons to whom the Software is
furnished to do so, subject to the following conditions:
The above copyright notice and this permission notice shall be included in all
copies or substantial portions of the Software.
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
SOFTWARE.
# permission_handler_html
[![pub package](https://img.shields.io/pub/v/permission_handler_html.svg)](https://pub.dartlang.org/packages/permission_handler_html) ![Build status](https://github.com/Baseflow/flutter-permission-handler/workflows/permission_handler_html/badge.svg?branch=master) [![style: flutter lints](https://img.shields.io/badge/style-flutter_lints-40c4ff.svg)](https://pub.dev/packages/flutter_lints)
The official web implementation of the [permission_handler](https://pub.dev/packages/permission_handler) plugin by [Baseflow](https://baseflow.com).
## Usage
This is the officially endorsed web implementation of the permission_handler plugin. This means it will automatically be added to your dependencies when you depend on `permission_handler` in your applications pubspec.yaml.
More detailed instructions on using the API can be found in the [README.md](../permission_handler/README.md) of the [permission_handler](https://pub.dev/packages/permission_handler) package.
## Issues
Please file any issues, bugs, or feature requests as an issue on our [GitHub](https://github.com/Baseflow/flutter-permission-handler/issues) page. Commercial support is available, you can contact us at <hello@baseflow.com>.
## Want to contribute
If you would like to contribute to the plugin (e.g. by improving the documentation, solving a bug, or adding a cool new feature), please carefully review our [contribution guide](../CONTRIBUTING.md) and send us your [pull request](https://github.com/Baseflow/flutter-permission-handler/pulls).
## Author
This permission_handler plugin for Flutter is developed by [Baseflow](https://baseflow.com).
# Miscellaneous
*.class
*.log
*.pyc
*.swp
.DS_Store
.atom/
.buildlog/
.history
.svn/
migrate_working_dir/
# IntelliJ related
*.iml
*.ipr
*.iws
.idea/
# The .vscode folder contains launch configuration and tasks you configure in
# VS Code which you may wish to be included in version control, so this line
# is commented out by default.
#.vscode/
# Flutter/Dart/Pub related
**/doc/api/
**/ios/Flutter/.last_build_id
.dart_tool/
.flutter-plugins
.flutter-plugins-dependencies
.packages
.pub-cache/
.pub/
/build/
# Symbolication related
app.*.symbols
# Obfuscation related
app.*.map.json
# Android Studio will place build artifacts here
/android/app/debug
/android/app/profile
/android/app/release
# This file tracks properties of this Flutter project.
# Used by Flutter tool to assess capabilities and perform upgrades etc.
#
# This file should be version controlled.
version:
revision: 796c8ef79279f9c774545b3771238c3098dbefab
channel: stable
project_type: app
# Tracks metadata for the flutter migrate command
migration:
platforms:
- platform: root
create_revision: 796c8ef79279f9c774545b3771238c3098dbefab
base_revision: 796c8ef79279f9c774545b3771238c3098dbefab
- platform: android
create_revision: 796c8ef79279f9c774545b3771238c3098dbefab
base_revision: 796c8ef79279f9c774545b3771238c3098dbefab
- platform: ios
create_revision: 796c8ef79279f9c774545b3771238c3098dbefab
base_revision: 796c8ef79279f9c774545b3771238c3098dbefab
- platform: linux
create_revision: 796c8ef79279f9c774545b3771238c3098dbefab
base_revision: 796c8ef79279f9c774545b3771238c3098dbefab
- platform: macos
create_revision: 796c8ef79279f9c774545b3771238c3098dbefab
base_revision: 796c8ef79279f9c774545b3771238c3098dbefab
- platform: web
create_revision: 796c8ef79279f9c774545b3771238c3098dbefab
base_revision: 796c8ef79279f9c774545b3771238c3098dbefab
- platform: windows
create_revision: 796c8ef79279f9c774545b3771238c3098dbefab
base_revision: 796c8ef79279f9c774545b3771238c3098dbefab
# User provided section
# List of Local paths (relative to this file) that should be
# ignored by the migrate tool.
#
# Files that are not part of the templates will be ignored by default.
unmanaged_files:
- 'lib/main.dart'
- 'ios/Runner.xcodeproj/project.pbxproj'
# example
A new Flutter project.
## Getting Started
This project is a starting point for a Flutter application.
A few resources to get you started if this is your first Flutter project:
- [Lab: Write your first Flutter app](https://docs.flutter.dev/get-started/codelab)
- [Cookbook: Useful Flutter samples](https://docs.flutter.dev/cookbook)
For help getting started with Flutter development, view the
[online documentation](https://docs.flutter.dev/), which offers tutorials,
samples, guidance on mobile development, and a full API reference.
import 'package:baseflow_plugin_template/baseflow_plugin_template.dart';
import 'package:flutter/material.dart';
import 'package:permission_handler_platform_interface/permission_handler_platform_interface.dart';
void main() {
runApp(BaseflowPluginExample(
pluginName: 'Permission Handler',
githubURL: 'https://github.com/Baseflow/flutter-permission-handler',
pubDevURL: 'https://pub.dev/packages/permission_handler',
pages: [PermissionHandlerWidget.createPage()]));
}
///Defines the main theme color
final MaterialColor themeMaterialColor = BaseflowPluginExample.createMaterialColor(const Color.fromRGBO(48, 49, 60, 1));
/// A Flutter application demonstrating the functionality of this plugin
class PermissionHandlerWidget extends StatefulWidget {
/// Create a page containing the functionality of this plugin
static ExamplePage createPage() {
return ExamplePage(Icons.location_on, (context) => PermissionHandlerWidget());
}
@override
_PermissionHandlerWidgetState createState() => _PermissionHandlerWidgetState();
}
class _PermissionHandlerWidgetState extends State<PermissionHandlerWidget> {
@override
Widget build(BuildContext context) {
return Center(
child: ListView(
children: Permission.values
.where((permission) {
return permission != Permission.unknown &&
permission != Permission.mediaLibrary &&
permission != Permission.photos &&
permission != Permission.photosAddOnly &&
permission != Permission.reminders &&
permission != Permission.appTrackingTransparency &&
permission != Permission.criticalAlerts;
})
.map((permission) => PermissionWidget(permission))
.toList()),
);
}
}
/// Permission widget containing information about the passed [Permission]
class PermissionWidget extends StatefulWidget {
/// Constructs a [PermissionWidget] for the supplied [Permission]
const PermissionWidget(this._permission);
final Permission _permission;
@override
_PermissionState createState() => _PermissionState(_permission);
}
class _PermissionState extends State<PermissionWidget> {
_PermissionState(this._permission);
final Permission _permission;
final PermissionHandlerPlatform _permissionHandler = PermissionHandlerPlatform.instance;
PermissionStatus _permissionStatus = PermissionStatus.denied;
@override
void initState() {
super.initState();
_listenForPermissionStatus();
}
void _listenForPermissionStatus() async {
await _permissionHandler
.checkPermissionStatus(_permission)
.then((status) => setState(() => _permissionStatus = status), onError: (error, st) => print('$error'));
}
Color getPermissionColor() {
switch (_permissionStatus) {
case PermissionStatus.denied:
return Colors.red;
case PermissionStatus.granted:
return Colors.green;
case PermissionStatus.limited:
return Colors.orange;
default:
return Colors.grey;
}
}
@override
Widget build(BuildContext context) {
return ListTile(
title: Text(
_permission.toString(),
style: Theme.of(context).textTheme.bodyLarge,
),
subtitle: Text(
_permissionStatus.toString(),
style: TextStyle(color: getPermissionColor()),
),
trailing: (_permission is PermissionWithService)
? IconButton(
icon: const Icon(
Icons.info,
color: Colors.white,
),
onPressed: () {
checkServiceStatus(context, _permission as PermissionWithService);
})
: null,
onTap: () {
requestPermission(_permission);
},
);
}
void checkServiceStatus(BuildContext context, PermissionWithService permission) async {
ScaffoldMessenger.of(context).showSnackBar(SnackBar(
content: Text((await _permissionHandler.checkServiceStatus(permission)).toString()),
));
}
Future<void> requestPermission(Permission permission) async {
await _permissionHandler.requestPermissions([permission]).then(
(status) => setState(() {
print(status);
_permissionStatus = status[permission] ?? PermissionStatus.denied;
print(_permissionStatus);
}),
onError: (error, st) => print('$error'));
}
}
name: permission_handler_html_example
description: Demonstrates how to use the permission_handler_html plugin.
environment:
sdk: ">=3.0.5 <4.0.0"
dependencies:
baseflow_plugin_template: ^2.1.2
flutter:
sdk: flutter
dev_dependencies:
integration_test:
sdk: flutter
flutter_test:
sdk: flutter
permission_handler_html:
# When depending on this package from a real application you should use:
# permission_handler_web: ^x.y.z
# See https://dart.dev/tools/pub/dependencies#version-constraints
# The example app is bundled with the plugin so we use a path dependency on
# the parent directory to use the current plugin's version.
path: ../
url_launcher: ^6.0.12
flutter:
uses-material-design: true
This diff was suppressed by a .gitattributes entry.
This diff was suppressed by a .gitattributes entry.
This diff was suppressed by a .gitattributes entry.
This diff was suppressed by a .gitattributes entry.
This diff was suppressed by a .gitattributes entry.
<!DOCTYPE html>
<html>
<head>
<!--
If you are serving your web app in a path other than the root, change the
href value below to reflect the base path you are serving from.
The path provided below has to start and end with a slash "/" in order for
it to work correctly.
For more details:
* https://developer.mozilla.org/en-US/docs/Web/HTML/Element/base
This is a placeholder for base href that will be replaced by the value of
the `--base-href` argument provided to `flutter build`.
-->
<base href="$FLUTTER_BASE_HREF">
<meta charset="UTF-8">
<meta content="IE=Edge" http-equiv="X-UA-Compatible">
<meta name="description" content="A new Flutter project.">
<!-- iOS meta tags & icons -->
<meta name="apple-mobile-web-app-capable" content="yes">
<meta name="apple-mobile-web-app-status-bar-style" content="black">
<meta name="apple-mobile-web-app-title" content="example">
<link rel="apple-touch-icon" href="icons/Icon-192.png">
<!-- Favicon -->
<link rel="icon" type="image/png" href="favicon.png"/>
<title>example</title>
<link rel="manifest" href="manifest.json">
<script>
// The value below is injected by flutter build, do not touch.
var serviceWorkerVersion = null;
</script>
<!-- This script adds the flutter initialization JS code -->
<script src="flutter.js" defer></script>
</head>
<body>
<script>
window.addEventListener('load', function(ev) {
// Download main.dart.js
_flutter.loader.loadEntrypoint({
serviceWorker: {
serviceWorkerVersion: serviceWorkerVersion,
},
onEntrypointLoaded: function(engineInitializer) {
engineInitializer.initializeEngine().then(function(appRunner) {
appRunner.runApp();
});
}
});
});
</script>
</body>
</html>
{
"name": "example",
"short_name": "example",
"start_url": ".",
"display": "standalone",
"background_color": "#0175C2",
"theme_color": "#0175C2",
"description": "A new Flutter project.",
"orientation": "portrait-primary",
"prefer_related_applications": false,
"icons": [
{
"src": "icons/Icon-192.png",
"sizes": "192x192",
"type": "image/png"
},
{
"src": "icons/Icon-512.png",
"sizes": "512x512",
"type": "image/png"
},
{
"src": "icons/Icon-maskable-192.png",
"sizes": "192x192",
"type": "image/png",
"purpose": "maskable"
},
{
"src": "icons/Icon-maskable-512.png",
"sizes": "512x512",
"type": "image/png",
"purpose": "maskable"
}
]
}
import 'dart:html' as html;
import 'dart:async';
import 'package:flutter/foundation.dart';
import 'package:flutter_web_plugins/flutter_web_plugins.dart';
import 'package:permission_handler_platform_interface/permission_handler_platform_interface.dart';
import 'web_delegate.dart';
/// Platform implementation of the permission_handler Flutter plugin.
class WebPermissionHandler extends PermissionHandlerPlatform {
static final html.MediaDevices? _devices = html.window.navigator.mediaDevices;
static final html.Geolocation _geolocation =
html.window.navigator.geolocation;
static final html.Permissions? _htmlPermissions =
html.window.navigator.permissions;
final WebDelegate _webDelegate;
/// Registers the web plugin implementation.
static void registerWith(Registrar registrar) {
PermissionHandlerPlatform.instance = WebPermissionHandler(
webDelegate: WebDelegate(
_devices,
_geolocation,
_htmlPermissions,
),
);
}
/// Constructs a WebPermissionHandler.
WebPermissionHandler({
required WebDelegate webDelegate,
}) : _webDelegate = webDelegate;
@override
Future<Map<Permission, PermissionStatus>> requestPermissions(
List<Permission> permissions) async {
return _webDelegate.requestPermissions(permissions);
}
@override
Future<PermissionStatus> checkPermissionStatus(Permission permission) async {
return _webDelegate.checkPermissionStatus(permission);
}
@override
Future<ServiceStatus> checkServiceStatus(Permission permission) async {
return _webDelegate.checkServiceStatus(permission);
}
@override
Future<bool> shouldShowRequestPermissionRationale(
Permission permission) async {
return SynchronousFuture(false);
}
@override
Future<bool> openAppSettings() {
return SynchronousFuture(false);
}
}
import 'dart:html' as html;
import 'dart:async';
import 'package:permission_handler_platform_interface/permission_handler_platform_interface.dart';
/// The delegate class for WebPermissionHandler.
/// Used for dependency injection of html.MediaDevices and html.Permissions objects
class WebDelegate {
/// Constructs a WebDelegate.
WebDelegate(
html.MediaDevices? devices,
html.Geolocation? geolocation,
html.Permissions? permissions,
) : _devices = devices,
_geolocation = geolocation,
_htmlPermissions = permissions;
/// The html media devices object used to request camera and microphone permissions.
final html.MediaDevices? _devices;
/// The html geolocation object used to request location permission.
final html.Geolocation? _geolocation;
/// The html permissions object used to check permission status.
final html.Permissions? _htmlPermissions;
/// The permission name to request access to the camera.
static const _microphonePermissionName = 'microphone';
/// The permission name to request access to the camera.
static const _cameraPermissionName = 'camera';
/// The permission name to request notifications from the user.
static const _notificationsPermissionName = 'notifications';
/// The permission name to request access to the user's location.
/// https://developer.mozilla.org/en-US/docs/Web/API/Permissions/query#name
static const _locationPermissionName = 'geolocation';
/// The status indicates that permission has been granted by the user.
static const _grantedPermissionStatus = 'granted';
/// The status indicates that permission has been denied by the user.
static const _deniedPermissionStatus = 'denied';
/// The status indicates that permission can be requested.
static const _promptPermissionStatus = 'prompt';
PermissionStatus _toPermissionStatus(String? webPermissionStatus) {
switch (webPermissionStatus) {
case _grantedPermissionStatus:
return PermissionStatus.granted;
case _deniedPermissionStatus:
return PermissionStatus.permanentlyDenied;
case _promptPermissionStatus:
default:
return PermissionStatus.denied;
}
}
Future<PermissionStatus> _permissionStatusState(String webPermissionName, html.Permissions? permissions) async {
final webPermissionStatus = await permissions?.query({'name': webPermissionName});
return _toPermissionStatus(webPermissionStatus?.state);
}
Future<bool> _requestMicrophonePermission() async {
if (_devices == null) {
return false;
}
try {
html.MediaStream mediaStream = await _devices!.getUserMedia({'audio': true});
// In browsers, calling [getUserMedia] will start the recording
// automatically right after. This is undesired behavior as
// [requestPermission] is expected to request permission only.
//
// The manual stop action is then needed here for to stop the automatic
// recording.
if (mediaStream.active ?? false) {
final audioTracks = mediaStream.getAudioTracks();
if (audioTracks.isNotEmpty) {
audioTracks[0].stop();
}
}
} on html.DomException {
return false;
}
return true;
}
Future<bool> _requestCameraPermission() async {
if (_devices == null) {
return false;
}
try {
html.MediaStream mediaStream = await _devices!.getUserMedia({'video': true});
// In browsers, calling [getUserMedia] will start the recording
// automatically right after. This is undesired behavior as
// [requestPermission] is expected to request permission only.
//
// The manual stop action is then needed here for to stop the automatic
// recording.
if (mediaStream.active ?? false) {
final videoTracks = mediaStream.getVideoTracks();
if (videoTracks.isNotEmpty) {
videoTracks[0].stop();
}
}
} on html.DomException {
return false;
}
return true;
}
Future<bool> _requestNotificationPermission() async {
return html.Notification.requestPermission().then((permission) => permission == "granted");
}
Future<bool> _requestLocationPermission() async {
try {
return await _geolocation?.getCurrentPosition().then((value) => true) ?? false;
} on html.PositionError {
return false;
}
}
Future<PermissionStatus> _requestSingularPermission(Permission permission) async {
bool permissionGranted = switch (permission) {
Permission.microphone => await _requestMicrophonePermission(),
Permission.camera => await _requestCameraPermission(),
Permission.notification => await _requestNotificationPermission(),
Permission.location => await _requestLocationPermission(),
_ => throw UnsupportedError('The ${permission.toString()} permission is currently not supported on web.')
};
if (!permissionGranted) {
return PermissionStatus.permanentlyDenied;
}
return PermissionStatus.granted;
}
/// Requests the user for access to the supplied list of [Permission]s, if
/// they have not already been granted before.
///
/// Returns a [Map] containing the status per requested [Permission].
Future<Map<Permission, PermissionStatus>> requestPermissions(List<Permission> permissions) async {
final Map<Permission, PermissionStatus> permissionStatusMap = {};
for (final permission in permissions) {
try {
permissionStatusMap[permission] = await _requestSingularPermission(permission);
} on UnimplementedError {
rethrow;
}
}
return permissionStatusMap;
}
/// Checks the current status of the given [Permission].
Future<PermissionStatus> checkPermissionStatus(Permission permission) async {
String webPermissionName;
switch (permission) {
case Permission.microphone:
webPermissionName = _microphonePermissionName;
break;
case Permission.camera:
webPermissionName = _cameraPermissionName;
break;
case Permission.notification:
webPermissionName = _notificationsPermissionName;
break;
case Permission.location:
webPermissionName = _locationPermissionName;
break;
default:
throw UnimplementedError(
'checkPermissionStatus() has not been implemented for ${permission.toString()} '
'on web.',
);
}
return _permissionStatusState(webPermissionName, _htmlPermissions);
}
/// Checks the current status of the service associated with the given
/// [Permission].
Future<ServiceStatus> checkServiceStatus(Permission permission) async {
try {
final permissionStatus = await checkPermissionStatus(permission);
switch (permissionStatus) {
case PermissionStatus.granted:
return ServiceStatus.enabled;
default:
return ServiceStatus.disabled;
}
} on UnimplementedError {
rethrow;
}
}
}
name: permission_handler_html
description: Permission plugin for Flutter. This plugin provides the web API to request and check permissions.
version: 0.1.1
homepage: https://github.com/baseflow/flutter-permission-handler
environment:
sdk: ">=3.0.5 <4.0.0"
flutter: ">=3.16.0"
dependencies:
flutter:
sdk: flutter
flutter_web_plugins:
sdk: flutter
permission_handler_platform_interface: ^4.1.0
dev_dependencies:
flutter_test:
sdk: flutter
flutter_lints: ^2.0.0
mockito: ^5.4.2
build_runner: ^2.1.2
test: ^1.24.4
flutter:
plugin:
implements: permission_handler
platforms:
web:
pluginClass: WebPermissionHandler
fileName: permission_handler_html.dart
import 'dart:html' as html;
import 'package:flutter_test/flutter_test.dart';
import 'package:mockito/mockito.dart';
import 'package:mockito/annotations.dart';
import 'package:permission_handler_platform_interface/permission_handler_platform_interface.dart';
import 'package:permission_handler_html/web_delegate.dart';
import 'permission_handler_web_test.mocks.dart';
@GenerateMocks([
html.DomException,
html.Geolocation,
html.Geoposition,
html.MediaDevices,
html.MediaStream,
html.Navigator,
html.Permissions,
html.PermissionStatus,
html.PositionError,
html.Window,
])
void main() {
TestWidgetsFlutterBinding.ensureInitialized();
final MockDomException domException = MockDomException();
final MockGeolocation geolocation = MockGeolocation();
final MockGeoposition geoposition = MockGeoposition();
final MockMediaDevices mediaDevices = MockMediaDevices();
final MockMediaStream mediaStream = MockMediaStream();
final MockNavigator navigator = MockNavigator();
final MockPermissions permissions = MockPermissions();
final MockPermissionStatus permissionStatus = MockPermissionStatus();
final MockPositionError positionError = MockPositionError();
final MockWindow window = MockWindow();
final WebDelegate fakePlugin =
WebDelegate(mediaDevices, geolocation, permissions);
final List<Permission> testPermissions = [
Permission.camera,
Permission.contacts,
Permission.location,
Permission.microphone,
Permission.notification,
];
when(window.navigator).thenReturn(navigator);
when(navigator.mediaDevices).thenReturn(mediaDevices);
when(navigator.geolocation).thenReturn(geolocation);
when(permissions.query(any)).thenAnswer((_) async => permissionStatus);
// camera stubs
when(mediaStream.active).thenReturn(true);
when(mediaStream.getVideoTracks()).thenReturn(List.empty());
// microphone stubs
when(mediaDevices.getUserMedia({'audio': true}))
.thenAnswer((_) async => mediaStream);
when(mediaStream.getAudioTracks()).thenReturn(List.empty());
// location stubs
when(geolocation.getCurrentPosition()).thenAnswer((_) async => geoposition);
test(
'check permission works for camera before user is prompted for permission',
() async {
when(permissionStatus.state).thenReturn('prompt');
// check permissions status before requesting
final preActualStatus =
await fakePlugin.checkPermissionStatus(Permission.camera);
expect(preActualStatus, PermissionStatus.denied);
});
test('check permission works for camera after user accepts permission',
() async {
when(permissionStatus.state).thenReturn('granted');
// check permissions status after requesting
final postActualStatus =
await fakePlugin.checkPermissionStatus(Permission.camera);
expect(postActualStatus, PermissionStatus.granted);
});
test('check permission works for camera after user declines permission',
() async {
when(permissionStatus.state).thenReturn('denied');
// check permissions status after requesting
final postActualStatus =
await fakePlugin.checkPermissionStatus(Permission.camera);
expect(postActualStatus, PermissionStatus.permanentlyDenied);
});
test('request permission works for camera if user grants permission',
() async {
when(mediaDevices.getUserMedia({'video': true}))
.thenAnswer((_) async => mediaStream);
// request permission
final permissionMap = await fakePlugin.requestPermissions(testPermissions);
expect(permissionMap[Permission.camera], PermissionStatus.granted);
});
test('request permission works for camera if user does not grant permission',
() async {
// stubs
when(mediaDevices.getUserMedia({'video': true})).thenThrow(domException);
// request permission
final permissionMap = await fakePlugin.requestPermissions(testPermissions);
expect(
permissionMap[Permission.camera], PermissionStatus.permanentlyDenied);
});
test(
'check permission works for microphone before user is prompted for permission',
() async {
when(permissionStatus.state).thenReturn('prompt');
// check permissions status before requesting
final preActualStatus =
await fakePlugin.checkPermissionStatus(Permission.microphone);
expect(preActualStatus, PermissionStatus.denied);
});
test('check permission works for microphone after user accepts permission',
() async {
when(permissionStatus.state).thenReturn('granted');
// check permissions status after requesting
final postActualStatus =
await fakePlugin.checkPermissionStatus(Permission.microphone);
expect(postActualStatus, PermissionStatus.granted);
});
test('check permission works for microphone after user declines permission',
() async {
when(permissionStatus.state).thenReturn('denied');
// check permissions status after requesting
final postActualStatus =
await fakePlugin.checkPermissionStatus(Permission.microphone);
expect(postActualStatus, PermissionStatus.permanentlyDenied);
});
test('request permission works for microphone if user grants permission',
() async {
when(mediaDevices.getUserMedia({'audio': true}))
.thenAnswer((_) async => mediaStream);
// request permission
final permissionMap = await fakePlugin.requestPermissions(testPermissions);
expect(permissionMap[Permission.microphone], PermissionStatus.granted);
});
test(
'request permission works for microphone if user does not grant permission',
() async {
// stubs
when(mediaDevices.getUserMedia({'audio': true})).thenThrow(domException);
// request permission
final permissionMap = await fakePlugin.requestPermissions(testPermissions);
expect(permissionMap[Permission.microphone],
PermissionStatus.permanentlyDenied);
});
test(
'check permission works for notification before user is prompted for permission',
() async {
when(permissionStatus.state).thenReturn('prompt');
// check permissions status before requesting
final preActualStatus =
await fakePlugin.checkPermissionStatus(Permission.notification);
expect(preActualStatus, PermissionStatus.denied);
});
test('check permission works for notification after user accepts permission',
() async {
when(permissionStatus.state).thenReturn('granted');
// check permissions status after requesting
final postActualStatus =
await fakePlugin.checkPermissionStatus(Permission.notification);
expect(postActualStatus, PermissionStatus.granted);
});
test('check permission works for notification after user declines permission',
() async {
when(permissionStatus.state).thenReturn('denied');
// check permissions status after requesting
final postActualStatus =
await fakePlugin.checkPermissionStatus(Permission.notification);
expect(postActualStatus, PermissionStatus.permanentlyDenied);
});
test(
'check permission works for location before user is prompted for permission',
() async {
when(permissionStatus.state).thenReturn('prompt');
// check permissions status before requesting
final preActualStatus =
await fakePlugin.checkPermissionStatus(Permission.location);
expect(preActualStatus, PermissionStatus.denied);
});
test('check permission works for location after user accepts permission',
() async {
when(permissionStatus.state).thenReturn('granted');
// check permissions status after requesting
final postActualStatus =
await fakePlugin.checkPermissionStatus(Permission.location);
expect(postActualStatus, PermissionStatus.granted);
});
test('check permission works for location after user declines permission',
() async {
when(permissionStatus.state).thenReturn('denied');
// check permissions status after requesting
final postActualStatus =
await fakePlugin.checkPermissionStatus(Permission.location);
expect(postActualStatus, PermissionStatus.permanentlyDenied);
});
test('request permission works for location if user grants permission',
() async {
when(geolocation.getCurrentPosition()).thenAnswer((_) async => geoposition);
// request permission
final permissionMap = await fakePlugin.requestPermissions(testPermissions);
expect(permissionMap[Permission.location], PermissionStatus.granted);
});
test(
'request permission works for location if user does not grant permission',
() async {
// stubs
when(geolocation.getCurrentPosition()).thenThrow(positionError);
// request permission
final permissionMap = await fakePlugin.requestPermissions(testPermissions);
expect(
permissionMap[Permission.location], PermissionStatus.permanentlyDenied);
});
}
// Mocks generated by Mockito 5.4.2 from annotations
// in permission_handler_web/test/permission_handler_web_test.dart.
// Do not manually edit this file.
// ignore_for_file: no_leading_underscores_for_library_prefixes
import 'dart:async' as _i3;
import 'dart:html' as _i2;
import 'dart:math' as _i4;
import 'package:mockito/mockito.dart' as _i1;
// ignore_for_file: type=lint
// ignore_for_file: avoid_redundant_argument_values
// ignore_for_file: avoid_setters_without_getters
// ignore_for_file: comment_references
// ignore_for_file: implementation_imports
// ignore_for_file: invalid_use_of_visible_for_testing_member
// ignore_for_file: prefer_const_constructors
// ignore_for_file: unnecessary_parenthesis
// ignore_for_file: camel_case_types
// ignore_for_file: subtype_of_sealed_class
class _FakeGeoposition_0 extends _i1.SmartFake implements _i2.Geoposition {
_FakeGeoposition_0(
Object parent,
Invocation parentInvocation,
) : super(
parent,
parentInvocation,
);
}
class _FakeEvents_1 extends _i1.SmartFake implements _i2.Events {
_FakeEvents_1(
Object parent,
Invocation parentInvocation,
) : super(
parent,
parentInvocation,
);
}
class _FakeMediaStream_2 extends _i1.SmartFake implements _i2.MediaStream {
_FakeMediaStream_2(
Object parent,
Invocation parentInvocation,
) : super(
parent,
parentInvocation,
);
}
class _FakeGeolocation_3 extends _i1.SmartFake implements _i2.Geolocation {
_FakeGeolocation_3(
Object parent,
Invocation parentInvocation,
) : super(
parent,
parentInvocation,
);
}
class _FakeRelatedApplication_4 extends _i1.SmartFake
implements _i2.RelatedApplication {
_FakeRelatedApplication_4(
Object parent,
Invocation parentInvocation,
) : super(
parent,
parentInvocation,
);
}
class _FakePermissionStatus_5 extends _i1.SmartFake
implements _i2.PermissionStatus {
_FakePermissionStatus_5(
Object parent,
Invocation parentInvocation,
) : super(
parent,
parentInvocation,
);
}
class _FakeDocument_6 extends _i1.SmartFake implements _i2.Document {
_FakeDocument_6(
Object parent,
Invocation parentInvocation,
) : super(
parent,
parentInvocation,
);
}
class _FakeLocation_7 extends _i1.SmartFake implements _i2.Location {
_FakeLocation_7(
Object parent,
Invocation parentInvocation,
) : super(
parent,
parentInvocation,
);
}
class _FakeConsole_8 extends _i1.SmartFake implements _i2.Console {
_FakeConsole_8(
Object parent,
Invocation parentInvocation,
) : super(
parent,
parentInvocation,
);
}
class _FakeHistory_9 extends _i1.SmartFake implements _i2.History {
_FakeHistory_9(
Object parent,
Invocation parentInvocation,
) : super(
parent,
parentInvocation,
);
}
class _FakeStorage_10 extends _i1.SmartFake implements _i2.Storage {
_FakeStorage_10(
Object parent,
Invocation parentInvocation,
) : super(
parent,
parentInvocation,
);
}
class _FakeNavigator_11 extends _i1.SmartFake implements _i2.Navigator {
_FakeNavigator_11(
Object parent,
Invocation parentInvocation,
) : super(
parent,
parentInvocation,
);
}
class _FakePerformance_12 extends _i1.SmartFake implements _i2.Performance {
_FakePerformance_12(
Object parent,
Invocation parentInvocation,
) : super(
parent,
parentInvocation,
);
}
class _FakeWindowBase_13 extends _i1.SmartFake implements _i2.WindowBase {
_FakeWindowBase_13(
Object parent,
Invocation parentInvocation,
) : super(
parent,
parentInvocation,
);
}
class _FakeFileSystem_14 extends _i1.SmartFake implements _i2.FileSystem {
_FakeFileSystem_14(
Object parent,
Invocation parentInvocation,
) : super(
parent,
parentInvocation,
);
}
class _FakeStylePropertyMapReadonly_15 extends _i1.SmartFake
implements _i2.StylePropertyMapReadonly {
_FakeStylePropertyMapReadonly_15(
Object parent,
Invocation parentInvocation,
) : super(
parent,
parentInvocation,
);
}
class _FakeMediaQueryList_16 extends _i1.SmartFake
implements _i2.MediaQueryList {
_FakeMediaQueryList_16(
Object parent,
Invocation parentInvocation,
) : super(
parent,
parentInvocation,
);
}
class _FakeEntry_17 extends _i1.SmartFake implements _i2.Entry {
_FakeEntry_17(
Object parent,
Invocation parentInvocation,
) : super(
parent,
parentInvocation,
);
}
/// A class which mocks [DomException].
///
/// See the documentation for Mockito's code generation for more information.
class MockDomException extends _i1.Mock implements _i2.DomException {
MockDomException() {
_i1.throwOnMissingStub(this);
}
@override
String get name => (super.noSuchMethod(
Invocation.getter(#name),
returnValue: '',
) as String);
}
/// A class which mocks [Geolocation].
///
/// See the documentation for Mockito's code generation for more information.
class MockGeolocation extends _i1.Mock implements _i2.Geolocation {
MockGeolocation() {
_i1.throwOnMissingStub(this);
}
@override
_i3.Future<_i2.Geoposition> getCurrentPosition({
bool? enableHighAccuracy,
Duration? timeout,
Duration? maximumAge,
}) =>
(super.noSuchMethod(
Invocation.method(
#getCurrentPosition,
[],
{
#enableHighAccuracy: enableHighAccuracy,
#timeout: timeout,
#maximumAge: maximumAge,
},
),
returnValue: _i3.Future<_i2.Geoposition>.value(_FakeGeoposition_0(
this,
Invocation.method(
#getCurrentPosition,
[],
{
#enableHighAccuracy: enableHighAccuracy,
#timeout: timeout,
#maximumAge: maximumAge,
},
),
)),
) as _i3.Future<_i2.Geoposition>);
@override
_i3.Stream<_i2.Geoposition> watchPosition({
bool? enableHighAccuracy,
Duration? timeout,
Duration? maximumAge,
}) =>
(super.noSuchMethod(
Invocation.method(
#watchPosition,
[],
{
#enableHighAccuracy: enableHighAccuracy,
#timeout: timeout,
#maximumAge: maximumAge,
},
),
returnValue: _i3.Stream<_i2.Geoposition>.empty(),
) as _i3.Stream<_i2.Geoposition>);
}
/// A class which mocks [Geoposition].
///
/// See the documentation for Mockito's code generation for more information.
class MockGeoposition extends _i1.Mock implements _i2.Geoposition {
MockGeoposition() {
_i1.throwOnMissingStub(this);
}
}
/// A class which mocks [MediaDevices].
///
/// See the documentation for Mockito's code generation for more information.
class MockMediaDevices extends _i1.Mock implements _i2.MediaDevices {
MockMediaDevices() {
_i1.throwOnMissingStub(this);
}
@override
_i2.Events get on => (super.noSuchMethod(
Invocation.getter(#on),
returnValue: _FakeEvents_1(
this,
Invocation.getter(#on),
),
) as _i2.Events);
@override
_i3.Future<List<dynamic>> enumerateDevices() => (super.noSuchMethod(
Invocation.method(
#enumerateDevices,
[],
),
returnValue: _i3.Future<List<dynamic>>.value(<dynamic>[]),
) as _i3.Future<List<dynamic>>);
@override
Map<dynamic, dynamic> getSupportedConstraints() => (super.noSuchMethod(
Invocation.method(
#getSupportedConstraints,
[],
),
returnValue: <dynamic, dynamic>{},
) as Map<dynamic, dynamic>);
@override
_i3.Future<_i2.MediaStream> getUserMedia(
[Map<dynamic, dynamic>? constraints]) =>
(super.noSuchMethod(
Invocation.method(
#getUserMedia,
[constraints],
),
returnValue: _i3.Future<_i2.MediaStream>.value(_FakeMediaStream_2(
this,
Invocation.method(
#getUserMedia,
[constraints],
),
)),
) as _i3.Future<_i2.MediaStream>);
@override
void addEventListener(
String? type,
_i2.EventListener? listener, [
bool? useCapture,
]) =>
super.noSuchMethod(
Invocation.method(
#addEventListener,
[
type,
listener,
useCapture,
],
),
returnValueForMissingStub: null,
);
@override
void removeEventListener(
String? type,
_i2.EventListener? listener, [
bool? useCapture,
]) =>
super.noSuchMethod(
Invocation.method(
#removeEventListener,
[
type,
listener,
useCapture,
],
),
returnValueForMissingStub: null,
);
@override
bool dispatchEvent(_i2.Event? event) => (super.noSuchMethod(
Invocation.method(
#dispatchEvent,
[event],
),
returnValue: false,
) as bool);
}
/// A class which mocks [MediaStream].
///
/// See the documentation for Mockito's code generation for more information.
class MockMediaStream extends _i1.Mock implements _i2.MediaStream {
MockMediaStream() {
_i1.throwOnMissingStub(this);
}
@override
_i3.Stream<_i2.Event> get onAddTrack => (super.noSuchMethod(
Invocation.getter(#onAddTrack),
returnValue: _i3.Stream<_i2.Event>.empty(),
) as _i3.Stream<_i2.Event>);
@override
_i3.Stream<_i2.Event> get onRemoveTrack => (super.noSuchMethod(
Invocation.getter(#onRemoveTrack),
returnValue: _i3.Stream<_i2.Event>.empty(),
) as _i3.Stream<_i2.Event>);
@override
_i2.Events get on => (super.noSuchMethod(
Invocation.getter(#on),
returnValue: _FakeEvents_1(
this,
Invocation.getter(#on),
),
) as _i2.Events);
@override
void addTrack(_i2.MediaStreamTrack? track) => super.noSuchMethod(
Invocation.method(
#addTrack,
[track],
),
returnValueForMissingStub: null,
);
@override
_i2.MediaStream clone() => (super.noSuchMethod(
Invocation.method(
#clone,
[],
),
returnValue: _FakeMediaStream_2(
this,
Invocation.method(
#clone,
[],
),
),
) as _i2.MediaStream);
@override
List<_i2.MediaStreamTrack> getAudioTracks() => (super.noSuchMethod(
Invocation.method(
#getAudioTracks,
[],
),
returnValue: <_i2.MediaStreamTrack>[],
) as List<_i2.MediaStreamTrack>);
@override
_i2.MediaStreamTrack? getTrackById(String? trackId) =>
(super.noSuchMethod(Invocation.method(
#getTrackById,
[trackId],
)) as _i2.MediaStreamTrack?);
@override
List<_i2.MediaStreamTrack> getTracks() => (super.noSuchMethod(
Invocation.method(
#getTracks,
[],
),
returnValue: <_i2.MediaStreamTrack>[],
) as List<_i2.MediaStreamTrack>);
@override
List<_i2.MediaStreamTrack> getVideoTracks() => (super.noSuchMethod(
Invocation.method(
#getVideoTracks,
[],
),
returnValue: <_i2.MediaStreamTrack>[],
) as List<_i2.MediaStreamTrack>);
@override
void removeTrack(_i2.MediaStreamTrack? track) => super.noSuchMethod(
Invocation.method(
#removeTrack,
[track],
),
returnValueForMissingStub: null,
);
@override
void addEventListener(
String? type,
_i2.EventListener? listener, [
bool? useCapture,
]) =>
super.noSuchMethod(
Invocation.method(
#addEventListener,
[
type,
listener,
useCapture,
],
),
returnValueForMissingStub: null,
);
@override
void removeEventListener(
String? type,
_i2.EventListener? listener, [
bool? useCapture,
]) =>
super.noSuchMethod(
Invocation.method(
#removeEventListener,
[
type,
listener,
useCapture,
],
),
returnValueForMissingStub: null,
);
@override
bool dispatchEvent(_i2.Event? event) => (super.noSuchMethod(
Invocation.method(
#dispatchEvent,
[event],
),
returnValue: false,
) as bool);
}
/// A class which mocks [Navigator].
///
/// See the documentation for Mockito's code generation for more information.
class MockNavigator extends _i1.Mock implements _i2.Navigator {
MockNavigator() {
_i1.throwOnMissingStub(this);
}
@override
String get language => (super.noSuchMethod(
Invocation.getter(#language),
returnValue: '',
) as String);
@override
_i2.Geolocation get geolocation => (super.noSuchMethod(
Invocation.getter(#geolocation),
returnValue: _FakeGeolocation_3(
this,
Invocation.getter(#geolocation),
),
) as _i2.Geolocation);
@override
String get vendor => (super.noSuchMethod(
Invocation.getter(#vendor),
returnValue: '',
) as String);
@override
String get vendorSub => (super.noSuchMethod(
Invocation.getter(#vendorSub),
returnValue: '',
) as String);
@override
String get appCodeName => (super.noSuchMethod(
Invocation.getter(#appCodeName),
returnValue: '',
) as String);
@override
String get appName => (super.noSuchMethod(
Invocation.getter(#appName),
returnValue: '',
) as String);
@override
String get appVersion => (super.noSuchMethod(
Invocation.getter(#appVersion),
returnValue: '',
) as String);
@override
String get product => (super.noSuchMethod(
Invocation.getter(#product),
returnValue: '',
) as String);
@override
String get userAgent => (super.noSuchMethod(
Invocation.getter(#userAgent),
returnValue: '',
) as String);
@override
List<_i2.Gamepad?> getGamepads() => (super.noSuchMethod(
Invocation.method(
#getGamepads,
[],
),
returnValue: <_i2.Gamepad?>[],
) as List<_i2.Gamepad?>);
@override
_i3.Future<_i2.MediaStream> getUserMedia({
dynamic audio = false,
dynamic video = false,
}) =>
(super.noSuchMethod(
Invocation.method(
#getUserMedia,
[],
{
#audio: audio,
#video: video,
},
),
returnValue: _i3.Future<_i2.MediaStream>.value(_FakeMediaStream_2(
this,
Invocation.method(
#getUserMedia,
[],
{
#audio: audio,
#video: video,
},
),
)),
) as _i3.Future<_i2.MediaStream>);
@override
void cancelKeyboardLock() => super.noSuchMethod(
Invocation.method(
#cancelKeyboardLock,
[],
),
returnValueForMissingStub: null,
);
@override
_i3.Future<dynamic> getBattery() => (super.noSuchMethod(
Invocation.method(
#getBattery,
[],
),
returnValue: _i3.Future<dynamic>.value(),
) as _i3.Future<dynamic>);
@override
_i3.Future<_i2.RelatedApplication> getInstalledRelatedApps() =>
(super.noSuchMethod(
Invocation.method(
#getInstalledRelatedApps,
[],
),
returnValue:
_i3.Future<_i2.RelatedApplication>.value(_FakeRelatedApplication_4(
this,
Invocation.method(
#getInstalledRelatedApps,
[],
),
)),
) as _i3.Future<_i2.RelatedApplication>);
@override
_i3.Future<dynamic> getVRDisplays() => (super.noSuchMethod(
Invocation.method(
#getVRDisplays,
[],
),
returnValue: _i3.Future<dynamic>.value(),
) as _i3.Future<dynamic>);
@override
void registerProtocolHandler(
String? scheme,
String? url,
String? title,
) =>
super.noSuchMethod(
Invocation.method(
#registerProtocolHandler,
[
scheme,
url,
title,
],
),
returnValueForMissingStub: null,
);
@override
_i3.Future<dynamic> requestKeyboardLock([List<String>? keyCodes]) =>
(super.noSuchMethod(
Invocation.method(
#requestKeyboardLock,
[keyCodes],
),
returnValue: _i3.Future<dynamic>.value(),
) as _i3.Future<dynamic>);
@override
_i3.Future<dynamic> requestMidiAccess([Map<dynamic, dynamic>? options]) =>
(super.noSuchMethod(
Invocation.method(
#requestMidiAccess,
[options],
),
returnValue: _i3.Future<dynamic>.value(),
) as _i3.Future<dynamic>);
@override
_i3.Future<dynamic> requestMediaKeySystemAccess(
String? keySystem,
List<Map<dynamic, dynamic>>? supportedConfigurations,
) =>
(super.noSuchMethod(
Invocation.method(
#requestMediaKeySystemAccess,
[
keySystem,
supportedConfigurations,
],
),
returnValue: _i3.Future<dynamic>.value(),
) as _i3.Future<dynamic>);
@override
bool sendBeacon(
String? url,
Object? data,
) =>
(super.noSuchMethod(
Invocation.method(
#sendBeacon,
[
url,
data,
],
),
returnValue: false,
) as bool);
@override
_i3.Future<dynamic> share([Map<dynamic, dynamic>? data]) =>
(super.noSuchMethod(
Invocation.method(
#share,
[data],
),
returnValue: _i3.Future<dynamic>.value(),
) as _i3.Future<dynamic>);
}
/// A class which mocks [Permissions].
///
/// See the documentation for Mockito's code generation for more information.
class MockPermissions extends _i1.Mock implements _i2.Permissions {
MockPermissions() {
_i1.throwOnMissingStub(this);
}
@override
_i3.Future<_i2.PermissionStatus> query(Map<dynamic, dynamic>? permission) =>
(super.noSuchMethod(
Invocation.method(
#query,
[permission],
),
returnValue:
_i3.Future<_i2.PermissionStatus>.value(_FakePermissionStatus_5(
this,
Invocation.method(
#query,
[permission],
),
)),
) as _i3.Future<_i2.PermissionStatus>);
@override
_i3.Future<_i2.PermissionStatus> request(
Map<dynamic, dynamic>? permissions) =>
(super.noSuchMethod(
Invocation.method(
#request,
[permissions],
),
returnValue:
_i3.Future<_i2.PermissionStatus>.value(_FakePermissionStatus_5(
this,
Invocation.method(
#request,
[permissions],
),
)),
) as _i3.Future<_i2.PermissionStatus>);
@override
_i3.Future<_i2.PermissionStatus> requestAll(
List<Map<dynamic, dynamic>>? permissions) =>
(super.noSuchMethod(
Invocation.method(
#requestAll,
[permissions],
),
returnValue:
_i3.Future<_i2.PermissionStatus>.value(_FakePermissionStatus_5(
this,
Invocation.method(
#requestAll,
[permissions],
),
)),
) as _i3.Future<_i2.PermissionStatus>);
@override
_i3.Future<_i2.PermissionStatus> revoke(Map<dynamic, dynamic>? permission) =>
(super.noSuchMethod(
Invocation.method(
#revoke,
[permission],
),
returnValue:
_i3.Future<_i2.PermissionStatus>.value(_FakePermissionStatus_5(
this,
Invocation.method(
#revoke,
[permission],
),
)),
) as _i3.Future<_i2.PermissionStatus>);
}
/// A class which mocks [PermissionStatus].
///
/// See the documentation for Mockito's code generation for more information.
class MockPermissionStatus extends _i1.Mock implements _i2.PermissionStatus {
MockPermissionStatus() {
_i1.throwOnMissingStub(this);
}
@override
_i3.Stream<_i2.Event> get onChange => (super.noSuchMethod(
Invocation.getter(#onChange),
returnValue: _i3.Stream<_i2.Event>.empty(),
) as _i3.Stream<_i2.Event>);
@override
_i2.Events get on => (super.noSuchMethod(
Invocation.getter(#on),
returnValue: _FakeEvents_1(
this,
Invocation.getter(#on),
),
) as _i2.Events);
@override
void addEventListener(
String? type,
_i2.EventListener? listener, [
bool? useCapture,
]) =>
super.noSuchMethod(
Invocation.method(
#addEventListener,
[
type,
listener,
useCapture,
],
),
returnValueForMissingStub: null,
);
@override
void removeEventListener(
String? type,
_i2.EventListener? listener, [
bool? useCapture,
]) =>
super.noSuchMethod(
Invocation.method(
#removeEventListener,
[
type,
listener,
useCapture,
],
),
returnValueForMissingStub: null,
);
@override
bool dispatchEvent(_i2.Event? event) => (super.noSuchMethod(
Invocation.method(
#dispatchEvent,
[event],
),
returnValue: false,
) as bool);
}
/// A class which mocks [PositionError].
///
/// See the documentation for Mockito's code generation for more information.
class MockPositionError extends _i1.Mock implements _i2.PositionError {
MockPositionError() {
_i1.throwOnMissingStub(this);
}
}
/// A class which mocks [Window].
///
/// See the documentation for Mockito's code generation for more information.
class MockWindow extends _i1.Mock implements _i2.Window {
MockWindow() {
_i1.throwOnMissingStub(this);
}
@override
_i3.Future<num> get animationFrame => (super.noSuchMethod(
Invocation.getter(#animationFrame),
returnValue: _i3.Future<num>.value(0),
) as _i3.Future<num>);
@override
_i2.Document get document => (super.noSuchMethod(
Invocation.getter(#document),
returnValue: _FakeDocument_6(
this,
Invocation.getter(#document),
),
) as _i2.Document);
@override
_i2.Location get location => (super.noSuchMethod(
Invocation.getter(#location),
returnValue: _FakeLocation_7(
this,
Invocation.getter(#location),
),
) as _i2.Location);
@override
set location(_i2.LocationBase? value) => super.noSuchMethod(
Invocation.setter(
#location,
value,
),
returnValueForMissingStub: null,
);
@override
_i2.Console get console => (super.noSuchMethod(
Invocation.getter(#console),
returnValue: _FakeConsole_8(
this,
Invocation.getter(#console),
),
) as _i2.Console);
@override
set defaultStatus(String? value) => super.noSuchMethod(
Invocation.setter(
#defaultStatus,
value,
),
returnValueForMissingStub: null,
);
@override
set defaultstatus(String? value) => super.noSuchMethod(
Invocation.setter(
#defaultstatus,
value,
),
returnValueForMissingStub: null,
);
@override
num get devicePixelRatio => (super.noSuchMethod(
Invocation.getter(#devicePixelRatio),
returnValue: 0,
) as num);
@override
_i2.History get history => (super.noSuchMethod(
Invocation.getter(#history),
returnValue: _FakeHistory_9(
this,
Invocation.getter(#history),
),
) as _i2.History);
@override
_i2.Storage get localStorage => (super.noSuchMethod(
Invocation.getter(#localStorage),
returnValue: _FakeStorage_10(
this,
Invocation.getter(#localStorage),
),
) as _i2.Storage);
@override
set name(String? value) => super.noSuchMethod(
Invocation.setter(
#name,
value,
),
returnValueForMissingStub: null,
);
@override
_i2.Navigator get navigator => (super.noSuchMethod(
Invocation.getter(#navigator),
returnValue: _FakeNavigator_11(
this,
Invocation.getter(#navigator),
),
) as _i2.Navigator);
@override
set opener(_i2.WindowBase? value) => super.noSuchMethod(
Invocation.setter(
#opener,
value,
),
returnValueForMissingStub: null,
);
@override
int get outerHeight => (super.noSuchMethod(
Invocation.getter(#outerHeight),
returnValue: 0,
) as int);
@override
int get outerWidth => (super.noSuchMethod(
Invocation.getter(#outerWidth),
returnValue: 0,
) as int);
@override
_i2.Performance get performance => (super.noSuchMethod(
Invocation.getter(#performance),
returnValue: _FakePerformance_12(
this,
Invocation.getter(#performance),
),
) as _i2.Performance);
@override
_i2.Storage get sessionStorage => (super.noSuchMethod(
Invocation.getter(#sessionStorage),
returnValue: _FakeStorage_10(
this,
Invocation.getter(#sessionStorage),
),
) as _i2.Storage);
@override
set status(String? value) => super.noSuchMethod(
Invocation.setter(
#status,
value,
),
returnValueForMissingStub: null,
);
@override
_i3.Stream<_i2.Event> get onContentLoaded => (super.noSuchMethod(
Invocation.getter(#onContentLoaded),
returnValue: _i3.Stream<_i2.Event>.empty(),
) as _i3.Stream<_i2.Event>);
@override
_i3.Stream<_i2.Event> get onAbort => (super.noSuchMethod(
Invocation.getter(#onAbort),
returnValue: _i3.Stream<_i2.Event>.empty(),
) as _i3.Stream<_i2.Event>);
@override
_i3.Stream<_i2.Event> get onBlur => (super.noSuchMethod(
Invocation.getter(#onBlur),
returnValue: _i3.Stream<_i2.Event>.empty(),
) as _i3.Stream<_i2.Event>);
@override
_i3.Stream<_i2.Event> get onCanPlay => (super.noSuchMethod(
Invocation.getter(#onCanPlay),
returnValue: _i3.Stream<_i2.Event>.empty(),
) as _i3.Stream<_i2.Event>);
@override
_i3.Stream<_i2.Event> get onCanPlayThrough => (super.noSuchMethod(
Invocation.getter(#onCanPlayThrough),
returnValue: _i3.Stream<_i2.Event>.empty(),
) as _i3.Stream<_i2.Event>);
@override
_i3.Stream<_i2.Event> get onChange => (super.noSuchMethod(
Invocation.getter(#onChange),
returnValue: _i3.Stream<_i2.Event>.empty(),
) as _i3.Stream<_i2.Event>);
@override
_i3.Stream<_i2.MouseEvent> get onClick => (super.noSuchMethod(
Invocation.getter(#onClick),
returnValue: _i3.Stream<_i2.MouseEvent>.empty(),
) as _i3.Stream<_i2.MouseEvent>);
@override
_i3.Stream<_i2.MouseEvent> get onContextMenu => (super.noSuchMethod(
Invocation.getter(#onContextMenu),
returnValue: _i3.Stream<_i2.MouseEvent>.empty(),
) as _i3.Stream<_i2.MouseEvent>);
@override
_i3.Stream<_i2.Event> get onDoubleClick => (super.noSuchMethod(
Invocation.getter(#onDoubleClick),
returnValue: _i3.Stream<_i2.Event>.empty(),
) as _i3.Stream<_i2.Event>);
@override
_i3.Stream<_i2.DeviceMotionEvent> get onDeviceMotion => (super.noSuchMethod(
Invocation.getter(#onDeviceMotion),
returnValue: _i3.Stream<_i2.DeviceMotionEvent>.empty(),
) as _i3.Stream<_i2.DeviceMotionEvent>);
@override
_i3.Stream<_i2.DeviceOrientationEvent> get onDeviceOrientation =>
(super.noSuchMethod(
Invocation.getter(#onDeviceOrientation),
returnValue: _i3.Stream<_i2.DeviceOrientationEvent>.empty(),
) as _i3.Stream<_i2.DeviceOrientationEvent>);
@override
_i3.Stream<_i2.MouseEvent> get onDrag => (super.noSuchMethod(
Invocation.getter(#onDrag),
returnValue: _i3.Stream<_i2.MouseEvent>.empty(),
) as _i3.Stream<_i2.MouseEvent>);
@override
_i3.Stream<_i2.MouseEvent> get onDragEnd => (super.noSuchMethod(
Invocation.getter(#onDragEnd),
returnValue: _i3.Stream<_i2.MouseEvent>.empty(),
) as _i3.Stream<_i2.MouseEvent>);
@override
_i3.Stream<_i2.MouseEvent> get onDragEnter => (super.noSuchMethod(
Invocation.getter(#onDragEnter),
returnValue: _i3.Stream<_i2.MouseEvent>.empty(),
) as _i3.Stream<_i2.MouseEvent>);
@override
_i3.Stream<_i2.MouseEvent> get onDragLeave => (super.noSuchMethod(
Invocation.getter(#onDragLeave),
returnValue: _i3.Stream<_i2.MouseEvent>.empty(),
) as _i3.Stream<_i2.MouseEvent>);
@override
_i3.Stream<_i2.MouseEvent> get onDragOver => (super.noSuchMethod(
Invocation.getter(#onDragOver),
returnValue: _i3.Stream<_i2.MouseEvent>.empty(),
) as _i3.Stream<_i2.MouseEvent>);
@override
_i3.Stream<_i2.MouseEvent> get onDragStart => (super.noSuchMethod(
Invocation.getter(#onDragStart),
returnValue: _i3.Stream<_i2.MouseEvent>.empty(),
) as _i3.Stream<_i2.MouseEvent>);
@override
_i3.Stream<_i2.MouseEvent> get onDrop => (super.noSuchMethod(
Invocation.getter(#onDrop),
returnValue: _i3.Stream<_i2.MouseEvent>.empty(),
) as _i3.Stream<_i2.MouseEvent>);
@override
_i3.Stream<_i2.Event> get onDurationChange => (super.noSuchMethod(
Invocation.getter(#onDurationChange),
returnValue: _i3.Stream<_i2.Event>.empty(),
) as _i3.Stream<_i2.Event>);
@override
_i3.Stream<_i2.Event> get onEmptied => (super.noSuchMethod(
Invocation.getter(#onEmptied),
returnValue: _i3.Stream<_i2.Event>.empty(),
) as _i3.Stream<_i2.Event>);
@override
_i3.Stream<_i2.Event> get onEnded => (super.noSuchMethod(
Invocation.getter(#onEnded),
returnValue: _i3.Stream<_i2.Event>.empty(),
) as _i3.Stream<_i2.Event>);
@override
_i3.Stream<_i2.Event> get onError => (super.noSuchMethod(
Invocation.getter(#onError),
returnValue: _i3.Stream<_i2.Event>.empty(),
) as _i3.Stream<_i2.Event>);
@override
_i3.Stream<_i2.Event> get onFocus => (super.noSuchMethod(
Invocation.getter(#onFocus),
returnValue: _i3.Stream<_i2.Event>.empty(),
) as _i3.Stream<_i2.Event>);
@override
_i3.Stream<_i2.Event> get onHashChange => (super.noSuchMethod(
Invocation.getter(#onHashChange),
returnValue: _i3.Stream<_i2.Event>.empty(),
) as _i3.Stream<_i2.Event>);
@override
_i3.Stream<_i2.Event> get onInput => (super.noSuchMethod(
Invocation.getter(#onInput),
returnValue: _i3.Stream<_i2.Event>.empty(),
) as _i3.Stream<_i2.Event>);
@override
_i3.Stream<_i2.Event> get onInvalid => (super.noSuchMethod(
Invocation.getter(#onInvalid),
returnValue: _i3.Stream<_i2.Event>.empty(),
) as _i3.Stream<_i2.Event>);
@override
_i3.Stream<_i2.KeyboardEvent> get onKeyDown => (super.noSuchMethod(
Invocation.getter(#onKeyDown),
returnValue: _i3.Stream<_i2.KeyboardEvent>.empty(),
) as _i3.Stream<_i2.KeyboardEvent>);
@override
_i3.Stream<_i2.KeyboardEvent> get onKeyPress => (super.noSuchMethod(
Invocation.getter(#onKeyPress),
returnValue: _i3.Stream<_i2.KeyboardEvent>.empty(),
) as _i3.Stream<_i2.KeyboardEvent>);
@override
_i3.Stream<_i2.KeyboardEvent> get onKeyUp => (super.noSuchMethod(
Invocation.getter(#onKeyUp),
returnValue: _i3.Stream<_i2.KeyboardEvent>.empty(),
) as _i3.Stream<_i2.KeyboardEvent>);
@override
_i3.Stream<_i2.Event> get onLoad => (super.noSuchMethod(
Invocation.getter(#onLoad),
returnValue: _i3.Stream<_i2.Event>.empty(),
) as _i3.Stream<_i2.Event>);
@override
_i3.Stream<_i2.Event> get onLoadedData => (super.noSuchMethod(
Invocation.getter(#onLoadedData),
returnValue: _i3.Stream<_i2.Event>.empty(),
) as _i3.Stream<_i2.Event>);
@override
_i3.Stream<_i2.Event> get onLoadedMetadata => (super.noSuchMethod(
Invocation.getter(#onLoadedMetadata),
returnValue: _i3.Stream<_i2.Event>.empty(),
) as _i3.Stream<_i2.Event>);
@override
_i3.Stream<_i2.Event> get onLoadStart => (super.noSuchMethod(
Invocation.getter(#onLoadStart),
returnValue: _i3.Stream<_i2.Event>.empty(),
) as _i3.Stream<_i2.Event>);
@override
_i3.Stream<_i2.MessageEvent> get onMessage => (super.noSuchMethod(
Invocation.getter(#onMessage),
returnValue: _i3.Stream<_i2.MessageEvent>.empty(),
) as _i3.Stream<_i2.MessageEvent>);
@override
_i3.Stream<_i2.MouseEvent> get onMouseDown => (super.noSuchMethod(
Invocation.getter(#onMouseDown),
returnValue: _i3.Stream<_i2.MouseEvent>.empty(),
) as _i3.Stream<_i2.MouseEvent>);
@override
_i3.Stream<_i2.MouseEvent> get onMouseEnter => (super.noSuchMethod(
Invocation.getter(#onMouseEnter),
returnValue: _i3.Stream<_i2.MouseEvent>.empty(),
) as _i3.Stream<_i2.MouseEvent>);
@override
_i3.Stream<_i2.MouseEvent> get onMouseLeave => (super.noSuchMethod(
Invocation.getter(#onMouseLeave),
returnValue: _i3.Stream<_i2.MouseEvent>.empty(),
) as _i3.Stream<_i2.MouseEvent>);
@override
_i3.Stream<_i2.MouseEvent> get onMouseMove => (super.noSuchMethod(
Invocation.getter(#onMouseMove),
returnValue: _i3.Stream<_i2.MouseEvent>.empty(),
) as _i3.Stream<_i2.MouseEvent>);
@override
_i3.Stream<_i2.MouseEvent> get onMouseOut => (super.noSuchMethod(
Invocation.getter(#onMouseOut),
returnValue: _i3.Stream<_i2.MouseEvent>.empty(),
) as _i3.Stream<_i2.MouseEvent>);
@override
_i3.Stream<_i2.MouseEvent> get onMouseOver => (super.noSuchMethod(
Invocation.getter(#onMouseOver),
returnValue: _i3.Stream<_i2.MouseEvent>.empty(),
) as _i3.Stream<_i2.MouseEvent>);
@override
_i3.Stream<_i2.MouseEvent> get onMouseUp => (super.noSuchMethod(
Invocation.getter(#onMouseUp),
returnValue: _i3.Stream<_i2.MouseEvent>.empty(),
) as _i3.Stream<_i2.MouseEvent>);
@override
_i3.Stream<_i2.WheelEvent> get onMouseWheel => (super.noSuchMethod(
Invocation.getter(#onMouseWheel),
returnValue: _i3.Stream<_i2.WheelEvent>.empty(),
) as _i3.Stream<_i2.WheelEvent>);
@override
_i3.Stream<_i2.Event> get onOffline => (super.noSuchMethod(
Invocation.getter(#onOffline),
returnValue: _i3.Stream<_i2.Event>.empty(),
) as _i3.Stream<_i2.Event>);
@override
_i3.Stream<_i2.Event> get onOnline => (super.noSuchMethod(
Invocation.getter(#onOnline),
returnValue: _i3.Stream<_i2.Event>.empty(),
) as _i3.Stream<_i2.Event>);
@override
_i3.Stream<_i2.Event> get onPageHide => (super.noSuchMethod(
Invocation.getter(#onPageHide),
returnValue: _i3.Stream<_i2.Event>.empty(),
) as _i3.Stream<_i2.Event>);
@override
_i3.Stream<_i2.Event> get onPageShow => (super.noSuchMethod(
Invocation.getter(#onPageShow),
returnValue: _i3.Stream<_i2.Event>.empty(),
) as _i3.Stream<_i2.Event>);
@override
_i3.Stream<_i2.Event> get onPause => (super.noSuchMethod(
Invocation.getter(#onPause),
returnValue: _i3.Stream<_i2.Event>.empty(),
) as _i3.Stream<_i2.Event>);
@override
_i3.Stream<_i2.Event> get onPlay => (super.noSuchMethod(
Invocation.getter(#onPlay),
returnValue: _i3.Stream<_i2.Event>.empty(),
) as _i3.Stream<_i2.Event>);
@override
_i3.Stream<_i2.Event> get onPlaying => (super.noSuchMethod(
Invocation.getter(#onPlaying),
returnValue: _i3.Stream<_i2.Event>.empty(),
) as _i3.Stream<_i2.Event>);
@override
_i3.Stream<_i2.PopStateEvent> get onPopState => (super.noSuchMethod(
Invocation.getter(#onPopState),
returnValue: _i3.Stream<_i2.PopStateEvent>.empty(),
) as _i3.Stream<_i2.PopStateEvent>);
@override
_i3.Stream<_i2.Event> get onProgress => (super.noSuchMethod(
Invocation.getter(#onProgress),
returnValue: _i3.Stream<_i2.Event>.empty(),
) as _i3.Stream<_i2.Event>);
@override
_i3.Stream<_i2.Event> get onRateChange => (super.noSuchMethod(
Invocation.getter(#onRateChange),
returnValue: _i3.Stream<_i2.Event>.empty(),
) as _i3.Stream<_i2.Event>);
@override
_i3.Stream<_i2.Event> get onReset => (super.noSuchMethod(
Invocation.getter(#onReset),
returnValue: _i3.Stream<_i2.Event>.empty(),
) as _i3.Stream<_i2.Event>);
@override
_i3.Stream<_i2.Event> get onResize => (super.noSuchMethod(
Invocation.getter(#onResize),
returnValue: _i3.Stream<_i2.Event>.empty(),
) as _i3.Stream<_i2.Event>);
@override
_i3.Stream<_i2.Event> get onScroll => (super.noSuchMethod(
Invocation.getter(#onScroll),
returnValue: _i3.Stream<_i2.Event>.empty(),
) as _i3.Stream<_i2.Event>);
@override
_i3.Stream<_i2.Event> get onSearch => (super.noSuchMethod(
Invocation.getter(#onSearch),
returnValue: _i3.Stream<_i2.Event>.empty(),
) as _i3.Stream<_i2.Event>);
@override
_i3.Stream<_i2.Event> get onSeeked => (super.noSuchMethod(
Invocation.getter(#onSeeked),
returnValue: _i3.Stream<_i2.Event>.empty(),
) as _i3.Stream<_i2.Event>);
@override
_i3.Stream<_i2.Event> get onSeeking => (super.noSuchMethod(
Invocation.getter(#onSeeking),
returnValue: _i3.Stream<_i2.Event>.empty(),
) as _i3.Stream<_i2.Event>);
@override
_i3.Stream<_i2.Event> get onSelect => (super.noSuchMethod(
Invocation.getter(#onSelect),
returnValue: _i3.Stream<_i2.Event>.empty(),
) as _i3.Stream<_i2.Event>);
@override
_i3.Stream<_i2.Event> get onStalled => (super.noSuchMethod(
Invocation.getter(#onStalled),
returnValue: _i3.Stream<_i2.Event>.empty(),
) as _i3.Stream<_i2.Event>);
@override
_i3.Stream<_i2.StorageEvent> get onStorage => (super.noSuchMethod(
Invocation.getter(#onStorage),
returnValue: _i3.Stream<_i2.StorageEvent>.empty(),
) as _i3.Stream<_i2.StorageEvent>);
@override
_i3.Stream<_i2.Event> get onSubmit => (super.noSuchMethod(
Invocation.getter(#onSubmit),
returnValue: _i3.Stream<_i2.Event>.empty(),
) as _i3.Stream<_i2.Event>);
@override
_i3.Stream<_i2.Event> get onSuspend => (super.noSuchMethod(
Invocation.getter(#onSuspend),
returnValue: _i3.Stream<_i2.Event>.empty(),
) as _i3.Stream<_i2.Event>);
@override
_i3.Stream<_i2.Event> get onTimeUpdate => (super.noSuchMethod(
Invocation.getter(#onTimeUpdate),
returnValue: _i3.Stream<_i2.Event>.empty(),
) as _i3.Stream<_i2.Event>);
@override
_i3.Stream<_i2.TouchEvent> get onTouchCancel => (super.noSuchMethod(
Invocation.getter(#onTouchCancel),
returnValue: _i3.Stream<_i2.TouchEvent>.empty(),
) as _i3.Stream<_i2.TouchEvent>);
@override
_i3.Stream<_i2.TouchEvent> get onTouchEnd => (super.noSuchMethod(
Invocation.getter(#onTouchEnd),
returnValue: _i3.Stream<_i2.TouchEvent>.empty(),
) as _i3.Stream<_i2.TouchEvent>);
@override
_i3.Stream<_i2.TouchEvent> get onTouchMove => (super.noSuchMethod(
Invocation.getter(#onTouchMove),
returnValue: _i3.Stream<_i2.TouchEvent>.empty(),
) as _i3.Stream<_i2.TouchEvent>);
@override
_i3.Stream<_i2.TouchEvent> get onTouchStart => (super.noSuchMethod(
Invocation.getter(#onTouchStart),
returnValue: _i3.Stream<_i2.TouchEvent>.empty(),
) as _i3.Stream<_i2.TouchEvent>);
@override
_i3.Stream<_i2.TransitionEvent> get onTransitionEnd => (super.noSuchMethod(
Invocation.getter(#onTransitionEnd),
returnValue: _i3.Stream<_i2.TransitionEvent>.empty(),
) as _i3.Stream<_i2.TransitionEvent>);
@override
_i3.Stream<_i2.Event> get onUnload => (super.noSuchMethod(
Invocation.getter(#onUnload),
returnValue: _i3.Stream<_i2.Event>.empty(),
) as _i3.Stream<_i2.Event>);
@override
_i3.Stream<_i2.Event> get onVolumeChange => (super.noSuchMethod(
Invocation.getter(#onVolumeChange),
returnValue: _i3.Stream<_i2.Event>.empty(),
) as _i3.Stream<_i2.Event>);
@override
_i3.Stream<_i2.Event> get onWaiting => (super.noSuchMethod(
Invocation.getter(#onWaiting),
returnValue: _i3.Stream<_i2.Event>.empty(),
) as _i3.Stream<_i2.Event>);
@override
_i3.Stream<_i2.AnimationEvent> get onAnimationEnd => (super.noSuchMethod(
Invocation.getter(#onAnimationEnd),
returnValue: _i3.Stream<_i2.AnimationEvent>.empty(),
) as _i3.Stream<_i2.AnimationEvent>);
@override
_i3.Stream<_i2.AnimationEvent> get onAnimationIteration =>
(super.noSuchMethod(
Invocation.getter(#onAnimationIteration),
returnValue: _i3.Stream<_i2.AnimationEvent>.empty(),
) as _i3.Stream<_i2.AnimationEvent>);
@override
_i3.Stream<_i2.AnimationEvent> get onAnimationStart => (super.noSuchMethod(
Invocation.getter(#onAnimationStart),
returnValue: _i3.Stream<_i2.AnimationEvent>.empty(),
) as _i3.Stream<_i2.AnimationEvent>);
@override
_i3.Stream<_i2.Event> get onBeforeUnload => (super.noSuchMethod(
Invocation.getter(#onBeforeUnload),
returnValue: _i3.Stream<_i2.Event>.empty(),
) as _i3.Stream<_i2.Event>);
@override
_i3.Stream<_i2.WheelEvent> get onWheel => (super.noSuchMethod(
Invocation.getter(#onWheel),
returnValue: _i3.Stream<_i2.WheelEvent>.empty(),
) as _i3.Stream<_i2.WheelEvent>);
@override
int get pageXOffset => (super.noSuchMethod(
Invocation.getter(#pageXOffset),
returnValue: 0,
) as int);
@override
int get pageYOffset => (super.noSuchMethod(
Invocation.getter(#pageYOffset),
returnValue: 0,
) as int);
@override
int get scrollX => (super.noSuchMethod(
Invocation.getter(#scrollX),
returnValue: 0,
) as int);
@override
int get scrollY => (super.noSuchMethod(
Invocation.getter(#scrollY),
returnValue: 0,
) as int);
@override
_i2.Events get on => (super.noSuchMethod(
Invocation.getter(#on),
returnValue: _FakeEvents_1(
this,
Invocation.getter(#on),
),
) as _i2.Events);
@override
_i2.WindowBase open(
String? url,
String? name, [
String? options,
]) =>
(super.noSuchMethod(
Invocation.method(
#open,
[
url,
name,
options,
],
),
returnValue: _FakeWindowBase_13(
this,
Invocation.method(
#open,
[
url,
name,
options,
],
),
),
) as _i2.WindowBase);
@override
int requestAnimationFrame(_i2.FrameRequestCallback? callback) =>
(super.noSuchMethod(
Invocation.method(
#requestAnimationFrame,
[callback],
),
returnValue: 0,
) as int);
@override
void cancelAnimationFrame(int? id) => super.noSuchMethod(
Invocation.method(
#cancelAnimationFrame,
[id],
),
returnValueForMissingStub: null,
);
@override
_i3.Future<_i2.FileSystem> requestFileSystem(
int? size, {
bool? persistent = false,
}) =>
(super.noSuchMethod(
Invocation.method(
#requestFileSystem,
[size],
{#persistent: persistent},
),
returnValue: _i3.Future<_i2.FileSystem>.value(_FakeFileSystem_14(
this,
Invocation.method(
#requestFileSystem,
[size],
{#persistent: persistent},
),
)),
) as _i3.Future<_i2.FileSystem>);
@override
void alert([String? message]) => super.noSuchMethod(
Invocation.method(
#alert,
[message],
),
returnValueForMissingStub: null,
);
@override
void cancelIdleCallback(int? handle) => super.noSuchMethod(
Invocation.method(
#cancelIdleCallback,
[handle],
),
returnValueForMissingStub: null,
);
@override
void close() => super.noSuchMethod(
Invocation.method(
#close,
[],
),
returnValueForMissingStub: null,
);
@override
bool confirm([String? message]) => (super.noSuchMethod(
Invocation.method(
#confirm,
[message],
),
returnValue: false,
) as bool);
@override
_i3.Future<dynamic> fetch(
dynamic input, [
Map<dynamic, dynamic>? init,
]) =>
(super.noSuchMethod(
Invocation.method(
#fetch,
[
input,
init,
],
),
returnValue: _i3.Future<dynamic>.value(),
) as _i3.Future<dynamic>);
@override
bool find(
String? string,
bool? caseSensitive,
bool? backwards,
bool? wrap,
bool? wholeWord,
bool? searchInFrames,
bool? showDialog,
) =>
(super.noSuchMethod(
Invocation.method(
#find,
[
string,
caseSensitive,
backwards,
wrap,
wholeWord,
searchInFrames,
showDialog,
],
),
returnValue: false,
) as bool);
@override
_i2.StylePropertyMapReadonly getComputedStyleMap(
_i2.Element? element,
String? pseudoElement,
) =>
(super.noSuchMethod(
Invocation.method(
#getComputedStyleMap,
[
element,
pseudoElement,
],
),
returnValue: _FakeStylePropertyMapReadonly_15(
this,
Invocation.method(
#getComputedStyleMap,
[
element,
pseudoElement,
],
),
),
) as _i2.StylePropertyMapReadonly);
@override
List<_i2.CssRule> getMatchedCssRules(
_i2.Element? element,
String? pseudoElement,
) =>
(super.noSuchMethod(
Invocation.method(
#getMatchedCssRules,
[
element,
pseudoElement,
],
),
returnValue: <_i2.CssRule>[],
) as List<_i2.CssRule>);
@override
_i2.MediaQueryList matchMedia(String? query) => (super.noSuchMethod(
Invocation.method(
#matchMedia,
[query],
),
returnValue: _FakeMediaQueryList_16(
this,
Invocation.method(
#matchMedia,
[query],
),
),
) as _i2.MediaQueryList);
@override
void moveBy(
int? x,
int? y,
) =>
super.noSuchMethod(
Invocation.method(
#moveBy,
[
x,
y,
],
),
returnValueForMissingStub: null,
);
@override
void postMessage(
dynamic message,
String? targetOrigin, [
List<Object>? transfer,
]) =>
super.noSuchMethod(
Invocation.method(
#postMessage,
[
message,
targetOrigin,
transfer,
],
),
returnValueForMissingStub: null,
);
@override
void print() => super.noSuchMethod(
Invocation.method(
#print,
[],
),
returnValueForMissingStub: null,
);
@override
int requestIdleCallback(
_i2.IdleRequestCallback? callback, [
Map<dynamic, dynamic>? options,
]) =>
(super.noSuchMethod(
Invocation.method(
#requestIdleCallback,
[
callback,
options,
],
),
returnValue: 0,
) as int);
@override
void resizeBy(
int? x,
int? y,
) =>
super.noSuchMethod(
Invocation.method(
#resizeBy,
[
x,
y,
],
),
returnValueForMissingStub: null,
);
@override
void resizeTo(
int? x,
int? y,
) =>
super.noSuchMethod(
Invocation.method(
#resizeTo,
[
x,
y,
],
),
returnValueForMissingStub: null,
);
@override
void scroll([
dynamic options_OR_x,
dynamic y,
Map<dynamic, dynamic>? scrollOptions,
]) =>
super.noSuchMethod(
Invocation.method(
#scroll,
[
options_OR_x,
y,
scrollOptions,
],
),
returnValueForMissingStub: null,
);
@override
void scrollBy([
dynamic options_OR_x,
dynamic y,
Map<dynamic, dynamic>? scrollOptions,
]) =>
super.noSuchMethod(
Invocation.method(
#scrollBy,
[
options_OR_x,
y,
scrollOptions,
],
),
returnValueForMissingStub: null,
);
@override
void scrollTo([
dynamic options_OR_x,
dynamic y,
Map<dynamic, dynamic>? scrollOptions,
]) =>
super.noSuchMethod(
Invocation.method(
#scrollTo,
[
options_OR_x,
y,
scrollOptions,
],
),
returnValueForMissingStub: null,
);
@override
void stop() => super.noSuchMethod(
Invocation.method(
#stop,
[],
),
returnValueForMissingStub: null,
);
@override
_i3.Future<_i2.Entry> resolveLocalFileSystemUrl(String? url) =>
(super.noSuchMethod(
Invocation.method(
#resolveLocalFileSystemUrl,
[url],
),
returnValue: _i3.Future<_i2.Entry>.value(_FakeEntry_17(
this,
Invocation.method(
#resolveLocalFileSystemUrl,
[url],
),
)),
) as _i3.Future<_i2.Entry>);
@override
String atob(String? atob) => (super.noSuchMethod(
Invocation.method(
#atob,
[atob],
),
returnValue: '',
) as String);
@override
String btoa(String? btoa) => (super.noSuchMethod(
Invocation.method(
#btoa,
[btoa],
),
returnValue: '',
) as String);
@override
void moveTo(_i4.Point<num>? p) => super.noSuchMethod(
Invocation.method(
#moveTo,
[p],
),
returnValueForMissingStub: null,
);
@override
void addEventListener(
String? type,
_i2.EventListener? listener, [
bool? useCapture,
]) =>
super.noSuchMethod(
Invocation.method(
#addEventListener,
[
type,
listener,
useCapture,
],
),
returnValueForMissingStub: null,
);
@override
void removeEventListener(
String? type,
_i2.EventListener? listener, [
bool? useCapture,
]) =>
super.noSuchMethod(
Invocation.method(
#removeEventListener,
[
type,
listener,
useCapture,
],
),
returnValueForMissingStub: null,
);
@override
bool dispatchEvent(_i2.Event? event) => (super.noSuchMethod(
Invocation.method(
#dispatchEvent,
[event],
),
returnValue: false,
) as bool);
}
## 4.2.1
* Resolves an error that occurred when calling the `shouldShowRequestPermissionRationale` on iOS.
## 4.2.0
* Adds a new permission `Permission.backgroundRefresh` to check the background refresh permission status on iOS & macOS platforms. This is a no-op on all other platforms.
## 4.1.0
* Adds the `Permission.assistant` which allows users to request permissions to access SiriKit on iOS and macOS platforms. This is a no-op on all other platforms.
## 4.0.2
* Improved the documentation around the `PermissionStatus`, `PermissionStatusGetters` and `FuturePermissionStatusGetters`.
## 4.0.1
* Updates Android documentation on how to use `permission.photo` on Android 12 (API 32) and below and Android 13 (API 33) and above.
## 4.0.0
* **BREAKING CHANGE**: Replaces `Permission.calendarReadOnly` with `Permission.calendarWriteOnly`.
## 3.12.0
* Adds `Permission.calendarReadOnly` and `Permission.calendarFullAccess`.
* Deprecates `Permission.calendar`. Developers should use `Permission.calendarReadOnly` and `Permission.calendarFullAccess` instead.
## 3.11.5
* Updates the mentions of Android versions throughout the plugin, now following a format of 'Android {name} (API {number})'. For example: 'Android 13 (API 33)'.
## 3.11.4
* Clarifies the documentation on requesting background location permission
through `Permission.locationAlways` on Android 10+ (API 29+).
## 3.11.3
* Updates the documentation for the `Permission.bluetooth` permission regarding the limitations of the permission on iOS.
## 3.11.2
* Changes `Permission.bluetooth` into an instance of `PermissionWithService` instead of `Permission` in order to determine iOS native's `CBManagerStatePoweredOn`.
## 3.11.1
* Updates the documentation for the `Permission.storage` permission regarding its use on Android.
## 3.11.0+1
* **HOTFIX**: Fixes misalignment in the `Permission` enum after adding the new BODY_SENSORS_BACKGROUND permission.
## 3.11.0
* Adds support for the new Android 13 permission: BODY_SENSORS_BACKGROUND.
## 3.10.0
* Adds support for the "Provisional" permission status introduced with iOS 12+.
## 3.9.0
* Adds support for the new Android 13 permissions: SCHEDULE_EXACT_ALARM, READ_MEDIA_IMAGES, READ_MEDIA_VIDEO and READ_MEDIA_AUDIO
## 3.8.0
* Adds support for the new Android 13 permission: NEARBY_WIFI_DEVICES.
## 3.7.1
* Updates the documentation on permissions in `permission_status.dart`
## 3.7.0
* Adds support for the new Android 12 Bluetooth permissions: BLUETOOTH_SCAN, BLUETOOTH_ADVERTISE, and BLUETOOTH_CONNECT.
## 3.6.2
* Updates the MethodChannelMock due to breaking changes in the platform channel test interface.
## 3.6.1
* Updates the `meta` dependency to version `^1.3.0`.
* Updates documentation for the `locationAlways` permission
## 3.6.0
* Adds support for iOS Critical Alerts and Android Access Notification Policy.
## 3.5.1
* Updates API documentation for the `PermissionStatus.permanentlyDenied` status.
## 3.5.0
* Adds support for app tracking transparency permission.
## 3.4.0
* Adds support request install packages permission.
## 3.3.0
* Adds support for system alert window permission.
## 3.2.0
* Adds support for managing external storage permission available on Android 10 and up.
## 3.1.3
* Implements the equality operator for the `Permission` class;
* Reverts the status of the services check for notification permission. Turns out the implementation does not fit with the ideas of the permission_handler plugin.
## 3.1.2
* Allows checking service status for notification permission.
## 3.1.1
* Fixes conversion issue where `PermissionStatus.denied` was not translated to the correct index.
* Adds unit tests to guard API against breaking changes.
## 3.1.0
* Adds support for Bluetooth permissions.
## 3.0.0+1
* **BREAKING**: Removes the PermissionStatus.undetermined. This is now replaced by PermissionStatus.denied.
## 3.0.0
* Migrates to null safety.
## 2.0.2
* Adds support for the limited photo permission available on iOS 14 and up.
## 2.0.1
* Updates to `platform_interface 1.0.2`
* Fixes bug that allows requesting if the device has phone capabilities.
## 2.0.0
* **BREAKING**: Creates a much more intuitive API using Dart's new extension methods ([#230](https://github.com/Baseflow/flutter-permission-handler/issues/230)). Big thank you to [@marcelgarus](https://github.com/marcelgarus) for the idea and for doing all the grunt work.
## 1.0.0
* Initial open-source release.
MIT License
Copyright (c) 2018 Baseflow
Permission is hereby granted, free of charge, to any person obtaining a copy
of this software and associated documentation files (the "Software"), to deal
in the Software without restriction, including without limitation the rights
to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
copies of the Software, and to permit persons to whom the Software is
furnished to do so, subject to the following conditions:
The above copyright notice and this permission notice shall be included in all
copies or substantial portions of the Software.
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
SOFTWARE.
# permission_handler_platform_interface
[![pub package](https://img.shields.io/pub/v/permission_handler_platform_interface.svg)](https://pub.dartlang.org/packages/permission_handler_platform_interface) ![Build status](https://github.com/Baseflow/flutter-permission-handler/workflows/permission_handler_platform_interface/badge.svg?branch=master) [![style: effective dart](https://img.shields.io/badge/style-effective_dart-40c4ff.svg)](https://github.com/tenhobi/effective_dart)[![codecov](https://codecov.io/gh/Baseflow/flutter-permission-handler/branch/master/graph/badge.svg)](https://codecov.io/gh/Baseflow/flutter-permission-handler)
A common platform interface for the [`permission_handler`][1] plugin.
This interface allows platform-specific implementations of the
`permission_handler` plugin, as well as the plugin itself, to ensure they are
supporting the same interface.
# Usage
To implement a new platform-specific implementation of `permission_handler`,
extend [`PermissionHandlerPlatform`][2] with an implementation that performs
the platform-specific behavior, and when you register your plugin, set the
default `PermissionHandlerPlatform` by calling
`PermissionHandlerPlatform.instance = MyPlatformPermissionHandler()`.
# Issues
Please file any issues, bugs, or feature requests as an issue on our [GitHub](https://github.com/Baseflow/flutter-permission-handler/issues) page.
# Want to contribute
If you would like to contribute to the plugin (e.g. by improving the documentation, solving a bug, or adding a cool new feature), please carefully review our [contribution guide](../CONTRIBUTING.md) and send us your [pull request](https://github.com/Baseflow/flutter-permission-handler/pulls).
## Note on breaking changes
Strongly prefer non-breaking changes (such as adding a method to the interface)
over breaking changes for this package.
See https://flutter.dev/go/platform-interface-breaking-changes for a discussion
on why a less clean interface is preferable to a breaking change.
# Author
This Permission handler plugin for Flutter is developed by [Baseflow](https://baseflow.com). You can contact us at <hello@baseflow.com>
[1]: ../permission_handler
[2]: lib/permission_handler_platform_interface.dart
include: package:flutter_lints/flutter.yaml
analyzer:
exclude:
# Ignore generated files
- "**/*.g.dart"
- "lib/src/generated/*.dart"
linter:
rules:
- public_member_api_docs
library permission_handler_platform_interface;
import 'dart:async';
import 'package:meta/meta.dart';
import 'package:plugin_platform_interface/plugin_platform_interface.dart';
import 'src/method_channel/method_channel_permission_handler.dart';
part 'src/permission_handler_platform_interface.dart';
part 'src/permission_status.dart';
part 'src/permissions.dart';
part 'src/service_status.dart';
import 'dart:async';
import 'package:flutter/foundation.dart';
import 'package:flutter/services.dart';
import '../../permission_handler_platform_interface.dart';
import 'utils/codec.dart';
const MethodChannel _methodChannel =
MethodChannel('flutter.baseflow.com/permissions/methods');
/// An implementation of [PermissionHandlerPlatform] that uses [MethodChannel]s.
class MethodChannelPermissionHandler extends PermissionHandlerPlatform {
/// Checks the current status of the given [Permission].
@override
Future<PermissionStatus> checkPermissionStatus(Permission permission) async {
final status = await _methodChannel.invokeMethod(
'checkPermissionStatus', permission.value);
return decodePermissionStatus(status);
}
/// Checks the current status of the service associated with the given
/// [Permission].
///
/// Notes about specific permissions:
/// - **[Permission.phone]**
/// - Android:
/// - The method will return [ServiceStatus.notApplicable] when:
/// - the device lacks the TELEPHONY feature
/// - TelephonyManager.getPhoneType() returns PHONE_TYPE_NONE
/// - when no Intents can be resolved to handle the `tel:` scheme
/// - The method will return [ServiceStatus.disabled] when:
/// - the SIM card is missing
/// - iOS:
/// - The method will return [ServiceStatus.notApplicable] when:
/// - the native code can not find a handler for the `tel:` scheme
/// - The method will return [ServiceStatus.disabled] when:
/// - the mobile network code (MNC) is either 0 or 65535. See
/// https://stackoverflow.com/a/11595365 for details
/// - **PLEASE NOTE that this is still not a perfect indication** of the
/// device's capability to place & connect phone calls as it also depends
/// on the network condition.
/// - **[Permission.bluetooth]**
/// - iOS:
/// - The method will **always** return [ServiceStatus.disabled] when the
/// Bluetooth permission was denied by the user. It is not possible
/// obtain the actual Bluetooth service status without having the
/// Bluetooth permission granted.
/// - The method will prompt the user for Bluetooth permission if the
/// permission was not requested before.
@override
Future<ServiceStatus> checkServiceStatus(Permission permission) async {
final status = await _methodChannel.invokeMethod(
'checkServiceStatus', permission.value);
return decodeServiceStatus(status);
}
/// Opens the app settings page.
///
/// Returns [true] if the app settings page could be opened, otherwise
/// [false].
@override
Future<bool> openAppSettings() async {
final wasOpened = await _methodChannel.invokeMethod('openAppSettings');
return wasOpened ?? false;
}
/// Requests the user for access to the supplied list of [Permission]s, if
/// they have not already been granted before.
///
/// Returns a [Map] containing the status per requested [Permission].
@override
Future<Map<Permission, PermissionStatus>> requestPermissions(
List<Permission> permissions) async {
final data = encodePermissions(permissions);
final status =
await _methodChannel.invokeMethod('requestPermissions', data);
return decodePermissionRequestResult(Map<int, int>.from(status));
}
/// Checks if you should show a rationale for requesting permission.
///
/// This method is only implemented on Android, calling this on iOS always
/// returns [false].
@override
Future<bool> shouldShowRequestPermissionRationale(
Permission permission) async {
if (defaultTargetPlatform != TargetPlatform.android) {
return false;
}
final shouldShowRationale = await _methodChannel.invokeMethod(
'shouldShowRequestPermissionRationale', permission.value);
return shouldShowRationale ?? false;
}
}
import '../../../permission_handler_platform_interface.dart';
/// Converts the given [value] into a [PermissionStatus] instance.
PermissionStatus decodePermissionStatus(int value) {
return PermissionStatusValue.statusByValue(value);
}
/// Converts the given [value] into a [ServiceStatus] instance.
ServiceStatus decodeServiceStatus(int value) {
return ServiceStatusValue.statusByValue(value);
}
/// Converts the given [Map] of [int]s into a [Map] with [Permission]s as
/// keys and their respective [PermissionStatus] as value.
Map<Permission, PermissionStatus> decodePermissionRequestResult(
Map<int, int> value) {
return value.map((key, value) => MapEntry<Permission, PermissionStatus>(
Permission.byValue(key), PermissionStatusValue.statusByValue(value)));
}
/// Converts the given [List] of [Permission]s into a [List] of [int]s which
/// can be sent on the Flutter method channel.
List<int> encodePermissions(List<Permission> permissions) {
return permissions.map((it) => it.value).toList();
}
part of permission_handler_platform_interface;
/// The interface that implementations of `permission_handler` must implement.
///
/// Platform implementations should extend this class rather than implement it
/// as `permission_handler` does not consider newly added methods to be
/// breaking changes. Extending this class (using `extends`) ensures that the
/// subclass will get the default implementation, while platform
/// implementations that `implements` this interface will be broken by newly
/// added [PermissionHandlerPlatform] methods.
abstract class PermissionHandlerPlatform extends PlatformInterface {
/// Constructs a PermissionHandlerPlatform.
PermissionHandlerPlatform() : super(token: _token);
static final Object _token = Object();
static PermissionHandlerPlatform _instance = MethodChannelPermissionHandler();
/// The default instance of [PermissionHandlerPlatform] to use.
///
/// Defaults to [MethodChannelPermissionHandler].
static PermissionHandlerPlatform get instance => _instance;
/// Platform-specific plugins should set this with their own
/// platform-specific class that extends
/// [PermissionHandlerPlatform] when they register themselves.
static set instance(PermissionHandlerPlatform instance) {
PlatformInterface.verifyToken(instance, _token);
_instance = instance;
}
/// Checks the current status of the given [Permission].
Future<PermissionStatus> checkPermissionStatus(Permission permission) {
throw UnimplementedError(
'checkPermissionStatus() has not been implemented.');
}
/// Checks the current status of the service associated with the given
/// [Permission].
///
/// Notes about specific permissions:
/// - **[Permission.phone]**
/// - Android:
/// - The method will return [ServiceStatus.notApplicable] when:
/// - the device lacks the TELEPHONY feature
/// - TelephonyManager.getPhoneType() returns PHONE_TYPE_NONE
/// - when no Intents can be resolved to handle the `tel:` scheme
/// - The method will return [ServiceStatus.disabled] when:
/// - the SIM card is missing
/// - iOS:
/// - The method will return [ServiceStatus.notApplicable] when:
/// - the native code can not find a handler for the `tel:` scheme
/// - The method will return [ServiceStatus.disabled] when:
/// - the mobile network code (MNC) is either 0 or 65535. See
/// https://stackoverflow.com/a/11595365 for details
/// - **PLEASE NOTE that this is still not a perfect indication** of the
/// device's capability to place & connect phone calls as it also depends
/// on the network condition.
Future<ServiceStatus> checkServiceStatus(Permission permission) {
throw UnimplementedError('checkServiceStatus() has not been implemented.');
}
/// Opens the app settings page.
///
/// Returns [true] if the app settings page could be opened, otherwise
/// [false].
Future<bool> openAppSettings() {
throw UnimplementedError('openAppSettings() has not been implemented.');
}
/// Requests the user for access to the supplied list of [Permission]s, if
/// they have not already been granted before.
///
/// Returns a [Map] containing the status per requested [Permission].
Future<Map<Permission, PermissionStatus>> requestPermissions(
List<Permission> permissions) {
throw UnimplementedError('requestPermissions() has not been implemented.');
}
/// Checks if you should show a rationale for requesting permission.
///
/// This method is only implemented on Android, calling this on iOS always
/// returns [false].
Future<bool> shouldShowRequestPermissionRationale(Permission permission) {
throw UnimplementedError(
'shouldShowRequestPermissionRationale() has not been implemented.');
}
}
part of permission_handler_platform_interface;
/// Defines the state of a [Permission].
enum PermissionStatus {
/// The user denied access to the requested feature, permission needs to be
/// asked first.
denied,
/// The user granted access to the requested feature.
granted,
/// The OS denied access to the requested feature. The user cannot change
/// this app's status, possibly due to active restrictions such as parental
/// controls being in place.
///
/// *Only supported on iOS.*
restricted,
/// The user has authorized this application for limited access. So far this
/// is only relevant for the Photo Library picker.
///
/// *Only supported on iOS (iOS14+).*
limited,
/// Permission to the requested feature is permanently denied, the permission
/// dialog will not be shown when requesting this permission. The user may
/// still change the permission status in the settings.
///
/// *On Android:*
/// Android 11+ (API 30+): whether the user denied the permission for a second
/// time.
/// Below Android 11 (API 30): whether the user denied access to the requested
/// feature and selected to never again show a request.
///
/// *On iOS:*
/// If the user has denied access to the requested feature.
permanentlyDenied,
/// The application is provisionally authorized to post non-interruptive user
/// notifications.
///
/// *Only supported on iOS (iOS12+).*
provisional,
}
/// Conversion extension methods for the [PermissionStatus] type.
extension PermissionStatusValue on PermissionStatus {
/// Converts the [PermissionStatus] value into an integer.
int get value {
switch (this) {
case PermissionStatus.denied:
return 0;
case PermissionStatus.granted:
return 1;
case PermissionStatus.restricted:
return 2;
case PermissionStatus.limited:
return 3;
case PermissionStatus.permanentlyDenied:
return 4;
case PermissionStatus.provisional:
return 5;
default:
throw UnimplementedError();
}
}
/// Converts the supplied integer value into a [PermissionStatus] enum.
static PermissionStatus statusByValue(int value) {
return [
PermissionStatus.denied,
PermissionStatus.granted,
PermissionStatus.restricted,
PermissionStatus.limited,
PermissionStatus.permanentlyDenied,
PermissionStatus.provisional,
][value];
}
}
/// Utility getter extensions for the [PermissionStatus] type.
extension PermissionStatusGetters on PermissionStatus {
/// If the user denied access to the requested feature.
bool get isDenied => this == PermissionStatus.denied;
/// If the user granted access to the requested feature.
bool get isGranted => this == PermissionStatus.granted;
/// If the OS denied access to the requested feature. The user cannot change
/// this app's status, possibly due to active restrictions such as parental
/// controls being in place.
///
/// *Only supported on iOS.*
bool get isRestricted => this == PermissionStatus.restricted;
/// If the permission to the requested feature is permanently denied, the
/// permission dialog will not be shown when requesting this permission. The
/// user may still change the permission status in the settings.
///
/// *On Android:*
/// Android 11+ (API 30+): whether the user denied the permission for a second
/// time.
/// Below Android 11 (API 30): whether the user denied access to the requested
/// feature and selected to never again show a request.
/// The user may still change the permission status in the settings.
///
/// *On iOS:*
/// If the user has denied access to the requested feature.
bool get isPermanentlyDenied => this == PermissionStatus.permanentlyDenied;
/// If the user has authorized this application for limited access. So far
/// this is only relevant for the Photo Library picker.
///
/// *Only supported on iOS (iOS14+).*
bool get isLimited => this == PermissionStatus.limited;
/// If the application is provisionally authorized to post non-interruptive
/// user notifications.
///
/// *Only supported on iOS (iOS12+).*
bool get isProvisional => this == PermissionStatus.provisional;
}
/// Utility getter extensions for the `Future<PermissionStatus>` type.
extension FuturePermissionStatusGetters on Future<PermissionStatus> {
/// If the user granted access to the requested feature.
Future<bool> get isGranted async => (await this).isGranted;
/// If the user denied access to the requested feature.
Future<bool> get isDenied async => (await this).isDenied;
/// If the OS denied access to the requested feature. The user cannot change
/// this app's status, possibly due to active restrictions such as parental
/// controls being in place.
///
/// *Only supported on iOS.*
Future<bool> get isRestricted async => (await this).isRestricted;
/// If the permission to the requested feature is permanently denied, the
/// permission dialog will not be shown when requesting this permission. The
/// user may still change the permission status in the settings.
///
/// *On Android:*
/// Android 11+ (API 30+): whether the user denied the permission for a second
/// time.
/// Below Android 11 (API 30): whether the user denied access to the requested
/// feature and selected to never again show a request.
///
/// *On iOS:*
/// If the user has denied access to the requested feature.
Future<bool> get isPermanentlyDenied async =>
(await this).isPermanentlyDenied;
/// If the user has authorized this application for limited access. So far
/// this is only relevant for the Photo Library picker.
///
/// *Only supported on iOS (iOS14+).*
Future<bool> get isLimited async => (await this).isLimited;
/// If the application is provisionally authorized to post non-interruptive
/// user notifications.
///
/// *Only supported on iOS (iOS12+).*
Future<bool> get isProvisional async => (await this).isProvisional;
}
part of permission_handler_platform_interface;
/// A special kind of permission, used to access a service.
///
/// Additionally to the actions that normal [Permission]s have, you can also
/// query the status of the related service.
class PermissionWithService extends Permission {
const PermissionWithService._(int value) : super._(value);
/// Creates a [PermissionWithService] instance.
///
/// This constructor is marked public for testing purposes only.
@visibleForTesting
const PermissionWithService.private(int value) : super._(value);
}
/// Defines the permissions which can be checked and requested.
@immutable
class Permission {
const Permission._(this.value);
/// Creates a [Permission] using the supplied integer value.
factory Permission.byValue(int value) => values[value];
/// Integer representation of the [Permission].
final int value;
/// Permission for accessing the device's calendar.
///
/// Android: Calendar
/// iOS: Calendar (Events)
@Deprecated('Use [calendarWriteOnly] and [calendarFullAccess].')
static const calendar = Permission._(0);
/// Permission for accessing the device's camera.
///
/// Android: Camera
/// iOS: Photos (Camera Roll and Camera)
static const camera = Permission._(1);
/// Permission for accessing the device's contacts.
///
/// Android: Contacts
/// iOS: AddressBook
static const contacts = Permission._(2);
/// Permission for accessing the device's location.
///
/// Android: Fine and Coarse Location
/// iOS: CoreLocation (Always and WhenInUse)
static const location = PermissionWithService._(3);
/// Permission for accessing the device's location when the app is running in
/// the background.
///
/// Depending on the platform and version, the requirements are slightly
/// different:
///
/// **Android:**
/// - When running on Android 10 (API 29) and above: Background Location
/// Permission.
/// <p>**Please note**: To request this permission, the user needs to grant
/// foreground location permissions first. You can do this by using either
/// [Permission.location] or [Permission.locationWhenInUse]. Then, requesting
/// [Permission.locationAlways] will show an additional dialog or open the
/// location permission app settings, allowing the user to change the location
/// access to 'allow all the time'.
/// - When running below Android 10 (API 29): Fine and Coarse Location
///
/// **iOS:** CoreLocation - Always
static const locationAlways = PermissionWithService._(4);
/// Permission for accessing the device's location when the app is running in
/// the foreground.
///
/// Android: Fine and Coarse Location
/// iOS: CoreLocation - WhenInUse
static const locationWhenInUse = PermissionWithService._(5);
/// Permission for accessing the device's media library (iOS 9.3+ only).
static const mediaLibrary = Permission._(6);
/// Permission for accessing the device's microphone.
static const microphone = Permission._(7);
/// Permission for accessing the device's phone state (Android only).
static const phone = PermissionWithService._(8);
/// Permission for accessing the device's photos.
///
/// Photos can be read and added. If you only want to read them, you can
/// use the [photos] permission instead (iOS only).
///
/// Depending on the platform and version, the requirements are slightly
/// different:
///
/// **iOS:**
/// - When running Photos (iOS 14+ read & write access level)
///
/// **Android:**
/// - Devices running Android 12 (API level 32) or lower: use [Permissions.storage].
/// - Devices running Android 13 (API level 33) and above: Should use [Permissions.photos].
///
/// EXAMPLE: in Manifest:
/// <uses-permission android:name="android.permission.READ_EXTERNAL_STORAGE" android:maxSdkVersion="32"/>
/// <uses-permission android:name="android.permission.READ_MEDIA_IMAGES"/>
///
/// In Flutter to check the status:
///
/// if (Platform.isAndroid) {
/// final androidInfo = await DeviceInfoPlugin().androidInfo;
/// if (androidInfo.version.sdkInt <= 32) {
/// use [Permissions.storage.status]
/// } else {
/// use [Permissions.photos.status]
/// }
/// }
static const photos = Permission._(9);
/// Permission for adding photos to the device's photo library (iOS only).
///
/// Photos can only be added. If you want to read them as well, use the
/// [photos] permission instead.
///
/// iOS: Photos (14+ read & write access level)
static const photosAddOnly = Permission._(10);
/// Permission for accessing the device's reminders (iOS only).
static const reminders = Permission._(11);
/// Permission for accessing the device's sensors.
///
/// Android: Body Sensors
/// iOS: CoreMotion
static const sensors = Permission._(12);
/// Permission for sending and reading SMS messages (Android only).
static const sms = Permission._(13);
/// Permission for accessing speech recognition.
///
/// **Android:**
/// - Requests access to microphone (identical to requesting
/// [Permission.microphone]).
///
/// **iOS:**
/// - Requests speech access (different from requesting
/// [Permission.microphone]).
static const speech = Permission._(14);
/// Permission for accessing external storage.
///
/// Depending on the platform and version, the requirements are slightly
/// different:
///
/// **Android:**
/// - On Android 13 (API 33) and above, this permission is deprecated and
/// always returns `PermissionStatus.denied`. Instead use `Permission.photos`,
/// `Permission.video`, `Permission.audio` or
/// `Permission.manageExternalStorage`. For more information see our
/// [FAQ](https://pub.dev/packages/permission_handler#faq).
/// - Below Android 13 (API 33), the `READ_EXTERNAL_STORAGE` and
/// `WRITE_EXTERNAL_STORAGE` permissions are requested (depending on the
/// definitions in the AndroidManifest.xml) file.
///
/// **iOS:**
/// - Access to folders like `Documents` or `Downloads`. Implicitly granted.
static const storage = Permission._(15);
/// Permission for accessing ignore battery optimizations (Android only).
static const ignoreBatteryOptimizations = Permission._(16);
/// Permission for pushing notifications.
static const notification = Permission._(17);
/// Permission for accessing the device's media library.
///
/// Android 10+ (API 29+)
///
/// Allows an application to access any geographic locations persisted in the
/// user's shared collection.
static const accessMediaLocation = Permission._(18);
/// Permission for accessing the activity recognition.
///
/// Android 10+ (API 29+)
static const activityRecognition = Permission._(19);
/// The unknown only used for return type, never requested.
static const unknown = Permission._(20);
/// Permission for accessing the device's bluetooth adapter state.
///
/// Depending on the platform and version, the requirements are slightly
/// different:
///
/// **Android:**
/// - Always allowed.
///
/// **iOS:**
/// - iOS 13 and above: The authorization state of Core Bluetooth manager.
/// - iOS below 13: always allowed.
///
/// Limitations:
/// - iOS 13.0 only: [bluetooth.status] is always [PermissionStatus.denied],
/// regardless of the actual status. For the actual permission state, use
/// [bluetooth.request]. Note that this will show a permission dialog if the
/// permission was not yet requested.
/// - All iOS versions: [bluetooth.serviceStatus] will **always** return
/// [ServiceStatus.disabled] when the Bluetooth permission was denied by the
/// user. It is impossible to obtain the actual Bluetooth service status
/// without having the Bluetooth permission granted. The method will prompt
/// the user for Bluetooth permission if the permission was not yet requested.
static const bluetooth = PermissionWithService._(21);
/// Permission for accessing the device's external storage.
///
/// Android 11+ (API 30+)
///
/// Allows an application a broad access to external storage in scoped
/// storage.
///
/// You should request the Manage External Storage permission only when
/// your app cannot effectively make use of the more privacy-friendly APIs.
/// For more information:
/// https://developer.android.com/training/data-storage/manage-all-files
///
/// When the privacy-friendly APIs (i.e. [Storage Access Framework](https://developer.android.com/guide/topics/providers/document-provider)
/// or the [MediaStore](https://developer.android.com/training/data-storage/shared/media) APIs)
/// is all your app needs, the [PermissionGroup.storage] are the only
/// permissions you need to request.
///
/// If the usage of the Manage External Storage permission is needed,
/// you have to fill out the Permission Declaration Form upon submitting
/// your app to the Google Play Store. More details can be found here:
/// https://support.google.com/googleplay/android-developer/answer/9214102#zippy=
static const manageExternalStorage = Permission._(22);
/// Permission for creating system alert window (Android only).
///
/// Allows an app to create windows shown on top of all other apps.
static const systemAlertWindow = Permission._(23);
/// Permission for requesting installing packages.
///
/// Android Marshmallow+ (API 23+)
static const requestInstallPackages = Permission._(24);
/// Permission for accessing the device's tracking state (iOS only).
///
/// Allows user to accept that your app collects data about end users and
/// shares it with other companies for purposes of tracking across apps and
/// websites.
static const appTrackingTransparency = Permission._(25);
/// Permission for sending critical alerts (iOS only).
///
/// Allow for sending notifications that override the ringer.
static const criticalAlerts = Permission._(26);
/// Permission for accessing the device's notification policy.
///
/// Android Marshmallow+ (API 23+)
///
/// Allows the user to access the notification policy of the phone.
/// EX: Allows app to turn on and off do-not-disturb.
static const accessNotificationPolicy = Permission._(27);
/// Permission for scanning for Bluetooth devices.
///
/// Android 12+ (API 31+)
static const bluetoothScan = Permission._(28);
/// Permission for advertising Bluetooth devices
///
/// Android 12+ (API 31+)
///
/// Allows the user to make this device discoverable to other Bluetooth
/// devices.
static const bluetoothAdvertise = Permission._(29);
/// Permission for connecting to Bluetooth devices.
///
/// Android 12+ (API 31+)
///
/// Allows the user to connect with already paired Bluetooth devices.
static const bluetoothConnect = Permission._(30);
/// Permission for connecting to nearby devices via Wi-Fi.
///
/// Android 13+ (API 33+)
static const nearbyWifiDevices = Permission._(31);
/// Permission for accessing the device's video files from external storage.
///
/// Android 13+ (API 33+)
static const videos = Permission._(32);
/// Permission for accessing the device's audio files from external storage.
///
/// Android 13+ (API 33+)
static const audio = Permission._(33);
/// Permission for scheduling exact alarms.
///
/// Android 12+ (API 31+)
static const scheduleExactAlarm = Permission._(34);
/// Permission for accessing the device's sensors in background.
///
/// Android 13+ (API 33+)
static const sensorsAlways = Permission._(35);
/// Permission for writing to the device's calendar.
///
/// On iOS 16 and lower, this permission is identical to [Permission.calendarFullAccess].
static const calendarWriteOnly = Permission._(36);
/// Permission for reading from and writing to the device's calendar.
static const calendarFullAccess = Permission._(37);
/// Android: Nothing
/// iOS: SiriKit
static const assistant = Permission._(38);
/// Permission for reading the current background refresh status. (iOS only)
static const backgroundRefresh = Permission._(39);
/// Returns a list of all possible [PermissionGroup] values.
static const List<Permission> values = <Permission>[
// ignore: deprecated_member_use_from_same_package
calendar,
camera,
contacts,
location,
locationAlways,
locationWhenInUse,
mediaLibrary,
microphone,
phone,
photos,
photosAddOnly,
reminders,
sensors,
sms,
speech,
storage,
ignoreBatteryOptimizations,
notification,
accessMediaLocation,
activityRecognition,
unknown,
bluetooth,
manageExternalStorage,
systemAlertWindow,
requestInstallPackages,
appTrackingTransparency,
criticalAlerts,
accessNotificationPolicy,
bluetoothScan,
bluetoothAdvertise,
bluetoothConnect,
nearbyWifiDevices,
videos,
audio,
scheduleExactAlarm,
sensorsAlways,
calendarWriteOnly,
calendarFullAccess,
assistant,
backgroundRefresh,
];
static const List<String> _names = <String>[
'calendar',
'camera',
'contacts',
'location',
'locationAlways',
'locationWhenInUse',
'mediaLibrary',
'microphone',
'phone',
'photos',
'photosAddOnly',
'reminders',
'sensors',
'sms',
'speech',
'storage',
'ignoreBatteryOptimizations',
'notification',
'access_media_location',
'activity_recognition',
'unknown',
'bluetooth',
'manageExternalStorage',
'systemAlertWindow',
'requestInstallPackages',
'appTrackingTransparency',
'criticalAlerts',
'accessNotificationPolicy',
'bluetoothScan',
'bluetoothAdvertise',
'bluetoothConnect',
'nearbyWifiDevices',
'videos',
'audio',
'scheduleExactAlarm',
'sensorsAlways',
'calendarWriteOnly',
'calendarFullAccess',
'assistant',
'backgroundRefresh'
];
@override
String toString() => 'Permission.${_names[value]}';
@override
bool operator ==(Object other) {
if (identical(this, other)) {
return true;
}
if (other.runtimeType != runtimeType) {
return false;
}
return other is Permission && other.value == value;
}
@override
int get hashCode => value.hashCode;
}
part of permission_handler_platform_interface;
/// Defines the different states a service can be in.
enum ServiceStatus {
/// The service for the permission is disabled.
disabled,
/// The service for the permission is enabled.
enabled,
/// The permission does not have an associated service on the current
/// platform.
notApplicable,
}
/// Conversion extension methods for the [ServiceStatus] type.
extension ServiceStatusValue on ServiceStatus {
/// Converts the [ServiceStatus] value into an integer.
int get value {
switch (this) {
case ServiceStatus.disabled:
return 0;
case ServiceStatus.enabled:
return 1;
case ServiceStatus.notApplicable:
return 2;
default:
throw UnimplementedError();
}
}
/// Converts the supplied integer value into a [ServiceStatus] enum.
static ServiceStatus statusByValue(int value) {
return [
ServiceStatus.disabled,
ServiceStatus.enabled,
ServiceStatus.notApplicable,
][value];
}
}
/// Utility getter extensions for the [ServiceStatus] type.
extension ServiceStatusGetters on ServiceStatus {
/// If the service for the permission is disabled.
bool get isDisabled => this == ServiceStatus.disabled;
/// If the service for the permission is enabled.
bool get isEnabled => this == ServiceStatus.enabled;
/// If the permission does not have an associated service on the current
/// platform.
bool get isNotApplicable => this == ServiceStatus.notApplicable;
}
/// Utility getter extensions for the `Future<ServiceStatus>` type.
extension FutureServiceStatusGetters on Future<ServiceStatus> {
/// If the service for the permission is disabled.
Future<bool> get isDisabled async => (await this).isDisabled;
/// If the service for the permission is enabled.
Future<bool> get isEnabled async => (await this).isEnabled;
/// If the permission does not have an associated service on the current
/// platform.
Future<bool> get isNotApplicable async => (await this).isNotApplicable;
}
name: permission_handler_platform_interface
description: A common platform interface for the permission_handler plugin.
homepage: https://github.com/baseflow/flutter-permission-handler/tree/master/permission_handler_platform_interface
# NOTE: We strongly prefer non-breaking changes, even at the expense of a
# less-clean API. See https://flutter.dev/go/platform-interface-breaking-changes
version: 4.2.1
dependencies:
flutter:
sdk: flutter
meta: ^1.3.0
plugin_platform_interface: ^2.0.0
dev_dependencies:
flutter_test:
sdk: flutter
mockito: ^5.0.0
flutter_lints: ^1.0.4
environment:
sdk: ">=2.14.0 <4.0.0"
flutter: ">=2.5.0"
import 'package:flutter/services.dart';
import 'package:flutter_test/flutter_test.dart';
class MethodChannelMock {
final MethodChannel methodChannel;
final String method;
final dynamic result;
final Duration delay;
MethodChannelMock({
required String channelName,
required this.method,
this.result,
this.delay = Duration.zero,
}) : methodChannel = MethodChannel(channelName) {
TestDefaultBinaryMessengerBinding.instance.defaultBinaryMessenger
.setMockMethodCallHandler(methodChannel, _handler);
}
Future _handler(MethodCall methodCall) async {
if (methodCall.method != method) {
throw MissingPluginException('No implementation found for method '
'$method on channel ${methodChannel.name}');
}
return Future.delayed(delay, () {
if (result is Exception) {
throw result;
}
return Future.value(result);
});
}
}
import 'package:flutter_test/flutter_test.dart';
import 'package:permission_handler_platform_interface/permission_handler_platform_interface.dart';
import 'package:permission_handler_platform_interface/src/method_channel/method_channel_permission_handler.dart';
import 'method_channel_mock.dart';
List<Permission> get mockPermissions => List.of(<Permission>{
Permission.contacts,
Permission.camera,
Permission.calendarWriteOnly,
});
Map<Permission, PermissionStatus> get mockPermissionMap => {};
void main() {
TestWidgetsFlutterBinding.ensureInitialized();
group('checkPermissionStatus: When checking for permission', () {
test('Should receive granted if user wants access to the requested feature',
() async {
MethodChannelMock(
channelName: 'flutter.baseflow.com/permissions/methods',
method: 'checkPermissionStatus',
result: PermissionStatus.denied.value,
);
final permissionStatus = await MethodChannelPermissionHandler()
.checkPermissionStatus(Permission.contacts);
expect(permissionStatus, PermissionStatus.denied);
});
test('Should receive denied if user denied access to the requested feature',
() async {
MethodChannelMock(
channelName: 'flutter.baseflow.com/permissions/methods',
method: 'checkPermissionStatus',
result: PermissionStatus.denied.value,
);
final permissionStatus = await MethodChannelPermissionHandler()
.checkPermissionStatus(Permission.contacts);
expect(permissionStatus, PermissionStatus.denied);
});
test(
// ignore: lines_longer_than_80_chars
'Should receive restricted if OS denied rights for to the requested feature',
() async {
MethodChannelMock(
channelName: 'flutter.baseflow.com/permissions/methods',
method: 'checkPermissionStatus',
result: PermissionStatus.restricted.value,
);
final permissionStatus = await MethodChannelPermissionHandler()
.checkPermissionStatus(Permission.contacts);
expect(permissionStatus, PermissionStatus.restricted);
});
test(
// ignore: lines_longer_than_80_chars
'Should receive limited if user has authorized this application for limited access',
() async {
MethodChannelMock(
channelName: 'flutter.baseflow.com/permissions/methods',
method: 'checkPermissionStatus',
result: PermissionStatus.limited.value,
);
final permissionStatus = await MethodChannelPermissionHandler()
.checkPermissionStatus(Permission.contacts);
expect(permissionStatus, PermissionStatus.limited);
});
test(
// ignore: lines_longer_than_80_chars
'Should receive permanentlyDenied if user denied access and selected to never show a request for this permission again',
() async {
MethodChannelMock(
channelName: 'flutter.baseflow.com/permissions/methods',
method: 'checkPermissionStatus',
result: PermissionStatus.permanentlyDenied.value,
);
final permissionStatus = await MethodChannelPermissionHandler()
.checkPermissionStatus(Permission.contacts);
expect(permissionStatus, PermissionStatus.permanentlyDenied);
});
});
group('checkServiceStatus: When checking for service', () {
// ignore: lines_longer_than_80_chars
test(
'Should receive disabled if the service for the permission is disabled',
() async {
MethodChannelMock(
channelName: 'flutter.baseflow.com/permissions/methods',
method: 'checkServiceStatus',
result: ServiceStatus.disabled.value,
);
final serviceStatus = await MethodChannelPermissionHandler()
.checkServiceStatus(Permission.contacts);
expect(serviceStatus, ServiceStatus.disabled);
});
test('Should receive enabled if the service for the permission is enabled',
() async {
MethodChannelMock(
channelName: 'flutter.baseflow.com/permissions/methods',
method: 'checkServiceStatus',
result: ServiceStatus.enabled.value,
);
final serviceStatus = await MethodChannelPermissionHandler()
.checkServiceStatus(Permission.contacts);
expect(serviceStatus, ServiceStatus.enabled);
});
test(
// ignore: lines_longer_than_80_chars
'Should receive notApplicable if the permission does not have an associated service on the current platform',
() async {
MethodChannelMock(
channelName: 'flutter.baseflow.com/permissions/methods',
method: 'checkServiceStatus',
result: ServiceStatus.notApplicable.value,
);
final serviceStatus = await MethodChannelPermissionHandler()
.checkServiceStatus(Permission.contacts);
expect(serviceStatus, ServiceStatus.notApplicable);
});
});
group('openAppSettings: When opening the App settings', () {
test('Should receive true if the page can be opened', () async {
MethodChannelMock(
channelName: 'flutter.baseflow.com/permissions/methods',
method: 'openAppSettings',
result: true,
);
final hasOpenedAppSettings =
await MethodChannelPermissionHandler().openAppSettings();
expect(hasOpenedAppSettings, true);
});
test('Should receive false if an error occurred', () async {
MethodChannelMock(
channelName: 'flutter.baseflow.com/permissions/methods',
method: 'openAppSettings',
result: false,
);
final hasOpenedAppSettings =
await MethodChannelPermissionHandler().openAppSettings();
expect(hasOpenedAppSettings, false);
});
});
group('requestPermissions: When requesting for permission', () {
// ignore: lines_longer_than_80_chars
test('returns a Map with all the PermissionStatus of the given permissions',
() async {
MethodChannelMock(
channelName: 'flutter.baseflow.com/permissions/methods',
method: 'requestPermissions',
result: mockPermissionMap,
);
final result = await MethodChannelPermissionHandler()
.requestPermissions(mockPermissions);
expect(result, isA<Map<Permission, PermissionStatus>>());
});
});
group('shouldShowRequestPermissionRationale:', () {
test(
// ignore: lines_longer_than_80_chars
'should return true when you should show a rationale for requesting permission.',
() async {
MethodChannelMock(
channelName: 'flutter.baseflow.com/permissions/methods',
method: 'shouldShowRequestPermissionRationale',
result: true,
);
final shouldShowRationale = await MethodChannelPermissionHandler()
.shouldShowRequestPermissionRationale(mockPermissions.first);
expect(shouldShowRationale, true);
});
});
}
import 'package:flutter_test/flutter_test.dart';
import 'package:permission_handler_platform_interface/permission_handler_platform_interface.dart';
import 'package:permission_handler_platform_interface/src/method_channel/utils/codec.dart';
void main() {
group('Codec', () {
test('decodePermissionStatus should return a PermissionStatus', () {
expect(decodePermissionStatus(0), PermissionStatus.denied);
});
test('decodeServiceStatus should a corresponding ServiceStatus', () {
expect(decodeServiceStatus(0), ServiceStatus.disabled);
});
test(
'decodePermissionRequestResult should convert a map<int, int>'
'to map<Permission, PermissionStatus>', () {
var value = <int, int>{
1: 1,
};
var permissionMap = decodePermissionRequestResult(value);
expect(permissionMap.keys.first, isA<Permission>());
expect(permissionMap.values.first, isA<PermissionStatus>());
});
test('encodePermissions should return a list of integers', () {
var permissions = [Permission.accessMediaLocation];
var integers = encodePermissions(permissions);
expect(integers.first, isA<int>());
});
});
}
import 'package:flutter_test/flutter_test.dart';
import 'package:mockito/mockito.dart';
import 'package:permission_handler_platform_interface/permission_handler_platform_interface.dart';
import 'package:permission_handler_platform_interface/src/method_channel/method_channel_permission_handler.dart';
import 'package:plugin_platform_interface/plugin_platform_interface.dart';
void main() {
TestWidgetsFlutterBinding.ensureInitialized();
group('$PermissionHandlerPlatform', () {
test('$MethodChannelPermissionHandler is the default instance', () {
expect(PermissionHandlerPlatform.instance,
isA<MethodChannelPermissionHandler>());
});
test('Cannot be implemented with `implements`', () {
expect(() {
PermissionHandlerPlatform.instance =
ImplementsPermissionHandlerPlatform();
}, throwsA(anything));
});
test('Can be extended with `extend`', () {
PermissionHandlerPlatform.instance = ExtendsPermissionHandlerPlatform();
});
test('Can be mocked with `implements`', () {
final mock = MockPermissionHandlerPlatform();
PermissionHandlerPlatform.instance = mock;
});
test(
// ignore: lines_longer_than_80_chars
'Default implementation of checkPermissionStatus should throw unimplemented error',
() {
final permissionHandlerPlatform = ExtendsPermissionHandlerPlatform();
expect(() {
permissionHandlerPlatform
.checkPermissionStatus(Permission.accessMediaLocation);
}, throwsUnimplementedError);
});
test(
// ignore: lines_longer_than_80_chars
'Default implementation of checkServiceStatus should throw unimplemented error',
() {
final permissionHandlerPlatform = ExtendsPermissionHandlerPlatform();
expect(() {
permissionHandlerPlatform
.checkServiceStatus(Permission.accessMediaLocation);
}, throwsUnimplementedError);
});
test(
// ignore: lines_longer_than_80_chars
'Default implementation of openAppSettings should throw unimplemented error',
() {
final permissionHandlerPlatform = ExtendsPermissionHandlerPlatform();
expect(
permissionHandlerPlatform.openAppSettings, throwsUnimplementedError);
});
test(
// ignore: lines_longer_than_80_chars
'Default implementation of requestPermissions should throw unimplemented error',
() {
final permissionHandlerPlatform = ExtendsPermissionHandlerPlatform();
var permission = <Permission>[Permission.accessMediaLocation];
expect(() {
permissionHandlerPlatform.requestPermissions(permission);
}, throwsUnimplementedError);
});
test(
// ignore: lines_longer_than_80_chars
'Default implementation of shouldShowRequestPermissionRationale should throw unimplemented error',
() {
final permissionHandlerPlatform = ExtendsPermissionHandlerPlatform();
expect(() {
permissionHandlerPlatform.shouldShowRequestPermissionRationale(
Permission.accessMediaLocation);
}, throwsUnimplementedError);
});
});
}
class ImplementsPermissionHandlerPlatform implements PermissionHandlerPlatform {
@override
dynamic noSuchMethod(Invocation invocation) => super.noSuchMethod(invocation);
}
class ExtendsPermissionHandlerPlatform extends PermissionHandlerPlatform {}
class MockPermissionHandlerPlatform extends Mock
with
// ignore: prefer_mixin
MockPlatformInterfaceMixin
implements
PermissionHandlerPlatform {}
import 'package:flutter_test/flutter_test.dart';
import 'package:permission_handler_platform_interface/permission_handler_platform_interface.dart';
void main() {
group('PermissionStatus', () {
test('PermissionStatus should contain 6 options', () {
const values = PermissionStatus.values;
expect(values.length, 6);
});
test('PermissionStatus enum should have items in correct index', () {
const values = PermissionStatus.values;
expect(values[0], PermissionStatus.denied);
expect(values[1], PermissionStatus.granted);
expect(values[2], PermissionStatus.restricted);
expect(values[3], PermissionStatus.limited);
expect(values[4], PermissionStatus.permanentlyDenied);
expect(values[5], PermissionStatus.provisional);
});
});
group('PermissionStatusValue', () {
test('PermissionStatusValue returns right integer', () {
expect(PermissionStatus.denied.value, 0);
expect(PermissionStatus.granted.value, 1);
expect(PermissionStatus.restricted.value, 2);
expect(PermissionStatus.limited.value, 3);
expect(PermissionStatus.permanentlyDenied.value, 4);
expect(PermissionStatus.provisional.value, 5);
});
test(
// ignore: lines_longer_than_80_chars
'statusByValue should return right index int that corresponds with the right PermissionStatus',
() {
expect(PermissionStatusValue.statusByValue(0), PermissionStatus.denied);
expect(PermissionStatusValue.statusByValue(1), PermissionStatus.granted);
expect(
PermissionStatusValue.statusByValue(2), PermissionStatus.restricted);
expect(PermissionStatusValue.statusByValue(3), PermissionStatus.limited);
expect(PermissionStatusValue.statusByValue(4),
PermissionStatus.permanentlyDenied);
expect(
PermissionStatusValue.statusByValue(5), PermissionStatus.provisional);
});
});
group('PermissionStatusGetters', () {
test('Getters should return true if statement is met', () {
expect(PermissionStatus.denied.isDenied, true);
expect(PermissionStatus.granted.isGranted, true);
expect(PermissionStatus.restricted.isRestricted, true);
expect(PermissionStatus.limited.isLimited, true);
expect(PermissionStatus.permanentlyDenied.isPermanentlyDenied, true);
expect(PermissionStatus.provisional.isProvisional, true);
});
test('Getters should return false if statement is not met', () {
expect(PermissionStatus.denied.isGranted, false);
expect(PermissionStatus.granted.isDenied, false);
expect(PermissionStatus.restricted.isDenied, false);
expect(PermissionStatus.limited.isDenied, false);
expect(PermissionStatus.permanentlyDenied.isDenied, false);
expect(PermissionStatus.provisional.isDenied, false);
});
});
group('FuturePermissionStatusGetters', () {
mockFuture(PermissionStatus status) => Future.value(status);
test('Getters should return true if statement is met', () async {
expect(await mockFuture(PermissionStatus.denied).isDenied, true);
expect(await mockFuture(PermissionStatus.granted).isGranted, true);
expect(await mockFuture(PermissionStatus.restricted).isRestricted, true);
expect(await mockFuture(PermissionStatus.limited).isLimited, true);
expect(
await mockFuture(PermissionStatus.permanentlyDenied)
.isPermanentlyDenied,
true);
expect(
await mockFuture(PermissionStatus.provisional).isProvisional, true);
});
test('Getters should return false if statement is not met', () async {
expect(await mockFuture(PermissionStatus.denied).isGranted, false);
expect(await mockFuture(PermissionStatus.granted).isDenied, false);
expect(await mockFuture(PermissionStatus.restricted).isDenied, false);
expect(await mockFuture(PermissionStatus.limited).isDenied, false);
expect(
await mockFuture(PermissionStatus.permanentlyDenied).isDenied, false);
expect(await mockFuture(PermissionStatus.provisional).isDenied, false);
});
});
test('test', () {});
}
import 'package:flutter_test/flutter_test.dart';
import 'package:permission_handler_platform_interface/permission_handler_platform_interface.dart';
void main() {
test('Permission has the right amount of possible Permission values', () {
const values = Permission.values;
expect(values.length, 40);
});
test('check if byValue returns corresponding Permission value', () {
const values = Permission.values;
for (var i = 0; i < values.length; i++) {
expect(values[i], Permission.byValue(i));
}
});
test('check if toString method returns the corresponding name', () {
const PermissionWithService permissionWithService =
PermissionWithService.private(0);
var permissionName = permissionWithService.toString();
expect(permissionName, 'Permission.calendar');
});
test('check if toString works on all Permission values', () {
const values = Permission.values;
for (var i = 0; i < values.length; i++) {
expect(values[i].toString(), isNotNull);
}
});
test(
// ignore: lines_longer_than_80_chars
'equality operator should return true for two instances with the same values',
() {
// Arrange
final firstPermission = Permission.byValue(1);
final secondPermission = Permission.byValue(1);
// Act & Assert
expect(
firstPermission == secondPermission,
true,
);
});
test(
// ignore: lines_longer_than_80_chars
'equality operator should return false for two instances with different values',
() {
// Arrange
final firstPermission = Permission.byValue(1);
final secondPermission = Permission.byValue(2);
// Act & Assert
expect(
firstPermission == secondPermission,
false,
);
});
test('hashCode should be the same for two instances with the same values',
() {
// Arrange
final firstPermission = Permission.byValue(1);
final secondPermission = Permission.byValue(1);
// Act & Assert
expect(
firstPermission.hashCode,
secondPermission.hashCode,
);
});
test('hashCode should not match for two instances with different values', () {
// Arrange
final firstPermission = Permission.byValue(1);
final secondPermission = Permission.byValue(2);
// Act & Assert
expect(
firstPermission.hashCode == secondPermission.hashCode,
false,
);
});
}
import 'package:flutter_test/flutter_test.dart';
import 'package:permission_handler_platform_interface/permission_handler_platform_interface.dart';
void main() {
group('ServiceStatus', () {
test('ServiceStatus should contain 3 options', () {
const values = ServiceStatus.values;
expect(values.length, 3);
});
test('ServiceStatus enum should have items in correct index', () {
const values = ServiceStatus.values;
expect(values[0], ServiceStatus.disabled);
expect(values[1], ServiceStatus.enabled);
expect(values[2], ServiceStatus.notApplicable);
});
});
group('ServiceStatusValue', () {
test('ServiceStatusValue returns right integer', () {
expect(ServiceStatus.disabled.value, 0);
expect(ServiceStatus.enabled.value, 1);
expect(ServiceStatus.notApplicable.value, 2);
});
test(
// ignore: lines_longer_than_80_chars
'statusByValue should return right index int that corresponds with the right PermissionStatus',
() {
expect(ServiceStatusValue.statusByValue(0), ServiceStatus.disabled);
expect(ServiceStatusValue.statusByValue(1), ServiceStatus.enabled);
expect(ServiceStatusValue.statusByValue(2), ServiceStatus.notApplicable);
});
});
group('ServiceStatusGetters', () {
test('Getters should return true if statement is met', () {
expect(ServiceStatus.disabled.isDisabled, true);
expect(ServiceStatus.enabled.isEnabled, true);
expect(ServiceStatus.notApplicable.isNotApplicable, true);
});
test('Getters should return false if statement is not met', () {
expect(ServiceStatus.disabled.isEnabled, false);
expect(ServiceStatus.enabled.isDisabled, false);
expect(ServiceStatus.notApplicable.isDisabled, false);
});
});
}
# Below is a list of people and organizations that have contributed
# to the Flutter project. Names should be added to the list like so:
#
# Name/Organization <email address>
Baseflow <hello@baseflow.com>
Alexandre Zollinger Chohfi <alzollin@microsoft.com>
Maurits van Beusekom <maurits@baseflow.com>
## 0.2.1
* Updates the dependency on `permission_handler_platform_interface` to version 4.1.0 (SiriKit support is only available for iOS and macOS).
## 0.2.0
* Implements the `Permission.calendarWriteOnly` and `Permission.calendarFullAccess` permissions.
* Bumps `permission_handler_platform_interface` to version `4.0.0`.
## 0.1.3
* Adds the new Android 13 permission "BODY_SENSORS_BACKGROUND" to PermissionHandlerEnums.h.
## 0.1.2
* Adds the new Android 13 permissions "SCHEDULE_EXACT_ALARM, READ_MEDIA_IMAGES, READ_MEDIA_VIDEO and READ_MEDIA_AUDIO" to permission_constants.h.
## 0.1.1
* Adds the new Android 13 NEARBY_WIFI_DEVICES permission to permission_constants.h.
## 0.1.0
* Adds an initial implementation of Windows support for the permission_handler plugin.
MIT License
Copyright (c) 2018 Baseflow
Permission is hereby granted, free of charge, to any person obtaining a copy
of this software and associated documentation files (the "Software"), to deal
in the Software without restriction, including without limitation the rights
to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
copies of the Software, and to permit persons to whom the Software is
furnished to do so, subject to the following conditions:
The above copyright notice and this permission notice shall be included in all
copies or substantial portions of the Software.
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
SOFTWARE.
# permission_handler_windows
[![pub package](https://img.shields.io/pub/v/permission_handler_windows.svg)](https://pub.dartlang.org/packages/permission_handler_windows) ![Build status](https://github.com/Baseflow/flutter-permission-handler/workflows/permission_handler_android/badge.svg?branch=master) [![style: flutter lints](https://img.shields.io/badge/style-flutter_lints-40c4ff.svg)](https://pub.dev/packages/flutter_lints)
The official Windows implementation of the [permission_handler](https://pub.dev/packages/permission_handler) plugin by [Baseflow](https://baseflow.com).
## Usage
Starting from version 9.2.0 of the [permission_handler](https://pub.dev/packages/permission_handler) plugin this is the endorsed Windows implementation. This means it will automatically be added to your dependencies when you depend on `permission_handler: ^9.2.0` in your applications pubspec.yaml.
More detailed instructions on using the API can be found in the [README.md](../permission_handler/README.md) of the [permission_handler](https://pub.dev/packages/permission_handler) package.
## Issues
Please file any issues, bugs or feature requests as an issue on our [GitHub](https://github.com/Baseflow/flutter-permission-handler/issues) page. Commercial support is available, you can contact us at <hello@baseflow.com>.
## Want to contribute
If you would like to contribute to the plugin (e.g. by improving the documentation, solving a bug or adding a cool new feature), please carefully review our [contribution guide](../CONTRIBUTING.md) and send us your [pull request](https://github.com/Baseflow/flutter-permission-handler/pulls).
## Author
This permission_handler plugin for Flutter is developed by [Baseflow](https://baseflow.com).
# Miscellaneous
*.class
*.log
*.pyc
*.swp
.DS_Store
.atom/
.buildlog/
.history
.svn/
# IntelliJ related
*.iml
*.ipr
*.iws
.idea/
# The .vscode folder contains launch configuration and tasks you configure in
# VS Code which you may wish to be included in version control, so this line
# is commented out by default.
#.vscode/
# Flutter/Dart/Pub related
**/doc/api/
**/ios/Flutter/.last_build_id
.dart_tool/
.flutter-plugins
.flutter-plugins-dependencies
.packages
.pub-cache/
.pub/
/build/
# Web related
lib/generated_plugin_registrant.dart
# Symbolication related
app.*.symbols
# Obfuscation related
app.*.map.json
# Android Studio will place build artifacts here
/android/app/debug
/android/app/profile
/android/app/release
# This file tracks properties of this Flutter project.
# Used by Flutter tool to assess capabilities and perform upgrades etc.
#
# This file should be version controlled and should not be manually edited.
version:
revision: db747aa1331bd95bc9b3874c842261ca2d302cd5
channel: stable
project_type: app
# permission_handler_example
Demonstrates how to use the permission_handler plugin.
## Getting Started
This project is a starting point for a Flutter application.
A few resources to get you started if this is your first Flutter project:
- [Lab: Write your first Flutter app](https://flutter.io/docs/get-started/codelab)
- [Cookbook: Useful Flutter samples](https://flutter.io/docs/cookbook)
For help getting started with Flutter, view our
[online documentation](https://flutter.io/docs), which offers tutorials,
samples, guidance on mobile development, and a full API reference.
import 'package:baseflow_plugin_template/baseflow_plugin_template.dart';
import 'package:flutter/material.dart';
import 'package:permission_handler_platform_interface/permission_handler_platform_interface.dart';
void main() {
runApp(BaseflowPluginExample(
pluginName: 'Permission Handler',
githubURL: 'https://github.com/Baseflow/flutter-permission-handler',
pubDevURL: 'https://pub.dev/packages/permission_handler',
pages: [PermissionHandlerWidget.createPage()]));
}
///Defines the main theme color
final MaterialColor themeMaterialColor =
BaseflowPluginExample.createMaterialColor(
const Color.fromRGBO(48, 49, 60, 1));
/// A Flutter application demonstrating the functionality of this plugin
class PermissionHandlerWidget extends StatefulWidget {
/// Create a page containing the functionality of this plugin
static ExamplePage createPage() {
return ExamplePage(
Icons.location_on, (context) => PermissionHandlerWidget());
}
@override
_PermissionHandlerWidgetState createState() =>
_PermissionHandlerWidgetState();
}
class _PermissionHandlerWidgetState extends State<PermissionHandlerWidget> {
@override
Widget build(BuildContext context) {
return Center(
child: ListView(
children: Permission.values
.where((permission) {
return permission != Permission.unknown &&
permission != Permission.mediaLibrary &&
permission != Permission.photos &&
permission != Permission.photosAddOnly &&
permission != Permission.reminders &&
permission != Permission.appTrackingTransparency &&
permission != Permission.criticalAlerts;
})
.map((permission) => PermissionWidget(permission))
.toList()),
);
}
}
/// Permission widget containing information about the passed [Permission]
class PermissionWidget extends StatefulWidget {
/// Constructs a [PermissionWidget] for the supplied [Permission]
const PermissionWidget(this._permission);
final Permission _permission;
@override
_PermissionState createState() => _PermissionState(_permission);
}
class _PermissionState extends State<PermissionWidget> {
_PermissionState(this._permission);
final Permission _permission;
final PermissionHandlerPlatform _permissionHandler =
PermissionHandlerPlatform.instance;
PermissionStatus _permissionStatus = PermissionStatus.denied;
@override
void initState() {
super.initState();
_listenForPermissionStatus();
}
void _listenForPermissionStatus() async {
final status = await _permissionHandler.checkPermissionStatus(_permission);
setState(() => _permissionStatus = status);
}
Color getPermissionColor() {
switch (_permissionStatus) {
case PermissionStatus.denied:
return Colors.red;
case PermissionStatus.granted:
return Colors.green;
case PermissionStatus.limited:
return Colors.orange;
default:
return Colors.grey;
}
}
@override
Widget build(BuildContext context) {
return ListTile(
title: Text(
_permission.toString(),
style: Theme.of(context).textTheme.bodyLarge,
),
subtitle: Text(
_permissionStatus.toString(),
style: TextStyle(color: getPermissionColor()),
),
trailing: (_permission is PermissionWithService)
? IconButton(
icon: const Icon(
Icons.info,
color: Colors.white,
),
onPressed: () {
checkServiceStatus(
context, _permission as PermissionWithService);
})
: null,
onTap: () {
requestPermission(_permission);
},
);
}
void checkServiceStatus(
BuildContext context, PermissionWithService permission) async {
ScaffoldMessenger.of(context).showSnackBar(SnackBar(
content: Text(
(await _permissionHandler.checkServiceStatus(permission)).toString()),
));
}
Future<void> requestPermission(Permission permission) async {
final status = await _permissionHandler.requestPermissions([permission]);
setState(() {
print(status);
_permissionStatus = status[permission] ?? PermissionStatus.denied;
print(_permissionStatus);
});
}
}
name: permission_handler_windows_example
description: Demonstrates how to use the permission_handler_windows plugin.
environment:
sdk: ">=2.15.0 <3.0.0"
dependencies:
baseflow_plugin_template: ^2.1.1
flutter:
sdk: flutter
dev_dependencies:
flutter_test:
sdk: flutter
permission_handler_windows:
# When depending on this package from a real application you should use:
# permission_handler_windows: ^x.y.z
# See https://dart.dev/tools/pub/dependencies#version-constraints
# The example app is bundled with the plugin so we use a path dependency on
# the parent directory to use the current plugin's version.
path: ../
url_launcher: ^6.0.12
flutter:
uses-material-design: true
assets:
- res/images/baseflow_logo_def_light-02.png
- res/images/poweredByBaseflowLogoLight@3x.png
- packages/baseflow_plugin_template/logo.png
- packages/baseflow_plugin_template/poweredByBaseflow.png
flutter/ephemeral/
# Visual Studio user-specific files.
*.suo
*.user
*.userosscache
*.sln.docstates
# Visual Studio build-related files.
x64/
x86/
# Visual Studio cache files
# files ending in .cache can be ignored
*.[Cc]ache
# but keep track of directories ending in .cache
!*.[Cc]ache/
cmake_minimum_required(VERSION 3.14)
project(example LANGUAGES CXX)
set(BINARY_NAME "example")
cmake_policy(SET CMP0063 NEW)
set(CMAKE_INSTALL_RPATH "$ORIGIN/lib")
# Configure build options.
get_property(IS_MULTICONFIG GLOBAL PROPERTY GENERATOR_IS_MULTI_CONFIG)
if(IS_MULTICONFIG)
set(CMAKE_CONFIGURATION_TYPES "Debug;Profile;Release"
CACHE STRING "" FORCE)
else()
if(NOT CMAKE_BUILD_TYPE AND NOT CMAKE_CONFIGURATION_TYPES)
set(CMAKE_BUILD_TYPE "Debug" CACHE
STRING "Flutter build mode" FORCE)
set_property(CACHE CMAKE_BUILD_TYPE PROPERTY STRINGS
"Debug" "Profile" "Release")
endif()
endif()
set(CMAKE_EXE_LINKER_FLAGS_PROFILE "${CMAKE_EXE_LINKER_FLAGS_RELEASE}")
set(CMAKE_SHARED_LINKER_FLAGS_PROFILE "${CMAKE_SHARED_LINKER_FLAGS_RELEASE}")
set(CMAKE_C_FLAGS_PROFILE "${CMAKE_C_FLAGS_RELEASE}")
set(CMAKE_CXX_FLAGS_PROFILE "${CMAKE_CXX_FLAGS_RELEASE}")
# Use Unicode for all projects.
add_definitions(-DUNICODE -D_UNICODE)
# Compilation settings that should be applied to most targets.
function(APPLY_STANDARD_SETTINGS TARGET)
target_compile_features(${TARGET} PUBLIC cxx_std_17)
target_compile_options(${TARGET} PRIVATE /W4 /WX /wd"4100")
target_compile_options(${TARGET} PRIVATE /EHsc)
target_compile_definitions(${TARGET} PRIVATE "_HAS_EXCEPTIONS=0")
target_compile_definitions(${TARGET} PRIVATE "$<$<CONFIG:Debug>:_DEBUG>")
endfunction()
set(FLUTTER_MANAGED_DIR "${CMAKE_CURRENT_SOURCE_DIR}/flutter")
# Flutter library and tool build rules.
add_subdirectory(${FLUTTER_MANAGED_DIR})
# Application build
add_subdirectory("runner")
# Generated plugin build rules, which manage building the plugins and adding
# them to the application.
include(flutter/generated_plugins.cmake)
# === Installation ===
# Support files are copied into place next to the executable, so that it can
# run in place. This is done instead of making a separate bundle (as on Linux)
# so that building and running from within Visual Studio will work.
set(BUILD_BUNDLE_DIR "$<TARGET_FILE_DIR:${BINARY_NAME}>")
# Make the "install" step default, as it's required to run.
set(CMAKE_VS_INCLUDE_INSTALL_TO_DEFAULT_BUILD 1)
if(CMAKE_INSTALL_PREFIX_INITIALIZED_TO_DEFAULT)
set(CMAKE_INSTALL_PREFIX "${BUILD_BUNDLE_DIR}" CACHE PATH "..." FORCE)
endif()
set(INSTALL_BUNDLE_DATA_DIR "${CMAKE_INSTALL_PREFIX}/data")
set(INSTALL_BUNDLE_LIB_DIR "${CMAKE_INSTALL_PREFIX}")
install(TARGETS ${BINARY_NAME} RUNTIME DESTINATION "${CMAKE_INSTALL_PREFIX}"
COMPONENT Runtime)
install(FILES "${FLUTTER_ICU_DATA_FILE}" DESTINATION "${INSTALL_BUNDLE_DATA_DIR}"
COMPONENT Runtime)
install(FILES "${FLUTTER_LIBRARY}" DESTINATION "${INSTALL_BUNDLE_LIB_DIR}"
COMPONENT Runtime)
if(PLUGIN_BUNDLED_LIBRARIES)
install(FILES "${PLUGIN_BUNDLED_LIBRARIES}"
DESTINATION "${INSTALL_BUNDLE_LIB_DIR}"
COMPONENT Runtime)
endif()
# Fully re-copy the assets directory on each build to avoid having stale files
# from a previous install.
set(FLUTTER_ASSET_DIR_NAME "flutter_assets")
install(CODE "
file(REMOVE_RECURSE \"${INSTALL_BUNDLE_DATA_DIR}/${FLUTTER_ASSET_DIR_NAME}\")
" COMPONENT Runtime)
install(DIRECTORY "${PROJECT_BUILD_DIR}/${FLUTTER_ASSET_DIR_NAME}"
DESTINATION "${INSTALL_BUNDLE_DATA_DIR}" COMPONENT Runtime)
# Install the AOT library on non-Debug builds only.
install(FILES "${AOT_LIBRARY}" DESTINATION "${INSTALL_BUNDLE_DATA_DIR}"
CONFIGURATIONS Profile;Release
COMPONENT Runtime)
cmake_minimum_required(VERSION 3.14)
set(EPHEMERAL_DIR "${CMAKE_CURRENT_SOURCE_DIR}/ephemeral")
# Configuration provided via flutter tool.
include(${EPHEMERAL_DIR}/generated_config.cmake)
# TODO: Move the rest of this into files in ephemeral. See
# https://github.com/flutter/flutter/issues/57146.
set(WRAPPER_ROOT "${EPHEMERAL_DIR}/cpp_client_wrapper")
# === Flutter Library ===
set(FLUTTER_LIBRARY "${EPHEMERAL_DIR}/flutter_windows.dll")
# Published to parent scope for install step.
set(FLUTTER_LIBRARY ${FLUTTER_LIBRARY} PARENT_SCOPE)
set(FLUTTER_ICU_DATA_FILE "${EPHEMERAL_DIR}/icudtl.dat" PARENT_SCOPE)
set(PROJECT_BUILD_DIR "${PROJECT_DIR}/build/" PARENT_SCOPE)
set(AOT_LIBRARY "${PROJECT_DIR}/build/windows/app.so" PARENT_SCOPE)
list(APPEND FLUTTER_LIBRARY_HEADERS
"flutter_export.h"
"flutter_windows.h"
"flutter_messenger.h"
"flutter_plugin_registrar.h"
"flutter_texture_registrar.h"
)
list(TRANSFORM FLUTTER_LIBRARY_HEADERS PREPEND "${EPHEMERAL_DIR}/")
add_library(flutter INTERFACE)
target_include_directories(flutter INTERFACE
"${EPHEMERAL_DIR}"
)
target_link_libraries(flutter INTERFACE "${FLUTTER_LIBRARY}.lib")
add_dependencies(flutter flutter_assemble)
# === Wrapper ===
list(APPEND CPP_WRAPPER_SOURCES_CORE
"core_implementations.cc"
"standard_codec.cc"
)
list(TRANSFORM CPP_WRAPPER_SOURCES_CORE PREPEND "${WRAPPER_ROOT}/")
list(APPEND CPP_WRAPPER_SOURCES_PLUGIN
"plugin_registrar.cc"
)
list(TRANSFORM CPP_WRAPPER_SOURCES_PLUGIN PREPEND "${WRAPPER_ROOT}/")
list(APPEND CPP_WRAPPER_SOURCES_APP
"flutter_engine.cc"
"flutter_view_controller.cc"
)
list(TRANSFORM CPP_WRAPPER_SOURCES_APP PREPEND "${WRAPPER_ROOT}/")
# Wrapper sources needed for a plugin.
add_library(flutter_wrapper_plugin STATIC
${CPP_WRAPPER_SOURCES_CORE}
${CPP_WRAPPER_SOURCES_PLUGIN}
)
apply_standard_settings(flutter_wrapper_plugin)
set_target_properties(flutter_wrapper_plugin PROPERTIES
POSITION_INDEPENDENT_CODE ON)
set_target_properties(flutter_wrapper_plugin PROPERTIES
CXX_VISIBILITY_PRESET hidden)
target_link_libraries(flutter_wrapper_plugin PUBLIC flutter)
target_include_directories(flutter_wrapper_plugin PUBLIC
"${WRAPPER_ROOT}/include"
)
add_dependencies(flutter_wrapper_plugin flutter_assemble)
# Wrapper sources needed for the runner.
add_library(flutter_wrapper_app STATIC
${CPP_WRAPPER_SOURCES_CORE}
${CPP_WRAPPER_SOURCES_APP}
)
apply_standard_settings(flutter_wrapper_app)
target_link_libraries(flutter_wrapper_app PUBLIC flutter)
target_include_directories(flutter_wrapper_app PUBLIC
"${WRAPPER_ROOT}/include"
)
add_dependencies(flutter_wrapper_app flutter_assemble)
# === Flutter tool backend ===
# _phony_ is a non-existent file to force this command to run every time,
# since currently there's no way to get a full input/output list from the
# flutter tool.
set(PHONY_OUTPUT "${CMAKE_CURRENT_BINARY_DIR}/_phony_")
set_source_files_properties("${PHONY_OUTPUT}" PROPERTIES SYMBOLIC TRUE)
add_custom_command(
OUTPUT ${FLUTTER_LIBRARY} ${FLUTTER_LIBRARY_HEADERS}
${CPP_WRAPPER_SOURCES_CORE} ${CPP_WRAPPER_SOURCES_PLUGIN}
${CPP_WRAPPER_SOURCES_APP}
${PHONY_OUTPUT}
COMMAND ${CMAKE_COMMAND} -E env
${FLUTTER_TOOL_ENVIRONMENT}
"${FLUTTER_ROOT}/packages/flutter_tools/bin/tool_backend.bat"
windows-x64 $<CONFIG>
VERBATIM
)
add_custom_target(flutter_assemble DEPENDS
"${FLUTTER_LIBRARY}"
${FLUTTER_LIBRARY_HEADERS}
${CPP_WRAPPER_SOURCES_CORE}
${CPP_WRAPPER_SOURCES_PLUGIN}
${CPP_WRAPPER_SOURCES_APP}
)
//
// Generated file. Do not edit.
//
// clang-format off
#include "generated_plugin_registrant.h"
#include <permission_handler_windows/permission_handler_windows_plugin.h>
#include <url_launcher_windows/url_launcher_windows.h>
void RegisterPlugins(flutter::PluginRegistry* registry) {
PermissionHandlerWindowsPluginRegisterWithRegistrar(
registry->GetRegistrarForPlugin("PermissionHandlerWindowsPlugin"));
UrlLauncherWindowsRegisterWithRegistrar(
registry->GetRegistrarForPlugin("UrlLauncherWindows"));
}
//
// Generated file. Do not edit.
//
// clang-format off
#ifndef GENERATED_PLUGIN_REGISTRANT_
#define GENERATED_PLUGIN_REGISTRANT_
#include <flutter/plugin_registry.h>
// Registers Flutter plugins.
void RegisterPlugins(flutter::PluginRegistry* registry);
#endif // GENERATED_PLUGIN_REGISTRANT_
#
# Generated file, do not edit.
#
list(APPEND FLUTTER_PLUGIN_LIST
permission_handler_windows
url_launcher_windows
)
list(APPEND FLUTTER_FFI_PLUGIN_LIST
)
set(PLUGIN_BUNDLED_LIBRARIES)
foreach(plugin ${FLUTTER_PLUGIN_LIST})
add_subdirectory(flutter/ephemeral/.plugin_symlinks/${plugin}/windows plugins/${plugin})
target_link_libraries(${BINARY_NAME} PRIVATE ${plugin}_plugin)
list(APPEND PLUGIN_BUNDLED_LIBRARIES $<TARGET_FILE:${plugin}_plugin>)
list(APPEND PLUGIN_BUNDLED_LIBRARIES ${${plugin}_bundled_libraries})
endforeach(plugin)
foreach(ffi_plugin ${FLUTTER_FFI_PLUGIN_LIST})
add_subdirectory(flutter/ephemeral/.plugin_symlinks/${ffi_plugin}/windows plugins/${ffi_plugin})
list(APPEND PLUGIN_BUNDLED_LIBRARIES ${${ffi_plugin}_bundled_libraries})
endforeach(ffi_plugin)
cmake_minimum_required(VERSION 3.14)
project(runner LANGUAGES CXX)
add_executable(${BINARY_NAME} WIN32
"flutter_window.cpp"
"main.cpp"
"utils.cpp"
"win32_window.cpp"
"${FLUTTER_MANAGED_DIR}/generated_plugin_registrant.cc"
"Runner.rc"
"runner.exe.manifest"
)
apply_standard_settings(${BINARY_NAME})
target_compile_definitions(${BINARY_NAME} PRIVATE "NOMINMAX")
target_link_libraries(${BINARY_NAME} PRIVATE flutter flutter_wrapper_app)
target_include_directories(${BINARY_NAME} PRIVATE "${CMAKE_SOURCE_DIR}")
add_dependencies(${BINARY_NAME} flutter_assemble)
// Microsoft Visual C++ generated resource script.
//
#pragma code_page(65001)
#include "resource.h"
#define APSTUDIO_READONLY_SYMBOLS
/////////////////////////////////////////////////////////////////////////////
//
// Generated from the TEXTINCLUDE 2 resource.
//
#include "winres.h"
/////////////////////////////////////////////////////////////////////////////
#undef APSTUDIO_READONLY_SYMBOLS
/////////////////////////////////////////////////////////////////////////////
// English (United States) resources
#if !defined(AFX_RESOURCE_DLL) || defined(AFX_TARG_ENU)
LANGUAGE LANG_ENGLISH, SUBLANG_ENGLISH_US
#ifdef APSTUDIO_INVOKED
/////////////////////////////////////////////////////////////////////////////
//
// TEXTINCLUDE
//
1 TEXTINCLUDE
BEGIN
"resource.h\0"
END
2 TEXTINCLUDE
BEGIN
"#include ""winres.h""\r\n"
"\0"
END
3 TEXTINCLUDE
BEGIN
"\r\n"
"\0"
END
#endif // APSTUDIO_INVOKED
/////////////////////////////////////////////////////////////////////////////
//
// Icon
//
// Icon with lowest ID value placed first to ensure application icon
// remains consistent on all systems.
IDI_APP_ICON ICON "resources\\app_icon.ico"
/////////////////////////////////////////////////////////////////////////////
//
// Version
//
#ifdef FLUTTER_BUILD_NUMBER
#define VERSION_AS_NUMBER FLUTTER_BUILD_NUMBER
#else
#define VERSION_AS_NUMBER 1,0,0
#endif
#ifdef FLUTTER_BUILD_NAME
#define VERSION_AS_STRING #FLUTTER_BUILD_NAME
#else
#define VERSION_AS_STRING "1.0.0"
#endif
VS_VERSION_INFO VERSIONINFO
FILEVERSION VERSION_AS_NUMBER
PRODUCTVERSION VERSION_AS_NUMBER
FILEFLAGSMASK VS_FFI_FILEFLAGSMASK
#ifdef _DEBUG
FILEFLAGS VS_FF_DEBUG
#else
FILEFLAGS 0x0L
#endif
FILEOS VOS__WINDOWS32
FILETYPE VFT_APP
FILESUBTYPE 0x0L
BEGIN
BLOCK "StringFileInfo"
BEGIN
BLOCK "040904e4"
BEGIN
VALUE "CompanyName", "com.example" "\0"
VALUE "FileDescription", "example" "\0"
VALUE "FileVersion", VERSION_AS_STRING "\0"
VALUE "InternalName", "example" "\0"
VALUE "LegalCopyright", "Copyright (C) 2022 com.example. All rights reserved." "\0"
VALUE "OriginalFilename", "example.exe" "\0"
VALUE "ProductName", "example" "\0"
VALUE "ProductVersion", VERSION_AS_STRING "\0"
END
END
BLOCK "VarFileInfo"
BEGIN
VALUE "Translation", 0x409, 1252
END
END
#endif // English (United States) resources
/////////////////////////////////////////////////////////////////////////////
#ifndef APSTUDIO_INVOKED
/////////////////////////////////////////////////////////////////////////////
//
// Generated from the TEXTINCLUDE 3 resource.
//
/////////////////////////////////////////////////////////////////////////////
#endif // not APSTUDIO_INVOKED
#include "flutter_window.h"
#include <optional>
#include "flutter/generated_plugin_registrant.h"
FlutterWindow::FlutterWindow(const flutter::DartProject& project)
: project_(project) {}
FlutterWindow::~FlutterWindow() {}
bool FlutterWindow::OnCreate() {
if (!Win32Window::OnCreate()) {
return false;
}
RECT frame = GetClientArea();
// The size here must match the window dimensions to avoid unnecessary surface
// creation / destruction in the startup path.
flutter_controller_ = std::make_unique<flutter::FlutterViewController>(
frame.right - frame.left, frame.bottom - frame.top, project_);
// Ensure that basic setup of the controller was successful.
if (!flutter_controller_->engine() || !flutter_controller_->view()) {
return false;
}
RegisterPlugins(flutter_controller_->engine());
SetChildContent(flutter_controller_->view()->GetNativeWindow());
return true;
}
void FlutterWindow::OnDestroy() {
if (flutter_controller_) {
flutter_controller_ = nullptr;
}
Win32Window::OnDestroy();
}
LRESULT
FlutterWindow::MessageHandler(HWND hwnd, UINT const message,
WPARAM const wparam,
LPARAM const lparam) noexcept {
// Give Flutter, including plugins, an opportunity to handle window messages.
if (flutter_controller_) {
std::optional<LRESULT> result =
flutter_controller_->HandleTopLevelWindowProc(hwnd, message, wparam,
lparam);
if (result) {
return *result;
}
}
switch (message) {
case WM_FONTCHANGE:
flutter_controller_->engine()->ReloadSystemFonts();
break;
}
return Win32Window::MessageHandler(hwnd, message, wparam, lparam);
}
#ifndef RUNNER_FLUTTER_WINDOW_H_
#define RUNNER_FLUTTER_WINDOW_H_
#include <flutter/dart_project.h>
#include <flutter/flutter_view_controller.h>
#include <memory>
#include "win32_window.h"
// A window that does nothing but host a Flutter view.
class FlutterWindow : public Win32Window {
public:
// Creates a new FlutterWindow hosting a Flutter view running |project|.
explicit FlutterWindow(const flutter::DartProject& project);
virtual ~FlutterWindow();
protected:
// Win32Window:
bool OnCreate() override;
void OnDestroy() override;
LRESULT MessageHandler(HWND window, UINT const message, WPARAM const wparam,
LPARAM const lparam) noexcept override;
private:
// The project to run.
flutter::DartProject project_;
// The Flutter instance hosted by this window.
std::unique_ptr<flutter::FlutterViewController> flutter_controller_;
};
#endif // RUNNER_FLUTTER_WINDOW_H_
#include <flutter/dart_project.h>
#include <flutter/flutter_view_controller.h>
#include <windows.h>
#include "flutter_window.h"
#include "utils.h"
int APIENTRY wWinMain(_In_ HINSTANCE instance, _In_opt_ HINSTANCE prev,
_In_ wchar_t *command_line, _In_ int show_command) {
// Attach to console when present (e.g., 'flutter run') or create a
// new console when running with a debugger.
if (!::AttachConsole(ATTACH_PARENT_PROCESS) && ::IsDebuggerPresent()) {
CreateAndAttachConsole();
}
// Initialize COM, so that it is available for use in the library and/or
// plugins.
::CoInitializeEx(nullptr, COINIT_APARTMENTTHREADED);
flutter::DartProject project(L"data");
std::vector<std::string> command_line_arguments =
GetCommandLineArguments();
project.set_dart_entrypoint_arguments(std::move(command_line_arguments));
FlutterWindow window(project);
Win32Window::Point origin(10, 10);
Win32Window::Size size(1280, 720);
if (!window.CreateAndShow(L"example", origin, size)) {
return EXIT_FAILURE;
}
window.SetQuitOnClose(true);
::MSG msg;
while (::GetMessage(&msg, nullptr, 0, 0)) {
::TranslateMessage(&msg);
::DispatchMessage(&msg);
}
::CoUninitialize();
return EXIT_SUCCESS;
}
//{{NO_DEPENDENCIES}}
// Microsoft Visual C++ generated include file.
// Used by Runner.rc
//
#define IDI_APP_ICON 101
// Next default values for new objects
//
#ifdef APSTUDIO_INVOKED
#ifndef APSTUDIO_READONLY_SYMBOLS
#define _APS_NEXT_RESOURCE_VALUE 102
#define _APS_NEXT_COMMAND_VALUE 40001
#define _APS_NEXT_CONTROL_VALUE 1001
#define _APS_NEXT_SYMED_VALUE 101
#endif
#endif
<?xml version="1.0" encoding="UTF-8" standalone="yes"?>
<assembly xmlns="urn:schemas-microsoft-com:asm.v1" manifestVersion="1.0">
<application xmlns="urn:schemas-microsoft-com:asm.v3">
<windowsSettings>
<dpiAwareness xmlns="http://schemas.microsoft.com/SMI/2016/WindowsSettings">PerMonitorV2</dpiAwareness>
</windowsSettings>
</application>
<compatibility xmlns="urn:schemas-microsoft-com:compatibility.v1">
<application>
<!-- Windows 10 -->
<supportedOS Id="{8e0f7a12-bfb3-4fe8-b9a5-48fd50a15a9a}"/>
<!-- Windows 8.1 -->
<supportedOS Id="{1f676c76-80e1-4239-95bb-83d0f6d0da78}"/>
<!-- Windows 8 -->
<supportedOS Id="{4a2f28e3-53b9-4441-ba9c-d69d4a4a6e38}"/>
<!-- Windows 7 -->
<supportedOS Id="{35138b9a-5d96-4fbd-8e2d-a2440225f93a}"/>
</application>
</compatibility>
</assembly>
#include "utils.h"
#include <flutter_windows.h>
#include <io.h>
#include <stdio.h>
#include <windows.h>
#include <iostream>
void CreateAndAttachConsole() {
if (::AllocConsole()) {
FILE *unused;
if (freopen_s(&unused, "CONOUT$", "w", stdout)) {
_dup2(_fileno(stdout), 1);
}
if (freopen_s(&unused, "CONOUT$", "w", stderr)) {
_dup2(_fileno(stdout), 2);
}
std::ios::sync_with_stdio();
FlutterDesktopResyncOutputStreams();
}
}
std::vector<std::string> GetCommandLineArguments() {
// Convert the UTF-16 command line arguments to UTF-8 for the Engine to use.
int argc;
wchar_t** argv = ::CommandLineToArgvW(::GetCommandLineW(), &argc);
if (argv == nullptr) {
return std::vector<std::string>();
}
std::vector<std::string> command_line_arguments;
// Skip the first argument as it's the binary name.
for (int i = 1; i < argc; i++) {
command_line_arguments.push_back(Utf8FromUtf16(argv[i]));
}
::LocalFree(argv);
return command_line_arguments;
}
std::string Utf8FromUtf16(const wchar_t* utf16_string) {
if (utf16_string == nullptr) {
return std::string();
}
int target_length = ::WideCharToMultiByte(
CP_UTF8, WC_ERR_INVALID_CHARS, utf16_string,
-1, nullptr, 0, nullptr, nullptr);
if (target_length == 0) {
return std::string();
}
std::string utf8_string;
utf8_string.resize(target_length);
int converted_length = ::WideCharToMultiByte(
CP_UTF8, WC_ERR_INVALID_CHARS, utf16_string,
-1, utf8_string.data(),
target_length, nullptr, nullptr);
if (converted_length == 0) {
return std::string();
}
return utf8_string;
}
#ifndef RUNNER_UTILS_H_
#define RUNNER_UTILS_H_
#include <string>
#include <vector>
// Creates a console for the process, and redirects stdout and stderr to
// it for both the runner and the Flutter library.
void CreateAndAttachConsole();
// Takes a null-terminated wchar_t* encoded in UTF-16 and returns a std::string
// encoded in UTF-8. Returns an empty std::string on failure.
std::string Utf8FromUtf16(const wchar_t* utf16_string);
// Gets the command line arguments passed in as a std::vector<std::string>,
// encoded in UTF-8. Returns an empty std::vector<std::string> on failure.
std::vector<std::string> GetCommandLineArguments();
#endif // RUNNER_UTILS_H_
#include "win32_window.h"
#include <flutter_windows.h>
#include "resource.h"
namespace {
constexpr const wchar_t kWindowClassName[] = L"FLUTTER_RUNNER_WIN32_WINDOW";
// The number of Win32Window objects that currently exist.
static int g_active_window_count = 0;
using EnableNonClientDpiScaling = BOOL __stdcall(HWND hwnd);
// Scale helper to convert logical scaler values to physical using passed in
// scale factor
int Scale(int source, double scale_factor) {
return static_cast<int>(source * scale_factor);
}
// Dynamically loads the |EnableNonClientDpiScaling| from the User32 module.
// This API is only needed for PerMonitor V1 awareness mode.
void EnableFullDpiSupportIfAvailable(HWND hwnd) {
HMODULE user32_module = LoadLibraryA("User32.dll");
if (!user32_module) {
return;
}
auto enable_non_client_dpi_scaling =
reinterpret_cast<EnableNonClientDpiScaling*>(
GetProcAddress(user32_module, "EnableNonClientDpiScaling"));
if (enable_non_client_dpi_scaling != nullptr) {
enable_non_client_dpi_scaling(hwnd);
FreeLibrary(user32_module);
}
}
} // namespace
// Manages the Win32Window's window class registration.
class WindowClassRegistrar {
public:
~WindowClassRegistrar() = default;
// Returns the singleton registar instance.
static WindowClassRegistrar* GetInstance() {
if (!instance_) {
instance_ = new WindowClassRegistrar();
}
return instance_;
}
// Returns the name of the window class, registering the class if it hasn't
// previously been registered.
const wchar_t* GetWindowClass();
// Unregisters the window class. Should only be called if there are no
// instances of the window.
void UnregisterWindowClass();
private:
WindowClassRegistrar() = default;
static WindowClassRegistrar* instance_;
bool class_registered_ = false;
};
WindowClassRegistrar* WindowClassRegistrar::instance_ = nullptr;
const wchar_t* WindowClassRegistrar::GetWindowClass() {
if (!class_registered_) {
WNDCLASS window_class{};
window_class.hCursor = LoadCursor(nullptr, IDC_ARROW);
window_class.lpszClassName = kWindowClassName;
window_class.style = CS_HREDRAW | CS_VREDRAW;
window_class.cbClsExtra = 0;
window_class.cbWndExtra = 0;
window_class.hInstance = GetModuleHandle(nullptr);
window_class.hIcon =
LoadIcon(window_class.hInstance, MAKEINTRESOURCE(IDI_APP_ICON));
window_class.hbrBackground = 0;
window_class.lpszMenuName = nullptr;
window_class.lpfnWndProc = Win32Window::WndProc;
RegisterClass(&window_class);
class_registered_ = true;
}
return kWindowClassName;
}
void WindowClassRegistrar::UnregisterWindowClass() {
UnregisterClass(kWindowClassName, nullptr);
class_registered_ = false;
}
Win32Window::Win32Window() {
++g_active_window_count;
}
Win32Window::~Win32Window() {
--g_active_window_count;
Destroy();
}
bool Win32Window::CreateAndShow(const std::wstring& title,
const Point& origin,
const Size& size) {
Destroy();
const wchar_t* window_class =
WindowClassRegistrar::GetInstance()->GetWindowClass();
const POINT target_point = {static_cast<LONG>(origin.x),
static_cast<LONG>(origin.y)};
HMONITOR monitor = MonitorFromPoint(target_point, MONITOR_DEFAULTTONEAREST);
UINT dpi = FlutterDesktopGetDpiForMonitor(monitor);
double scale_factor = dpi / 96.0;
HWND window = CreateWindow(
window_class, title.c_str(), WS_OVERLAPPEDWINDOW | WS_VISIBLE,
Scale(origin.x, scale_factor), Scale(origin.y, scale_factor),
Scale(size.width, scale_factor), Scale(size.height, scale_factor),
nullptr, nullptr, GetModuleHandle(nullptr), this);
if (!window) {
return false;
}
return OnCreate();
}
// static
LRESULT CALLBACK Win32Window::WndProc(HWND const window,
UINT const message,
WPARAM const wparam,
LPARAM const lparam) noexcept {
if (message == WM_NCCREATE) {
auto window_struct = reinterpret_cast<CREATESTRUCT*>(lparam);
SetWindowLongPtr(window, GWLP_USERDATA,
reinterpret_cast<LONG_PTR>(window_struct->lpCreateParams));
auto that = static_cast<Win32Window*>(window_struct->lpCreateParams);
EnableFullDpiSupportIfAvailable(window);
that->window_handle_ = window;
} else if (Win32Window* that = GetThisFromHandle(window)) {
return that->MessageHandler(window, message, wparam, lparam);
}
return DefWindowProc(window, message, wparam, lparam);
}
LRESULT
Win32Window::MessageHandler(HWND hwnd,
UINT const message,
WPARAM const wparam,
LPARAM const lparam) noexcept {
switch (message) {
case WM_DESTROY:
window_handle_ = nullptr;
Destroy();
if (quit_on_close_) {
PostQuitMessage(0);
}
return 0;
case WM_DPICHANGED: {
auto newRectSize = reinterpret_cast<RECT*>(lparam);
LONG newWidth = newRectSize->right - newRectSize->left;
LONG newHeight = newRectSize->bottom - newRectSize->top;
SetWindowPos(hwnd, nullptr, newRectSize->left, newRectSize->top, newWidth,
newHeight, SWP_NOZORDER | SWP_NOACTIVATE);
return 0;
}
case WM_SIZE: {
RECT rect = GetClientArea();
if (child_content_ != nullptr) {
// Size and position the child window.
MoveWindow(child_content_, rect.left, rect.top, rect.right - rect.left,
rect.bottom - rect.top, TRUE);
}
return 0;
}
case WM_ACTIVATE:
if (child_content_ != nullptr) {
SetFocus(child_content_);
}
return 0;
}
return DefWindowProc(window_handle_, message, wparam, lparam);
}
void Win32Window::Destroy() {
OnDestroy();
if (window_handle_) {
DestroyWindow(window_handle_);
window_handle_ = nullptr;
}
if (g_active_window_count == 0) {
WindowClassRegistrar::GetInstance()->UnregisterWindowClass();
}
}
Win32Window* Win32Window::GetThisFromHandle(HWND const window) noexcept {
return reinterpret_cast<Win32Window*>(
GetWindowLongPtr(window, GWLP_USERDATA));
}
void Win32Window::SetChildContent(HWND content) {
child_content_ = content;
SetParent(content, window_handle_);
RECT frame = GetClientArea();
MoveWindow(content, frame.left, frame.top, frame.right - frame.left,
frame.bottom - frame.top, true);
SetFocus(child_content_);
}
RECT Win32Window::GetClientArea() {
RECT frame;
GetClientRect(window_handle_, &frame);
return frame;
}
HWND Win32Window::GetHandle() {
return window_handle_;
}
void Win32Window::SetQuitOnClose(bool quit_on_close) {
quit_on_close_ = quit_on_close;
}
bool Win32Window::OnCreate() {
// No-op; provided for subclasses.
return true;
}
void Win32Window::OnDestroy() {
// No-op; provided for subclasses.
}
#ifndef RUNNER_WIN32_WINDOW_H_
#define RUNNER_WIN32_WINDOW_H_
#include <windows.h>
#include <functional>
#include <memory>
#include <string>
// A class abstraction for a high DPI-aware Win32 Window. Intended to be
// inherited from by classes that wish to specialize with custom
// rendering and input handling
class Win32Window {
public:
struct Point {
unsigned int x;
unsigned int y;
Point(unsigned int x, unsigned int y) : x(x), y(y) {}
};
struct Size {
unsigned int width;
unsigned int height;
Size(unsigned int width, unsigned int height)
: width(width), height(height) {}
};
Win32Window();
virtual ~Win32Window();
// Creates and shows a win32 window with |title| and position and size using
// |origin| and |size|. New windows are created on the default monitor. Window
// sizes are specified to the OS in physical pixels, hence to ensure a
// consistent size to will treat the width height passed in to this function
// as logical pixels and scale to appropriate for the default monitor. Returns
// true if the window was created successfully.
bool CreateAndShow(const std::wstring& title,
const Point& origin,
const Size& size);
// Release OS resources associated with window.
void Destroy();
// Inserts |content| into the window tree.
void SetChildContent(HWND content);
// Returns the backing Window handle to enable clients to set icon and other
// window properties. Returns nullptr if the window has been destroyed.
HWND GetHandle();
// If true, closing this window will quit the application.
void SetQuitOnClose(bool quit_on_close);
// Return a RECT representing the bounds of the current client area.
RECT GetClientArea();
protected:
// Processes and route salient window messages for mouse handling,
// size change and DPI. Delegates handling of these to member overloads that
// inheriting classes can handle.
virtual LRESULT MessageHandler(HWND window,
UINT const message,
WPARAM const wparam,
LPARAM const lparam) noexcept;
// Called when CreateAndShow is called, allowing subclass window-related
// setup. Subclasses should return false if setup fails.
virtual bool OnCreate();
// Called when Destroy is called.
virtual void OnDestroy();
private:
friend class WindowClassRegistrar;
// OS callback called by message pump. Handles the WM_NCCREATE message which
// is passed when the non-client area is being created and enables automatic
// non-client DPI scaling so that the non-client area automatically
// responsponds to changes in DPI. All other messages are handled by
// MessageHandler.
static LRESULT CALLBACK WndProc(HWND const window,
UINT const message,
WPARAM const wparam,
LPARAM const lparam) noexcept;
// Retrieves a class instance pointer for |window|
static Win32Window* GetThisFromHandle(HWND const window) noexcept;
bool quit_on_close_ = false;
// window handle for top level window.
HWND window_handle_ = nullptr;
// window handle for hosted content.
HWND child_content_ = nullptr;
};
#endif // RUNNER_WIN32_WINDOW_H_
name: permission_handler_windows
description: Permission plugin for Flutter. This plugin provides the Windows API to request and check permissions.
version: 0.2.1
homepage: https://github.com/baseflow/flutter-permission-handler
flutter:
plugin:
implements: permission_handler
platforms:
windows:
pluginClass: PermissionHandlerWindowsPlugin
dependencies:
flutter:
sdk: flutter
permission_handler_platform_interface: ^4.1.0
dev_dependencies:
flutter_test:
sdk: flutter
plugin_platform_interface: ^2.0.0
environment:
sdk: ">=2.12.0 <4.0.0"
flutter: ">=2.0.0"
flutter/
# Visual Studio user-specific files.
*.suo
*.user
*.userosscache
*.sln.docstates
# Visual Studio build-related files.
x64/
x86/
# Visual Studio cache files
# files ending in .cache can be ignored
*.[Cc]ache
# but keep track of directories ending in .cache
!*.[Cc]ache/
cmake_minimum_required(VERSION 3.15)
set(PROJECT_NAME "permission_handler_windows")
set(CPPWINRT_VERSION "2.0.210806.1")
project(${PROJECT_NAME} LANGUAGES CXX)
include(FetchContent)
# This value is used when generating builds using this plugin, so it must
# not be changed
set(PLUGIN_NAME "${PROJECT_NAME}_plugin")
FetchContent_Declare(nuget
URL "https://dist.nuget.org/win-x86-commandline/v6.0.0/nuget.exe"
URL_HASH SHA256=04eb6c4fe4213907e2773e1be1bbbd730e9a655a3c9c58387ce8d4a714a5b9e1
DOWNLOAD_NO_EXTRACT true
)
find_program(NUGET nuget)
if (NOT NUGET)
message("Nuget.exe not found, trying to download or use cached version.")
FetchContent_MakeAvailable(nuget)
set(NUGET ${nuget_SOURCE_DIR}/nuget.exe)
endif()
execute_process(COMMAND
${NUGET} install Microsoft.Windows.CppWinRT -Version ${CPPWINRT_VERSION} -OutputDirectory packages
WORKING_DIRECTORY ${CMAKE_BINARY_DIR}
RESULT_VARIABLE ret)
if (NOT ret EQUAL 0)
message(FATAL_ERROR "Failed to install nuget package Microsoft.Windows.CppWinRT.${CPPWINRT_VERSION}")
endif()
set(CPPWINRT ${CMAKE_BINARY_DIR}/packages/Microsoft.Windows.CppWinRT.${CPPWINRT_VERSION}/bin/cppwinrt.exe)
execute_process(COMMAND
${CPPWINRT} -input sdk -output include
WORKING_DIRECTORY ${CMAKE_BINARY_DIR}
RESULT_VARIABLE ret)
if (NOT ret EQUAL 0)
message(FATAL_ERROR "Failed to run cppwinrt.exe")
endif()
include_directories(BEFORE SYSTEM ${CMAKE_BINARY_DIR}/include)
add_library(${PLUGIN_NAME} SHARED
"include/permission_handler_windows/permission_handler_windows_plugin.h"
"permission_handler_windows_plugin.cpp"
)
apply_standard_settings(${PLUGIN_NAME})
set_target_properties(${PLUGIN_NAME} PROPERTIES CXX_VISIBILITY_PRESET hidden)
target_compile_features(${PLUGIN_NAME} PRIVATE cxx_std_20)
target_compile_options(${PLUGIN_NAME} PRIVATE /await)
target_compile_definitions(${PLUGIN_NAME} PRIVATE FLUTTER_PLUGIN_IMPL)
target_include_directories(${PLUGIN_NAME} INTERFACE
"${CMAKE_CURRENT_SOURCE_DIR}/include")
target_link_libraries(${PLUGIN_NAME} PRIVATE flutter flutter_wrapper_plugin)
# List of absolute paths to libraries that should be bundled with the plugin
set(permission_handler_windows_bundled_libraries
""
PARENT_SCOPE
)
#ifndef PACKAGES_PERMISSION_HANDLER_PERMISSION_HANDLER_WINDOWS_WINDOWS_INCLUDE_PERMISSION_HANDLER_WINDOWS_PERMISSION_HANDLER_PLUGIN_H_
#define PACKAGES_PERMISSION_HANDLER_PERMISSION_HANDLER_WINDOWS_WINDOWS_INCLUDE_PERMISSION_HANDLER_WINDOWS_PERMISSION_HANDLER_PLUGIN_H_
#include <flutter_plugin_registrar.h>
#ifdef FLUTTER_PLUGIN_IMPL
#define FLUTTER_PLUGIN_EXPORT __declspec(dllexport)
#else
#define FLUTTER_PLUGIN_EXPORT __declspec(dllimport)
#endif
#if defined(__cplusplus)
extern "C" {
#endif
FLUTTER_PLUGIN_EXPORT void PermissionHandlerWindowsPluginRegisterWithRegistrar(
FlutterDesktopPluginRegistrarRef registrar);
#if defined(__cplusplus)
} // extern "C"
#endif
#endif // PACKAGES_PERMISSION_HANDLER_PERMISSION_HANDLER_WINDOWS_WINDOWS_INCLUDE_PERMISSION_HANDLER_WINDOWS_PERMISSION_HANDLER_PLUGIN_H_
#include <string>
class PermissionConstants {
public:
inline static int PERMISSION_CODE = 24;
inline static int PERMISSION_CODE_IGNORE_BATTERY_OPTIMIZATIONS = 209;
inline static int PERMISSION_CODE_MANAGE_EXTERNAL_STORAGE = 210;
inline static int PERMISSION_CODE_SYSTEM_ALERT_WINDOW = 211;
inline static int PERMISSION_CODE_REQUEST_INSTALL_PACKAGES = 212;
inline static int PERMISSION_CODE_ACCESS_NOTIFICATION_POLICY = 213;
//PERMISSION_GROUP
enum class PermissionGroup {
CALENDAR = 0,
CAMERA = 1,
CONTACTS = 2,
LOCATION = 3,
LOCATION_ALWAYS = 4,
LOCATION_WHEN_IN_USE = 5,
MEDIA_LIBRARY = 6,
MICROPHONE = 7,
PHONE = 8,
PHOTOS = 9,
PHOTOS_ADD_ONLY = 10,
REMINDERS = 11,
SENSORS = 12,
SMS = 13,
SPEECH = 14,
STORAGE = 15,
IGNORE_BATTERY_OPTIMIZATIONS = 16,
NOTIFICATION = 17,
ACCESS_MEDIA_LOCATION = 18,
ACTIVITY_RECOGNITION = 19,
UNKNOWN = 20,
BLUETOOTH = 21,
MANAGE_EXTERNAL_STORAGE = 22,
SYSTEM_ALERT_WINDOW = 23,
REQUEST_INSTALL_PACKAGES = 24,
APP_TRACK_TRANSPARENCY = 25,
CRITICAL_ALERTS = 26,
ACCESS_NOTIFICATION_POLICY = 27,
BLUETOOTH_SCAN = 28,
BLUETOOTH_ADVERTISE = 29,
BLUETOOTH_CONNECT = 30,
NEARBY_WIFI_DEVICES = 31,
VIDEOS = 32,
AUDIO = 33,
SCHEDULE_EXACT_ALARM = 34,
SENSORS_ALWAYS = 35,
CALENDAR_WRITE_ONLY = 36,
CALENDAR_FULL_ACCESS = 37,
ASSISTANT = 38,
BACKGROUND_REFRESH = 39
};
//PERMISSION_STATUS
enum class PermissionStatus {
DENIED = 0,
GRANTED = 1,
RESTRICTED = 2,
LIMITED = 3,
NEVER_ASK_AGAIN = 4
};
//SERVICE_STATUS
enum class ServiceStatus {
DISABLED = 0,
ENABLED = 1,
NOT_APPLICABLE = 2
};
};
#include "include/permission_handler_windows/permission_handler_windows_plugin.h"
#include <flutter/method_channel.h>
#include <flutter/plugin_registrar_windows.h>
#include <flutter/standard_method_codec.h>
#include <flutter/event_channel.h>
#include <flutter/event_stream_handler.h>
#include <flutter/event_stream_handler_functions.h>
#include <flutter/encodable_value.h>
#include <windows.h>
#include <memory>
#include <optional>
#include <sstream>
#include <map>
#include <string>
#include <variant>
#include <winrt/Windows.Foundation.h>
#include <winrt/Windows.Devices.Geolocation.h>
#include <winrt/Windows.Devices.Bluetooth.h>
#include <winrt/Windows.Devices.Radios.h>
#include <winrt/Windows.Foundation.Collections.h>
#include "permission_constants.h"
namespace {
using namespace flutter;
using namespace winrt;
using namespace winrt::Windows::Devices::Geolocation;
using namespace winrt::Windows::Devices::Bluetooth;
using namespace winrt::Windows::Devices::Radios;
template<typename T>
T GetArgument(const std::string arg, const EncodableValue* args, T fallback) {
T result {fallback};
const auto* arguments = std::get_if<EncodableMap>(args);
if (arguments) {
auto result_it = arguments->find(EncodableValue(arg));
if (result_it != arguments->end()) {
result = std::get<T>(result_it->second);
}
}
return result;
}
class PermissionHandlerWindowsPlugin : public Plugin {
public:
static void RegisterWithRegistrar(PluginRegistrar* registrar);
PermissionHandlerWindowsPlugin();
virtual ~PermissionHandlerWindowsPlugin();
// Disallow copy and move.
PermissionHandlerWindowsPlugin(const PermissionHandlerWindowsPlugin&) = delete;
PermissionHandlerWindowsPlugin& operator=(const PermissionHandlerWindowsPlugin&) = delete;
// Called when a method is called on the plugin channel.
void HandleMethodCall(const MethodCall<>&,
std::unique_ptr<MethodResult<>>);
private:
void IsLocationServiceEnabled(std::unique_ptr<MethodResult<>> result);
winrt::fire_and_forget IsBluetoothServiceEnabled(std::unique_ptr<MethodResult<>> result);
winrt::Windows::Devices::Geolocation::Geolocator geolocator;
winrt::Windows::Devices::Geolocation::Geolocator::PositionChanged_revoker m_positionChangedRevoker;
};
// static
void PermissionHandlerWindowsPlugin::RegisterWithRegistrar(
PluginRegistrar* registrar) {
auto channel = std::make_unique<MethodChannel<>>(
registrar->messenger(), "flutter.baseflow.com/permissions/methods",
&StandardMethodCodec::GetInstance());
std::unique_ptr<PermissionHandlerWindowsPlugin> plugin = std::make_unique<PermissionHandlerWindowsPlugin>();
channel->SetMethodCallHandler(
[plugin_pointer = plugin.get()](const auto& call, auto result) {
plugin_pointer->HandleMethodCall(call, std::move(result));
});
registrar->AddPlugin(std::move(plugin));
}
PermissionHandlerWindowsPlugin::PermissionHandlerWindowsPlugin(){
m_positionChangedRevoker = geolocator.PositionChanged(winrt::auto_revoke,
[this](Geolocator const& geolocator, PositionChangedEventArgs e)
{
});
}
PermissionHandlerWindowsPlugin::~PermissionHandlerWindowsPlugin() = default;
void PermissionHandlerWindowsPlugin::HandleMethodCall(
const MethodCall<>& method_call,
std::unique_ptr<MethodResult<>> result) {
auto methodName = method_call.method_name();
if (methodName.compare("checkServiceStatus") == 0) {
auto permission = (PermissionConstants::PermissionGroup)std::get<int>(*method_call.arguments());
if (permission == PermissionConstants::PermissionGroup::LOCATION ||
permission == PermissionConstants::PermissionGroup::LOCATION_ALWAYS ||
permission == PermissionConstants::PermissionGroup::LOCATION_WHEN_IN_USE) {
IsLocationServiceEnabled(std::move(result));
return;
}
if(permission == PermissionConstants::PermissionGroup::BLUETOOTH){
IsBluetoothServiceEnabled(std::move(result));
return;
}
if (permission == PermissionConstants::PermissionGroup::IGNORE_BATTERY_OPTIMIZATIONS) {
result->Success(EncodableValue((int)PermissionConstants::ServiceStatus::ENABLED));
return;
}
result->Success(EncodableValue((int)PermissionConstants::ServiceStatus::NOT_APPLICABLE));
} else if (methodName.compare("checkPermissionStatus") == 0) {
result->Success(EncodableValue((int)PermissionConstants::PermissionStatus::GRANTED));
} else if (methodName.compare("requestPermissions") == 0) {
auto permissionsEncoded = std::get<EncodableList>(*method_call.arguments());
std::vector<int> permissions;
permissions.reserve( permissionsEncoded.size() );
std::transform( permissionsEncoded.begin(), permissionsEncoded.end(),
std::back_inserter( permissions ),
[](const EncodableValue& encoded) {
return std::get<int>(encoded);
});
EncodableMap requestResults;
for (int i=0;i<permissions.size();i++) {
auto permissionStatus = PermissionConstants::PermissionStatus::GRANTED;
requestResults.insert({EncodableValue(permissions[i]), EncodableValue((int)permissionStatus)});
}
result->Success(requestResults);
} else if (methodName.compare("shouldShowRequestPermissionRationale") == 0
|| methodName.compare("openAppSettings")) {
result->Success(EncodableValue(false));
} else {
result->NotImplemented();
}
}
void PermissionHandlerWindowsPlugin::IsLocationServiceEnabled(std::unique_ptr<MethodResult<>> result) {
result->Success(EncodableValue((int)(geolocator.LocationStatus() != PositionStatus::NotAvailable
? PermissionConstants::ServiceStatus::ENABLED
: PermissionConstants::ServiceStatus::DISABLED)));
}
winrt::fire_and_forget PermissionHandlerWindowsPlugin::IsBluetoothServiceEnabled(std::unique_ptr<MethodResult<>> result) {
auto btAdapter = co_await BluetoothAdapter::GetDefaultAsync();
if (btAdapter == nullptr) {
result->Success(EncodableValue((int)PermissionConstants::ServiceStatus::DISABLED));
co_return;
}
if (!btAdapter.IsCentralRoleSupported()) {
result->Success(EncodableValue((int)PermissionConstants::ServiceStatus::DISABLED));
co_return;
}
auto radios = co_await Radio::GetRadiosAsync();
for (uint32_t i=0; i<radios.Size(); i++) {
auto radio = radios.GetAt(i);
if(radio.Kind() == RadioKind::Bluetooth) {
co_await radio.SetStateAsync(RadioState::On);
result->Success(EncodableValue((int)(radio.State() == RadioState::On
? PermissionConstants::ServiceStatus::ENABLED
: PermissionConstants::ServiceStatus::DISABLED)));
co_return;
}
}
result->Success(EncodableValue((int)PermissionConstants::ServiceStatus::DISABLED));
}
} // namespace
void PermissionHandlerWindowsPluginRegisterWithRegistrar(
FlutterDesktopPluginRegistrarRef registrar) {
PermissionHandlerWindowsPlugin::RegisterWithRegistrar(
PluginRegistrarManager::GetInstance()
->GetRegistrar<PluginRegistrarWindows>(registrar));
}
Markdown is supported
0% or
You are about to add 0 people to the discussion. Proceed with caution.
Finish editing this message first!
Please register or to comment