Commit b5c32ffe by songyanzhi

feat:merge

parents a273f694 0044cf27
# 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
github: Baseflow
custom: https://baseflow.com/contact
---
name: 🔙 Regression
about: Report unexpected behavior that worked previously
---
## 🔙 Regression
<!--- Summary description of the regression --->
### Old (and correct) behavior
### Current behavior
### Reproduction steps
### Configuration
**Version:** 1.x
**Platform:**
- [ ] :iphone: iOS
- [ ] :robot: Android
\ No newline at end of file
---
name: 🐛 Bug Report
about: Create a report to help us fix bugs and make improvements
---
## 🐛 Bug Report
<!--- Summary description of the bug --->
### Expected behavior
### Reproduction steps
### Configuration
**Version:** 1.x
**Platform:**
- [ ] :iphone: iOS
- [ ] :robot: Android
\ No newline at end of file
---
name: 🚀 Feature Request
about: Want to see something new included in the Framework? Submit it!
---
## 🚀 Feature Requests
<!--- Summary description of the feature --->
### Contextualize the feature
<!--- Where does it fit in the framework and why it's being included there. --->
### Describe the feature
<!--- Use as much detail as possible here! --->
### Platforms affected (mark all that apply)
- [ ] :iphone: iOS
- [ ] :robot: Android
\ No newline at end of file
---
name: 🏗 Enhancement Proposal
about: Proposals for code cleanup, refactor and improvements in general
---
## 🏗 Enhancement Proposal
<!--- A clear and concise description for your idea --->
### Pitch
<!--- How will this refactor improve contributors' lives? Input as many details as possible! --->
### Platforms affected (mark all that apply)
- [ ] :iphone: iOS
- [ ] :robot: Android
\ No newline at end of file
---
name: 💬 Questions and Help
about: If you have questions, please use this for support
---
## 💬 Questions and Help
For questions or help we recommend checking:
- The [Flutter tag in Stack Overflow](https://stackoverflow.com/questions/tagged/flutter)
\ No newline at end of file
### :sparkles: What kind of change does this PR introduce? (Bug fix, feature, docs update...)
### :arrow_heading_down: What is the current behavior?
### :new: What is the new behavior (if this is a feature change)?
### :boom: Does this PR introduce a breaking change?
### :bug: Recommendations for testing
### :memo: Links to relevant issues/docs
### :thinking: Checklist before submitting
- [ ] I made sure all projects build.
- [ ] I updated pubspec.yaml with an appropriate new version according to the [pub versioning philosophy](https://dart.dev/tools/pub/versioning).
- [ ] I updated CHANGELOG.md to add a description of the change.
- [ ] I followed the style guide lines ([code style guide](https://github.com/Baseflow/flutter-permission-handler/blob/master/CONTRIBUTING.md)).
- [ ] I updated the relevant documentation.
- [ ] I rebased onto current `master`.
# Configuration for probot-no-response - https://github.com/probot/no-response
# Number of days of inactivity before an Issue is closed for lack of response
daysUntilClose: 14
# Label requiring a response
responseRequiredLabel: "status: needs more info"
# Comment to post when closing an Issue for lack of response. Set to `false` to disable
closeComment: >
This issue has been automatically closed because there has been no response
to our request for more information from the original author. With only the
information that is currently in the issue, we don't have enough information
to take action. Please reach out if you have or find the answers we need so
that we can investigate further.
# This is a basic workflow to help you get started with Actions
name: app_facing_package
# Controls when the action will run. Triggers the workflow on push or pull request
# events but only for the develop branch
on:
push:
branches: [ master ]
paths:
- 'permission_handler/**'
pull_request:
branches: [ master ]
paths:
- 'permission_handler/**'
# A workflow run is made up of one or more jobs that can run sequentially or in parallel
jobs:
# Job configuration for the permission_handler (App Facing Package)
permission_handler:
# The type of runner that the job will run on
runs-on: macos-latest
env:
source-directory: ./permission_handler
example-directory: ./permission_handler/example
# Steps represent a sequence of tasks that will be executed as part of the job
steps:
# Checks-out your repository under $GITHUB_WORKSPACE, so your job can access it
- uses: actions/checkout@v2
# Make sure the stable version of Flutter is available
- uses: subosito/flutter-action@v1
with:
channel: 'stable'
# Download all Flutter packages the permission_handler depends on
- name: Download dependencies
run: flutter pub get
working-directory: ${{env.source-directory}}
# Run Flutter Format to ensure formatting is valid
- name: Run Flutter Format
run: flutter format --set-exit-if-changed lib
working-directory: ${{env.source-directory}}
# Run Flutter Analyzer
- name: Run Flutter Analyzer
run: flutter analyze
working-directory: ${{env.source-directory}}
# Build Android version of the example app
- name: Run Android build
run: flutter build apk --release
working-directory: ${{env.example-directory}}
# Build iOS version of the example app
- name: Run iOS build
run: flutter build ios --release --no-codesign
working-directory: ${{env.example-directory}}
# Run all unit-tests with code coverage
- name: Run unit tests
run: flutter test --coverage
working-directory: ${{env.source-directory}}
# Upload code coverage information
- uses: codecov/codecov-action@v1
with:
file: ${{env.source-directory}}/coverage/lcov.info # optional
name: permission_handler (Platform Interface Package) # optional
fail_ci_if_error: true
# This is a basic workflow to help you get started with Actions
name: platform_interface_package
# Controls when the action will run. Triggers the workflow on push or pull request
# events but only for the develop branch
on:
push:
branches: [ master ]
paths:
- 'permission_handler_platform_interface/**'
pull_request:
branches: [ master ]
paths:
- 'permission_handler_platform_interface/**'
# A workflow run is made up of one or more jobs that can run sequentially or in parallel
jobs:
# Job configuration for the permission_handler_platform_interface (Platform Interface Package)
permission_handler_platform_interface:
# The type of runner that the job will run on
runs-on: macos-latest
env:
source-directory: ./permission_handler_platform_interface
# Steps represent a sequence of tasks that will be executed as part of the job
steps:
# Checks-out your repository under $GITHUB_WORKSPACE, so your job can access it
- uses: actions/checkout@v2
# Make sure the stable version of Flutter is available
- uses: subosito/flutter-action@v1
with:
channel: 'stable'
# Download all Flutter packages the permission_handler_platform_interface depends on
- name: Download dependencies
run: flutter pub get
working-directory: ${{env.source-directory}}
# Run Flutter Format to ensure formatting is valid
- name: Run Flutter Format
run: flutter format --set-exit-if-changed lib
working-directory: ${{env.source-directory}}
# Run Flutter Analyzer
- name: Run Flutter Analyzer
run: flutter analyze
working-directory: ${{env.source-directory}}
# Run all unit-tests with code coverage
- name: Run unit tests
run: flutter test --coverage
working-directory: ${{env.source-directory}}
# Upload code coverage information
- uses: codecov/codecov-action@v1
with:
file: ${{env.source-directory}}/coverage/lcov.info # optional
name: permission_handler (Platform Interface Package) # optional
fail_ci_if_error: true
# Miscellaneous
*.class
*.lock
*.log
*.pyc
*.swp
.DS_Store
.atom/
.buildlog/
.history
.project
.svn/
bin/
# 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
**/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 making participation 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 a physical or electronic
address, without explicit permission
* Other conduct which 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 project spaces and in public spaces
when an individual is representing 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.
Further details of specific enforcement policies may be posted 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 instruction 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 you 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 fetch 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
Copyright (c) 2020 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.
# Flutter permission_handler plugin
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:
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)".
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 int the [README.md][4] of the `permission_handler_platform_interface` package.
[1]: ./permission_handler
[2]: ./permission_handler/README.md
[3]: ./permission_handler_platform_interface
[4]: ./permission_handler_platform_interface/README.md
include: package:effective_dart/analysis_options.1.2.0.yaml
linter:
rules:
- public_member_api_docs
## 7.1.0
* Added support for the "SYSTEM_ALERT_WINDOW" permission on Android.
## 7.0.0
This release contains the following **breaking changes**:
* Updated compile SDK version to 30 in the build.gradle for handling the MANAGE_EXTERNAL_STORAGE permission;
* Added the MANAGE_EXTERNAL_STORAGE permission for Android R and up;
* Registered listeners on the plugin level to prevent memory leaks or unwanted behaviour.
## 6.1.3
* Implement equality operator on the `Permission` class;
* Updated the README.md with instructions on enabling/ disabling the bluetooth permissions on iOS;
* Corrected some spelling mistakes in the `CHANGELOG.md`.
## 6.1.2
* Correctly handle the ACCESS_MEDIA_LOCATION and ACCESS_ACTIVITY_RECOGNITION permissions on pre Android Q devices (permissions should be implicitly granted on pre Android Q).
## 6.1.1
* Added unit-tests to guard API against breaking changes.
## 6.1.0
* Added support for bluetooth permissions;
* Workaround for ignore battery optimizations on pre-M Android devices (see PR [#376](https://github.com/Baseflow/flutter-permission-handler/pull/376)).
## 6.0.1+1
* Fixed content of the README.md file.
## 6.0.1
* Fixed deprecation warning when building Android project.
## 6.0.0
This release includes the following **breaking changes**:
* Migrated to null safety
* Removed PermissionStatus.undetermined, PermissionStatus.denied will be used instead (see our "[Changes in 6.0.0](https://github.com/Baseflow/flutter-permission-handler/wiki/Changes-in-6.0.0)" wiki page for more details).
## 5.1.0+2
* Solve mismatch with permission constants between Dart and Android (due to addition of permission on iOS);
* Fix compile error which occurred when on iOS the "PERMISSION_PHOTOS" macro is deactivated (meaning code dealing with the `PHPhotoLibrary` library is removed from the code base).
## 5.1.0+1
* Recreate the iOS part of the example project based on the Flutter stable channel (previous version was accidentally created with the Flutter beta channel).
## 5.1.0
* Added support for the limited photos permission available on iOS 14 and up;
* Fixed deprecated warning on iOS;
* Added support for the "READ_PHONE_NUMBERS" permission on Android;
* Fix a link to the contribution guide in the README.md.
## 5.0.1+2
* Pin dependency on permission_handler_platform_interface on version 2.0.1.
## 5.0.1+1
* Fixes Typo
* Issue #233 - on 5.0: Solved a bug that prevented Android applications running in the background to check the permission status.
## 5.0.1
* Update `permission_handler_platform_interface 2.0.1`
## 5.0.0+hotfix.10
* Revert pull-request [#317](https://github.com/Baseflow/flutter-permission-handler/pull/317)
## 5.0.0+hotfix.9
* Solved an issue where kCLAuthorizationStatusAuthorizedWhenInUse was returning PermissionStatusDenied (see [#317](https://github.com/Baseflow/flutter-permission-handler/pull/317))
## 5.0.0+hotfix.8
* Solved an issue on iOS where requesting notification permissions returned prematurely (see pull-request [#297](https://github.com/Baseflow/flutter-permission-handler/pull/297))
## 5.0.0+hotfix.7
* ** Mistake release please don't use this version **
## 5.0.0+hotfix.6
* Solved an issue on iOS where requesting notification permissions always resulted in a "granted" result (see pull-request [#289](https://github.com/Baseflow/flutter-permission-handler/pull/289))
## 5.0.0+hotfix.5
* Remove use of the deprecated pre iOS 8 API causing users compile issues (see issue [#277](https://github.com/Baseflow/flutter-permission-handler/issues/277)).
## 5.0.0+hotfix.4
* Solve issue on Android causing an IllegalStateException ([#267](https://github.com/Baseflow/flutter-permission-handler/issues/267)).
## 5.0.0+hotfix.3
* Includes the changes of 4.4.0+hotfix.4 (which was released to be backwards compatible).
## 5.0.0+hotfix.2
* Removed some residual usages of the `PermissionStatusUnknown` constants in #ifdef statements that were not found by the compiler.
## 5.0.0+hotfix.1
* Make sure all enums from `permission_handler_platform_interface: 2.0.0` are exposed through the `permission_handler`.
## 5.0.0
* **BREAKING**: Implemented more intuitive API exposed by `permission_handler_platform_interface: 2.0.0` ([#230](https://github.com/Baseflow/flutter-permission-handler/issues/230)).
## 4.4.0+hotfix.4
* Android: solved issue where `permission_handler` is used in a service (see [#251](https://github.com/Baseflow/flutter-permission-handler/issues/251))
## 4.4.0+hotfix.3
IGNORE THIS VERSION, it was released by accident and contains the same code as 4.4.0+hotfix.2
## 4.4.0+hotfix.2
* Issue #235: Solved a bug which made it impossible to request service status on Android 7;
* Issue #237: Solved a bug which crashes the application when cancelling the "Ignore battery optimizations" request for permissions.
## 4.4.0+hotfix.1
* Issue #233: Solved a bug that prevented Android applications running in the background to check the permission status.
## 4.4.0
* Updated plugin structure to confirm to the Flutter federated plugin architecture. This will make it easier to add new platform implementations (see: https://medium.com/flutter/how-to-write-a-flutter-web-plugin-part-2-afdddb69ece6);
* Android: Migrate to FlutterPlugin Android API (better support for Add-to-App);
* Android: Suppress JAVA warnings which are generated to old platform code (only executes on older platforms);
* Android: Fixed issue which sometimes resulting in illegal cast exception.
## 4.3.0
* Allow requesting location permissions when location services are disabled (on iOS this will redirect the user to the Location settings page);
* Android: Add support for requesting Activity Recognition permissions;
* Confirm to Effective Dart guidelines;
* Documented all public API members;
* Fixed several typos in the README.md.
## 4.2.0+hotfix.3
* Android: Fixes a bug which in some cases caused the permission `neverAskAgain` to be returned incorrectly.
## 4.2.0+hotfix.2
* Android: Fixes a bug where permissions are reported as `neverAskAgain` incorrectly after calling `requestPermissions` method.
## 4.2.0+hotfix.1
* Android: Fixes a bug where permissions are reported as `neverAskAgain` incorrectly.
## 4.2.0
* Android: Methods `checkPermissionStatus` and `requestPermissions` now support addition `neverAskAgain` status.
## 4.1.0
* iOS: Added option to exclude permissions logic using macros. This allows developers to submit their app to the AppStore without having to include all permissions in their Info.plist;
* Android: Support ANSWER_PHONE_CALLS permission for API 26 and higher;
* Android: Support ACCESS_MEDIA_LOCATION permission for API 26 and higher;
* Android: Synchronized Gradle version with Flutter stable (1.12.13+hotfix.5).
## 4.0.0
* iOS: Added support for requesting permissions on the DOCUMENTS and DOWNLOADS folder (thanks to @phranck);
* Android: Fix the PROCESS_OUTGOING_CALLS permissions which have been deprecated in API 29.
## 3.3.0
* Android: Add support for requesting the background location permission within the `locationAlways` group.
* Android: Update AGP, Gradle and AndroidX dependencies
## 3.2.2
* Fixed problem with dependency on specific version of gradle wrapper on Android.
## 3.2.1+1
* Reverted the update of the 'meta' plugin since Flutter SDK depends on version 1.1.6
## 3.2.1
* Updated dependency on 'meta' to latest version.
## 3.2.0
* Add support for Androids' "ignore battery optimizations" permission;
* Improve error logging;
* Documented support for AndroidX.
## 3.1.0
* Support service status inquiry for phone permission on iOS & Android.
## 3.0.2
* Fixed bug when rapidly requesting permissions (#23);
* Rename Enums.h to PermissionHandlerEnums.h to prevent conflicts with geolocator (#104);
* Update the Android permission request code to prevent conflicts with geolocator (#111);
* Update Gradle infrastructure.
## 3.0.1
* Mark the Swift pod as static
## 3.0.0
* Converted the iOS version from Swift to Objective-C, reducing the size of the final binary considerably.
## 2.2.0
* Added new method `checkServiceStatus` to allow users to check if the location services (on Android and iOS) and motion services (iOS only) are enabled;
* When checking permission status (using `checkPermissionStatus`) return `PermissionStatus.disabled` when permissions are granted or denied and the location services (on Android and iOS) or the motion services (iOS only) are disabled.
## 2.1.3
* Fixed bug on iOS where result of the `openAppSettings` call always returned `false`;
* Upgrade Android plugin to support AndroidX and latest Gradle and Kotlin versions;
* Added Swift version number to the Podfile of the plugin;
* Updated flutter static analyzes to conform to latest recommendations.
## 2.1.2
* Make sure the Permission Handler compiles with latest iOS SDK
## 2.1.1
* Update to the latest version of Swift (4.2);
* Make sure that the correct Swift version is set in the `Podfile` of consuming Apps;
* Updated configuration for static code analyses, so it complies with the Flutter recommendations.
## 2.1.0
* Added Android support to check if location services are enabled. If location services are not running the permission check returns `PermissionStatus.DISABLED`.
## 2.0.1
* Fix bug with dependency on `com.android.support:support-compat` library
* Update used Kotlin and Gradle versions
## 2.0.0
* Make methods non static so users can create an instance or override
## 1.0.1
* Converted the plugin into a library so that developers don't have to import additional files;
* Updated the README.md to fix example code.
## 1.0.0
* Initial 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.
[![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/app_facing_package.yaml/badge.svg?branch=master)](https://github.com/Baseflow/flutter-permission-handler/actions/workflows/app_facing_package.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 permissions 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 a permission.
On Android, you can show a rationale for requesting a permission.
## 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</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 behaviour. Most common known error is the permission_handler not returning after calling the `.request()` method on a 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:
```
android.useAndroidX=true
android.enableJetifier=true
```
2. Make sure you set the `compileSdkVersion` in your "android/app/build.gradle" file to 28:
```
android {
compileSdkVersion 28
...
}
```
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's a `debug`, `main` and `profile` version 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/develop/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</summary>
Add permission to your `Info.plist` file.
[Here](https://github.com/Baseflow/flutter-permission-handler/blob/develop/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 analyser (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/BaseflowIT/flutter-permission-handler/issues/26).
The <kbd>permission_handler</kbd> plugin use [macros](https://github.com/BaseflowIT/flutter-permission-handler/blob/develop/permission_handler/ios/Classes/PermissionHandlerEnums.h) to control whether a permission is supported.
You can remove permissions you don't use:
1. Add the following to your `Podfile` file:
```ruby
post_install do |installer|
installer.pods_project.targets.each do |target|
target.build_configurations.each do |config|
... # Here are some configurations automatically generated by flutter
# You can remove unused permissions here
# for more infomation: https://github.com/BaseflowIT/flutter-permission-handler/blob/develop/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=0',
## dart: PermissionGroup.reminders
# 'PERMISSION_REMINDERS=0',
## dart: PermissionGroup.contacts
# 'PERMISSION_CONTACTS=0',
## dart: PermissionGroup.camera
# 'PERMISSION_CAMERA=0',
## dart: PermissionGroup.microphone
# 'PERMISSION_MICROPHONE=0',
## dart: PermissionGroup.speech
# 'PERMISSION_SPEECH_RECOGNIZER=0',
## dart: PermissionGroup.photos
# 'PERMISSION_PHOTOS=0',
## dart: [PermissionGroup.location, PermissionGroup.locationAlways, PermissionGroup.locationWhenInUse]
# 'PERMISSION_LOCATION=0',
## dart: PermissionGroup.notification
# 'PERMISSION_NOTIFICATIONS=0',
## dart: PermissionGroup.mediaLibrary
# 'PERMISSION_MEDIA_LIBRARY=0',
## dart: PermissionGroup.sensors
# 'PERMISSION_SENSORS=0',
## dart: PermissionGroup.bluetooth
# 'PERMISSION_BLUETOOTH=0'
]
end
end
end
```
2. Remove the `#` character in front of the permission you do not want to use. For example if you don't need access to the calendar make sure the code looks like this:
```ruby
## dart: PermissionGroup.calendar
'PERMISSION_EVENTS=0',
```
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 | NSCalendarsUsageDescription | PERMISSION_EVENTS |
| 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.location, PermissionGroup.locationAlways, PermissionGroup.locationWhenInUse | NSLocationUsageDescription, NSLocationAlwaysAndWhenInUseUsageDescription, NSLocationWhenInUseUsageDescription | PERMISSION_LOCATION |
| PermissionGroup.notification | PermissionGroupNotification | PERMISSION_NOTIFICATIONS |
| PermissionGroup.mediaLibrary | NSAppleMusicUsageDescription, kTCCServiceMediaLibrary | PERMISSION_MEDIA_LIBRARY |
| PermissionGroup.sensors | NSMotionUsageDescription | PERMISSION_SENSORS |
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` or `permanentlyDenied`.
```dart
var status = await Permission.camera.status;
if (status.denied) {
// We didn't ask for permission yet or the permission has been denied before but not permanently.
}
// You can can also directly ask the permission about its status.
if (await Permission.location.isRestricted) {
// The OS restricts access, for example because of parental controls.
}
```
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 enable it in the system settings.
openAppSettings();
}
```
On Android, you can show a rationale for using a permission:
```dart
bool isShown = await Permission.contacts.shouldShowRequestRationale;
```
## Issues
Please file any issues, bugs or feature request 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>
<?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-1.8/"/>
<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
connection.project.dir=../example/android
eclipse.preferences.version=1
group 'com.baseflow.permissionhandler'
version '1.0-SNAPSHOT'
def args = ["-Xlint:deprecation","-Xlint:unchecked","-Werror"]
buildscript {
repositories {
google()
jcenter()
maven { url 'https://maven.google.com' }
}
dependencies {
classpath 'com.android.tools.build:gradle:3.5.0'
}
}
rootProject.allprojects {
repositories {
google()
jcenter()
}
}
project.getTasks().withType(JavaCompile){
options.compilerArgs.addAll(args)
}
apply plugin: 'com.android.library'
android {
compileSdkVersion 30
defaultConfig {
minSdkVersion 16
testInstrumentationRunner "androidx.test.runner.AndroidJUnitRunner"
}
lintOptions {
disable 'InvalidPackage'
}
compileOptions {
sourceCompatibility = '1.8'
targetCompatibility = '1.8'
}
}
dependencies {
implementation 'androidx.annotation:annotation:1.1.0'
implementation 'androidx.core:core:1.1.0'
}
repositories {
google()
}
\ No newline at end of file
rootProject.name = 'permission_handler'
<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.app.Activity;
import android.content.Context;
import androidx.annotation.NonNull;
import androidx.annotation.Nullable;
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;
}
@Nullable
private Activity activity;
public void setActivity(@Nullable Activity activity) {
this.activity = activity;
}
@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,
applicationContext,
result::success);
break;
}
case "requestPermissions":
final List<Integer> permissions = call.arguments();
permissionManager.requestPermissions(
permissions,
activity,
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,
activity,
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.Retention;
import java.lang.annotation.RetentionPolicy;
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;
//PERMISSION_GROUP
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;
@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_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
})
@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;
@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.
*
* <p>Call {@link #registerWith(io.flutter.plugin.common.PluginRegistry.Registrar)} to register an
* implementation of this that uses the stable {@code io.flutter.plugin.common} package.
*/
public final class PermissionHandlerPlugin implements FlutterPlugin, ActivityAware {
private final PermissionManager permissionManager;
private MethodChannel methodChannel;
@SuppressWarnings("deprecation")
@Nullable private io.flutter.plugin.common.PluginRegistry.Registrar pluginRegistrar;
@Nullable private ActivityPluginBinding pluginBinding;
@Nullable
private MethodCallHandlerImpl methodCallHandler;
public PermissionHandlerPlugin() {
this.permissionManager = new PermissionManager();
}
/**
* Registers a plugin implementation that uses the stable {@code io.flutter.plugin.common}
* package.
*
* <p>Calling this automatically initializes the plugin. However plugins initialized this way
* won't react to changes in activity or context, unlike {@link PermissionHandlerPlugin}.
*/
@SuppressWarnings("deprecation")
public static void registerWith(io.flutter.plugin.common.PluginRegistry.Registrar registrar) {
final PermissionHandlerPlugin plugin = new PermissionHandlerPlugin();
plugin.pluginRegistrar = registrar;
plugin.registerListeners();
plugin.startListening(registrar.context(), registrar.messenger());
if (registrar.activeContext() instanceof Activity) {
plugin.startListeningToActivity(
registrar.activity()
);
}
}
@Override
public void onAttachedToEngine(@NonNull FlutterPluginBinding binding) {
startListening(
binding.getApplicationContext(),
binding.getBinaryMessenger()
);
}
@Override
public void onDetachedFromEngine(@NonNull FlutterPluginBinding binding) {
stopListening();
}
@Override
public void onAttachedToActivity(@NonNull ActivityPluginBinding binding) {
startListeningToActivity(
binding.getActivity()
);
this.pluginBinding = binding;
registerListeners();
}
@Override
public void onReattachedToActivityForConfigChanges(@NonNull ActivityPluginBinding binding) {
onAttachedToActivity(binding);
}
@Override
public void onDetachedFromActivity() {
stopListeningToActivity();
deregisterListeners();
}
@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 (methodCallHandler != null) {
methodCallHandler.setActivity(activity);
}
}
private void stopListeningToActivity() {
if (methodCallHandler != null) {
methodCallHandler.setActivity(null);
}
}
private void registerListeners() {
if (this.pluginRegistrar != null) {
this.pluginRegistrar.addActivityResultListener(this.permissionManager);
this.pluginRegistrar.addRequestPermissionsResultListener(this.permissionManager);
} else 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 android.app.Activity;
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.Nullable;
import androidx.core.app.ActivityCompat;
import androidx.core.app.NotificationManagerCompat;
import androidx.core.content.ContextCompat;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import io.flutter.plugin.common.PluginRegistry;
final class PermissionManager implements PluginRegistry.ActivityResultListener, PluginRegistry.RequestPermissionsResultListener {
@Nullable
private RequestPermissionsSuccessCallback successCallback;
@Nullable
private Activity activity;
private Map<Integer, Integer> requestResults;
@Override
public boolean onActivityResult(int requestCode, int resultCode, Intent data) {
if (requestCode != PermissionConstants.PERMISSION_CODE_IGNORE_BATTERY_OPTIMIZATIONS &&
requestCode != PermissionConstants.PERMISSION_CODE_MANAGE_EXTERNAL_STORAGE &&
requestCode != PermissionConstants.PERMISSION_CODE_SYSTEM_ALERT_WINDOW) {
return false;
}
int status = resultCode == Activity.RESULT_OK
? PermissionConstants.PERMISSION_STATUS_GRANTED
: PermissionConstants.PERMISSION_STATUS_DENIED;
int permission;
if (requestCode == PermissionConstants.PERMISSION_CODE_IGNORE_BATTERY_OPTIMIZATIONS) {
permission = PermissionConstants.PERMISSION_GROUP_IGNORE_BATTERY_OPTIMIZATIONS;
} else if (requestCode == PermissionConstants.PERMISSION_CODE_MANAGE_EXTERNAL_STORAGE) {
status = Environment.isExternalStorageManager()
? PermissionConstants.PERMISSION_STATUS_GRANTED
: PermissionConstants.PERMISSION_STATUS_DENIED;
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 {
return false;
}
HashMap<Integer, Integer> results = new HashMap<>();
results.put(permission, status);
successCallback.onSuccess(results);
return true;
}
@Override
public boolean onRequestPermissionsResult(int requestCode, String[] permissions, int[] grantResults) {
if (requestCode != PermissionConstants.PERMISSION_CODE) {
ongoing = false;
return false;
}
for (int i = 0; i < permissions.length; i++) {
final String permissionName = permissions[i];
@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_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));
}
PermissionUtils.updatePermissionShouldShowStatus(this.activity, permission);
}
this.successCallback.onSuccess(requestResults);
ongoing = 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);
}
private boolean ongoing = false;
void checkPermissionStatus(
@PermissionConstants.PermissionGroup int permission,
Context context,
CheckPermissionsSuccessCallback successCallback) {
successCallback.onSuccess(determinePermissionStatus(
permission,
context));
}
void requestPermissions(
List<Integer> permissions,
Activity activity,
RequestPermissionsSuccessCallback successCallback,
ErrorCallback errorCallback) {
if (ongoing) {
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.activity = activity;
this.requestResults = new HashMap<>();
ArrayList<String> permissionsToRequest = new ArrayList<>();
for (Integer permission : permissions) {
@PermissionConstants.PermissionStatus final int permissionStatus = determinePermissionStatus(permission, activity);
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;
}
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.M && permission == PermissionConstants.PERMISSION_GROUP_IGNORE_BATTERY_OPTIMIZATIONS) {
executeIntent(
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) {
executeIntent(
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) {
executeIntent(
Settings.ACTION_MANAGE_OVERLAY_PERMISSION,
PermissionConstants.PERMISSION_CODE_SYSTEM_ALERT_WINDOW);
} else {
permissionsToRequest.addAll(names);
}
}
final String[] requestPermissions = permissionsToRequest.toArray(new String[0]);
if (permissionsToRequest.size() > 0) {
ongoing = true;
ActivityCompat.requestPermissions(
activity,
requestPermissions,
PermissionConstants.PERMISSION_CODE);
} else {
ongoing = false;
if (requestResults.size() > 0) {
successCallback.onSuccess(requestResults);
}
}
}
@PermissionConstants.PermissionStatus
private int determinePermissionStatus(
@PermissionConstants.PermissionGroup int permission,
Context context) {
if (permission == PermissionConstants.PERMISSION_GROUP_NOTIFICATION) {
return checkNotificationPermissionStatus(context);
}
if (permission == PermissionConstants.PERMISSION_GROUP_BLUETOOTH) {
return checkBluetoothPermissionStatus(context);
}
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: " + 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 PermissionConstants.PERMISSION_STATUS_DENIED;
}
final boolean targetsMOrHigher = context.getApplicationInfo().targetSdkVersion >= Build.VERSION_CODES.M;
for (String name : names) {
// Only handle them if the client app actually targets a API level greater than M.
if (targetsMOrHigher) {
if (permission == PermissionConstants.PERMISSION_GROUP_IGNORE_BATTERY_OPTIMIZATIONS) {
String packageName = context.getPackageName();
PowerManager pm = (PowerManager) context.getSystemService(Context.POWER_SERVICE);
// PowerManager.isIgnoringBatteryOptimizations has been included in Android M first.
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.M) {
if (pm != null && pm.isIgnoringBatteryOptimizations(packageName)) {
return PermissionConstants.PERMISSION_STATUS_GRANTED;
} else {
return PermissionConstants.PERMISSION_STATUS_DENIED;
}
} else {
return PermissionConstants.PERMISSION_STATUS_RESTRICTED;
}
}
if (permission == PermissionConstants.PERMISSION_GROUP_MANAGE_EXTERNAL_STORAGE) {
if (Build.VERSION.SDK_INT < Build.VERSION_CODES.R) {
return PermissionConstants.PERMISSION_STATUS_RESTRICTED;
}
return Environment.isExternalStorageManager()
? PermissionConstants.PERMISSION_STATUS_GRANTED
: PermissionConstants.PERMISSION_STATUS_DENIED;
}
if (permission == PermissionConstants.PERMISSION_GROUP_SYSTEM_ALERT_WINDOW) {
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.M) {
return Settings.canDrawOverlays(context)
? PermissionConstants.PERMISSION_STATUS_GRANTED
: PermissionConstants.PERMISSION_STATUS_DENIED;
}
}
final int permissionStatus = ContextCompat.checkSelfPermission(context, name);
if (permissionStatus != PackageManager.PERMISSION_GRANTED) {
return PermissionConstants.PERMISSION_STATUS_DENIED;
}
}
}
return PermissionConstants.PERMISSION_STATUS_GRANTED;
}
private void executeIntent(String action, int requestCode) {
String packageName = activity.getPackageName();
Intent intent = new Intent();
intent.setAction(action);
intent.setData(Uri.parse("package:" + packageName));
activity.startActivityForResult(intent, requestCode);
}
void shouldShowRequestPermissionRationale(
int permission,
Activity activity,
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)));
}
private int checkNotificationPermissionStatus(Context context) {
NotificationManagerCompat manager = NotificationManagerCompat.from(context);
boolean isGranted = manager.areNotificationsEnabled();
if (isGranted) {
return PermissionConstants.PERMISSION_STATUS_GRANTED;
}
return PermissionConstants.PERMISSION_STATUS_DENIED;
}
private int checkBluetoothPermissionStatus(Context context) {
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;
}
}
package com.baseflow.permissionhandler;
import android.Manifest;
import android.app.Activity;
import android.content.Context;
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.RequiresApi;
import androidx.core.app.ActivityCompat;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;
public class PermissionUtils {
@PermissionConstants.PermissionGroup
static int parseManifestName(String permission) {
switch (permission) {
case Manifest.permission.READ_CALENDAR:
case Manifest.permission.WRITE_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:
case Manifest.permission.BIND_CALL_REDIRECTION_SERVICE:
return PermissionConstants.PERMISSION_GROUP_PHONE;
case Manifest.permission.BODY_SENSORS:
return PermissionConstants.PERMISSION_GROUP_SENSORS;
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;
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:
if (hasPermissionInManifest(context, permissionNames, Manifest.permission.READ_CALENDAR))
permissionNames.add(Manifest.permission.READ_CALENDAR);
if (hasPermissionInManifest(context, permissionNames, Manifest.permission.WRITE_CALENDAR))
permissionNames.add(Manifest.permission.WRITE_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:
// 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 (Build.VERSION.SDK_INT >= Build.VERSION_CODES.Q) {
if (hasPermissionInManifest(context, permissionNames, Manifest.permission.ACCESS_BACKGROUND_LOCATION))
permissionNames.add(Manifest.permission.ACCESS_BACKGROUND_LOCATION);
}
case PermissionConstants.PERMISSION_GROUP_LOCATION_WHEN_IN_USE:
case PermissionConstants.PERMISSION_GROUP_LOCATION:
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.Q && hasPermissionInManifest(context, permissionNames, Manifest.permission.BIND_CALL_REDIRECTION_SERVICE))
permissionNames.add(Manifest.permission.BIND_CALL_REDIRECTION_SERVICE);
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_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_NOTIFICATION:
case PermissionConstants.PERMISSION_GROUP_MEDIA_LIBRARY:
case PermissionConstants.PERMISSION_GROUP_PHOTOS:
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 = context
.getPackageManager()
.getPackageInfo(context.getPackageName(), PackageManager.GET_PERMISSIONS);
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;
}
@PermissionConstants.PermissionStatus
static int toPermissionStatus(final Activity activity, final String permissionName, int grantResult) {
if (grantResult == PackageManager.PERMISSION_DENIED) {
return Build.VERSION.SDK_INT >= Build.VERSION_CODES.M && PermissionUtils.isNeverAskAgainSelected(activity, permissionName)
? PermissionConstants.PERMISSION_STATUS_NEVER_ASK_AGAIN
: PermissionConstants.PERMISSION_STATUS_DENIED;
}
return PermissionConstants.PERMISSION_STATUS_GRANTED;
}
static void updatePermissionShouldShowStatus(final Activity activity, @PermissionConstants.PermissionGroup int permission) {
if (activity == null) {
return;
}
List<String> names = getManifestNames(activity, permission);
if (names == null || names.isEmpty()) {
return;
}
}
@RequiresApi(api = Build.VERSION_CODES.M)
static boolean isNeverAskAgainSelected(final Activity activity, final String name) {
if (activity == null) {
return false;
}
final boolean shouldShowRequestPermissionRationale = ActivityCompat.shouldShowRequestPermissionRationale(activity, name);
return !shouldShowRequestPermissionRationale;
}
}
package com.baseflow.permissionhandler;
import android.bluetooth.BluetoothAdapter;
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()
? PermissionConstants.SERVICE_STATUS_ENABLED
: PermissionConstants.SERVICE_STATUS_DISABLED;
successCallback.onSuccess(serviceStatus);
}
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;
}
Intent callIntent = new Intent(Intent.ACTION_CALL);
callIntent.setData(Uri.parse("tel:123123"));
List<ResolveInfo> callAppsList = pm.queryIntentActivities(callIntent, 0);
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);
}
private boolean isBluetoothServiceEnabled() {
final BluetoothAdapter bluetoothAdapter = BluetoothAdapter.getDefaultAdapter();
return bluetoothAdapter.isEnabled();
}
}
# 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
connection.project.dir=
eclipse.preferences.version=1
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 {
compileSdkVersion 30
lintOptions {
disable 'InvalidPackage'
}
defaultConfig {
// TODO: Specify your own unique Application ID (https://developer.android.com/studio/build/application-id.html).
applicationId "com.example.permissionhandlerexample"
minSdkVersion 16
targetSdkVersion 29
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 '../..'
}
\ No newline at end of file
<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"/>
</manifest>
<manifest xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:tools="http://schemas.android.com/tools"
package="com.example.permissionhandlerexample">
<!--
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"/>
<!-- 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.BIND_CALL_REDIRECTION_SERVICE"/>
<!-- 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" />
<!-- 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 `bluetooth` group -->
<uses-permission android:name="android.permission.BLUETOOTH" />
<!-- 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" />
<application
android:name="io.flutter.app.FlutterApplication"
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">
<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" />
</manifest>
buildscript {
repositories {
google()
jcenter()
}
dependencies {
classpath 'com.android.tools.build:gradle:3.5.0'
}
}
allprojects {
repositories {
google()
jcenter()
}
}
rootProject.buildDir = '../build'
subprojects {
project.buildDir = "${rootProject.buildDir}/${project.name}"
}
subprojects {
project.evaluationDependsOn(':app')
}
task clean(type: Delete) {
delete rootProject.buildDir
}
org.gradle.jvmargs=-Xmx1536M
android.enableJetifier=true
android.useAndroidX=true
android.enableR8=true
#Thu May 16 14:57:52 BST 2019
distributionBase=GRADLE_USER_HOME
distributionPath=wrapper/dists
zipStoreBase=GRADLE_USER_HOME
zipStorePath=wrapper/dists
distributionUrl=https\://services.gradle.org/distributions/gradle-5.6.2-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
}
*.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>$(DEVELOPMENT_LANGUAGE)</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>8.0</string>
</dict>
</plist>
#include "Pods/Target Support Files/Pods-Runner/Pods-Runner.debug.xcconfig"
#include "Generated.xcconfig"
#
# NOTE: This podspec is NOT to be published. It is only used as a local source!
# This is a generated file; do not edit or check into version control.
#
Pod::Spec.new do |s|
s.name = 'Flutter'
s.version = '1.0.0'
s.summary = 'High-performance, high-fidelity mobile apps.'
s.homepage = 'https://flutter.io'
s.license = { :type => 'MIT' }
s.author = { 'Flutter Dev Team' => 'flutter-dev@googlegroups.com' }
s.source = { :git => 'https://github.com/flutter/engine', :tag => s.version.to_s }
s.ios.deployment_target = '8.0'
# Framework linking is handled by Flutter tooling, not CocoaPods.
# Add a placeholder to satisfy `s.dependency 'Flutter'` plugin podspecs.
s.vendored_frameworks = 'path/to/nothing'
end
#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, '9.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 infomation: https://github.com/BaseflowIT/flutter-permission-handler/blob/develop/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=0',
## dart: PermissionGroup.reminders
# 'PERMISSION_REMINDERS=0',
## dart: PermissionGroup.contacts
# 'PERMISSION_CONTACTS=0',
## dart: PermissionGroup.camera
# 'PERMISSION_CAMERA=0',
## dart: PermissionGroup.microphone
# 'PERMISSION_MICROPHONE=0',
## dart: PermissionGroup.speech
# 'PERMISSION_SPEECH_RECOGNIZER=0',
## dart: PermissionGroup.photos
#'PERMISSION_PHOTOS=0'
## dart: [PermissionGroup.location, PermissionGroup.locationAlways, PermissionGroup.locationWhenInUse]
# 'PERMISSION_LOCATION=0',
## dart: PermissionGroup.notification
# 'PERMISSION_NOTIFICATIONS=0',
## dart: PermissionGroup.mediaLibrary
# 'PERMISSION_MEDIA_LIBRARY=0',
## dart: PermissionGroup.sensors
# 'PERMISSION_SENSORS=0'
]
end
end
end
// !$*UTF8*$!
{
archiveVersion = 1;
classes = {
};
objectVersion = 51;
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>"; };
/* 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 = (
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 */,
);
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 = 1020;
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;
buildActionMask = 2147483647;
files = (
);
inputPaths = (
);
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;
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";
};
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 = 9.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)";
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 = 9.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 = 9.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;
CURRENT_PROJECT_VERSION = "$(FLUTTER_BUILD_NUMBER)";
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)";
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"?>
<Workspace
version = "1.0">
<FileRef
location = "group:Runner.xcodeproj">
</FileRef>
<FileRef
location = "group:Pods/Pods.xcodeproj">
</FileRef>
</Workspace>
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>
<!-- 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>
</dict>
</plist>
import 'package:flutter/material.dart';
import 'package:flutter/widgets.dart';
import 'template/globals.dart';
void main() {
runApp(BaseflowPluginExample());
}
/// A Flutter application demonstrating the functionality of this plugin
class BaseflowPluginExample extends StatelessWidget {
/// [MaterialColor] to be used in the app [ThemeData]
final MaterialColor themeMaterialColor =
createMaterialColor(const Color.fromRGBO(48, 49, 60, 1));
@override
Widget build(BuildContext context) {
return MaterialApp(
title: 'Baseflow $pluginName',
theme: ThemeData(
accentColor: Colors.white60,
backgroundColor: const Color.fromRGBO(48, 49, 60, 0.8),
buttonTheme: ButtonThemeData(
buttonColor: themeMaterialColor.shade500,
disabledColor: themeMaterialColor.withRed(200),
splashColor: themeMaterialColor.shade50,
textTheme: ButtonTextTheme.primary,
),
bottomAppBarColor: const Color.fromRGBO(57, 58, 71, 1),
hintColor: themeMaterialColor.shade500,
primarySwatch: createMaterialColor(const Color.fromRGBO(48, 49, 60, 1)),
textTheme: TextTheme(
bodyText1: TextStyle(
color: Colors.white,
fontSize: 16,
height: 1.3,
),
bodyText2: TextStyle(
color: Colors.white,
fontSize: 18,
height: 1.2,
),
button: TextStyle(color: Colors.white),
headline1: TextStyle(
color: Colors.white,
fontSize: 18,
),
),
visualDensity: VisualDensity.adaptivePlatformDensity,
inputDecorationTheme: InputDecorationTheme(
fillColor: const Color.fromRGBO(37, 37, 37, 1),
filled: true,
),
),
home: AppHome(title: 'Baseflow $pluginName example app'),
);
}
/// Creates a [MaterialColor] based on the supplied [Color]
static MaterialColor createMaterialColor(Color color) {
List strengths = <double>[.05];
Map swatch = <int, Color>{};
final r = color.red, g = color.green, b = color.blue;
for (var i = 1; i < 10; i++) {
strengths.add(0.1 * i);
}
for (var strength in strengths) {
final ds = 0.5 - strength;
swatch[(strength * 1000).round()] = Color.fromRGBO(
r + ((ds < 0 ? r : (255 - r)) * ds).round(),
g + ((ds < 0 ? g : (255 - g)) * ds).round(),
b + ((ds < 0 ? b : (255 - b)) * ds).round(),
1,
);
}
return MaterialColor(color.value, swatch as Map<int, Color>);
}
}
/// A Flutter example demonstrating how the [pluginName] plugin could be used
class AppHome extends StatefulWidget {
/// Constructs the [AppHome] class
AppHome({Key? key, this.title}) : super(key: key);
/// The [title] of the application, which is shown in the application's
/// title bar.
final String? title;
@override
_AppHomeState createState() => _AppHomeState();
}
class _AppHomeState extends State<AppHome> {
static final PageController _pageController = PageController(initialPage: 0);
int _currentPage = 0;
@override
Widget build(BuildContext context) {
return Scaffold(
appBar: AppBar(
backgroundColor: Theme.of(context).bottomAppBarColor,
title: Center(
child: Image.asset(
'res/images/baseflow_logo_def_light-02.png',
width: 140,
),
),
),
backgroundColor: Theme.of(context).backgroundColor,
body: PageView(
controller: _pageController,
children: pages,
onPageChanged: (page) {
setState(() {
_currentPage = page;
});
},
),
bottomNavigationBar: _bottomAppBar(),
);
}
BottomAppBar _bottomAppBar() {
return BottomAppBar(
elevation: 5,
color: Theme.of(context).bottomAppBarColor,
child: Row(
mainAxisSize: MainAxisSize.max,
mainAxisAlignment: MainAxisAlignment.spaceBetween,
children: List.unmodifiable(() sync* {
for (var i = 0; i < pages.length; i++) {
yield Expanded(
child: IconButton(
iconSize: 30,
icon: Icon(icons.elementAt(i)),
color: _bottomAppBarIconColor(i),
onPressed: () => _animateToPage(i),
),
);
}
}()),
),
);
}
void _animateToPage(int page) {
_pageController.animateToPage(page,
duration: Duration(milliseconds: 200), curve: Curves.linear);
}
Color _bottomAppBarIconColor(int page) {
return _currentPage == page ? Colors.white : Theme.of(context).accentColor;
}
}
import 'dart:io';
import 'package:flutter/material.dart';
import 'package:permission_handler/permission_handler.dart';
import 'permission_widget.dart';
/// Constructs a [ListView] containing [PermissionWidget] for each available
/// permission.
class PermissionList extends StatelessWidget {
@override
Widget build(BuildContext context) {
return Center(
child: ListView(
children: Permission.values
.where((permission) {
if (Platform.isIOS) {
return permission != Permission.unknown &&
permission != Permission.sms &&
permission != Permission.storage &&
permission != Permission.ignoreBatteryOptimizations &&
permission != Permission.accessMediaLocation &&
permission != Permission.activityRecognition &&
permission != Permission.manageExternalStorage;
} else {
return permission != Permission.unknown &&
permission != Permission.mediaLibrary &&
permission != Permission.photos &&
permission != Permission.reminders;
}
})
.map((permission) => PermissionWidget(permission))
.toList()),
);
}
}
import 'package:flutter/material.dart';
import 'package:permission_handler/permission_handler.dart';
/// Permission widget which displays a permission and allows users to request
/// the permissions.
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;
PermissionStatus _permissionStatus = PermissionStatus.denied;
@override
void initState() {
super.initState();
_listenForPermissionStatus();
}
void _listenForPermissionStatus() async {
final status = await _permission.status;
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.bodyText1,
),
subtitle: Text(
_permissionStatus.toString(),
style: TextStyle(color: getPermissionColor()),
),
trailing: IconButton(
icon: const Icon(
Icons.info,
color: Colors.white,
),
onPressed: () {
checkServiceStatus(context, _permission);
}),
onTap: () {
requestPermission(_permission);
},
);
}
void checkServiceStatus(BuildContext context, Permission permission) async {
ScaffoldMessenger.of(context).showSnackBar(SnackBar(
content: Text((await permission.status).toString()),
));
}
Future<void> requestPermission(Permission permission) async {
final status = await permission.request();
setState(() {
print(status);
_permissionStatus = status;
print(_permissionStatus);
});
}
}
import 'dart:core';
import 'package:flutter/material.dart';
import '../plugin_example/permission_list.dart';
import 'info_page.dart';
/// The name of the plugin, which will be displayed throughout the example App.
const String pluginName = 'Permission Handler';
/// Returns Github URL, which is shown in the [InfoPage].
const String githubURL =
'https://github.com/Baseflow/flutter-permission-handler';
/// Returns Baseflow URL, which is shown in the [InfoPage].
const String baseflowURL = 'https://baseflow.com';
/// Returns pub.dev URL, which is shown in the [InfoPage].
const String pubDevURL = 'https://pub.dev/packages/permission_handler';
/// [EdgeInsets] to define horizontal padding throughout the application.
const EdgeInsets defaultHorizontalPadding =
EdgeInsets.symmetric(horizontal: 24);
/// [EdgeInsets] to define vertical padding throughout the application.
const EdgeInsets defaultVerticalPadding = EdgeInsets.symmetric(vertical: 24);
/// Returns a [List] with [IconData] to show in the [AppHome] [AppBar].
final List<IconData> icons = [
Icons.list,
Icons.info_outline,
];
/// Returns a [List] with [Widget]s to construct pages in the [AppBar].
final List<Widget> pages = [
PermissionList(),
InfoPage(),
];
import 'package:flutter/material.dart';
import 'package:flutter/rendering.dart';
import 'package:url_launcher/url_launcher.dart';
import 'globals.dart';
/// [StatelessWidget] displaying information about Baseflow
class InfoPage extends StatelessWidget {
@override
Widget build(BuildContext context) {
return SizedBox.expand(
child: Align(
alignment: Alignment.bottomCenter,
child: SingleChildScrollView(
child: Padding(
padding: defaultHorizontalPadding + defaultVerticalPadding,
child: Column(
mainAxisSize: MainAxisSize.max,
mainAxisAlignment: MainAxisAlignment.end,
children: <Widget>[
Align(
alignment: Alignment.centerLeft,
child: Image.asset(
'res/images/poweredByBaseflowLogoLight@3x.png',
width: 250,
alignment: Alignment.centerLeft,
),
),
const Padding(
padding: EdgeInsets.symmetric(vertical: 24),
),
Text(
'This app showcases the possibilities of the $pluginName '
'plugin, powered by Baseflow. '
'This plugin is available as open source project on Github. '
'\n\n'
'Need help with integrating functionalities within your own '
'apps? Contact us at hello@baseflow.com',
style: Theme.of(context).textTheme.bodyText1,
),
const Padding(
padding: EdgeInsets.symmetric(vertical: 8),
),
_launcherRaisedButton(
'Find us on Github',
githubURL,
context,
),
_launcherRaisedButton(
'Find us on pub.dev',
pubDevURL,
context,
),
_launcherRaisedButton(
'Visit baseflow.com',
baseflowURL,
context,
),
const Padding(
padding: EdgeInsets.only(bottom: 30),
),
],
),
),
),
),
);
}
Widget _launcherRaisedButton(String text, String url, BuildContext context) {
return Container(
width: MediaQuery.of(context).size.width,
height: 50,
margin: const EdgeInsets.only(top: 24.0),
alignment: Alignment.center,
child: SizedBox.expand(
child: ElevatedButton(
style: ElevatedButton.styleFrom(
padding: const EdgeInsets.all(8),
shape: RoundedRectangleBorder(
borderRadius: BorderRadius.circular(30.0),
),
),
child: Text(text),
onPressed: () => _launchURL(url),
),
),
);
}
Future<void> _launchURL(String url) async {
if (await canLaunch(url)) {
await launch(url);
} else {
throw 'Could not launch $url';
}
}
}
name: permission_handler_example
description: Demonstrates how to use the permission_handler plugin.
environment:
sdk: ">=2.12.0-259.9.beta <3.0.0"
dependencies:
flutter:
sdk: flutter
dev_dependencies:
flutter_test:
sdk: flutter
permission_handler:
path: ../
url_launcher: ^6.0.0
flutter:
uses-material-design: true
assets:
- res/images/baseflow_logo_def_light-02.png
- res/images/poweredByBaseflowLogoLight@3x.png
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.
C:/Users/Administrator/AppData/Local/Pub/Cache/hosted/pub.flutter-io.cn/permission_handler_windows-0.2.1/
\ No newline at end of file
C:/Users/Administrator/AppData/Local/Pub/Cache/hosted/pub.flutter-io.cn/url_launcher_windows-3.1.1/
\ No newline at end of file
.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
// Info.plist: NSCalendarsUsageDescription
// dart: PermissionGroup.calendar
#ifndef PERMISSION_EVENTS
#define PERMISSION_EVENTS 1
#endif
// ios: PermissionGroupReminders
// Info.plist: NSRemindersUsageDescription
// dart: PermissionGroup.reminders
#ifndef PERMISSION_REMINDERS
#define PERMISSION_REMINDERS 1
#endif
// ios: PermissionGroupContacts
// Info.plist: NSContactsUsageDescription
// dart: PermissionGroup.contacts
#ifndef PERMISSION_CONTACTS
#define PERMISSION_CONTACTS 1
#endif
// ios: PermissionGroupCamera
// Info.plist: NSCameraUsageDescription
// dart: PermissionGroup.camera
#ifndef PERMISSION_CAMERA
#define PERMISSION_CAMERA 1
#endif
// ios: PermissionGroupMicrophone
// Info.plist: NSMicrophoneUsageDescription
// dart: PermissionGroup.microphone
#ifndef PERMISSION_MICROPHONE
#define PERMISSION_MICROPHONE 1
#endif
// ios: PermissionGroupSpeech
// Info.plist: NSSpeechRecognitionUsageDescription
// dart: PermissionGroup.speech
#ifndef PERMISSION_SPEECH_RECOGNIZER
#define PERMISSION_SPEECH_RECOGNIZER 1
#endif
// ios: PermissionGroupPhotos
// Info.plist: NSPhotoLibraryUsageDescription
// dart: PermissionGroup.photos
#ifndef PERMISSION_PHOTOS
#define PERMISSION_PHOTOS 1
#endif
// ios: PermissionGroupPhotosAddOnly
// Info.plist: NSPhotoLibraryUsageDescription
// dart: PermissionGroup.photosAddOnly
#ifndef PERMISSION_PHOTOS_ADD_ONLY
#define PERMISSION_PHOTOS_ADD_ONLY 1
#endif
// ios: [PermissionGroupLocation, PermissionGroupLocationAlways, PermissionGroupLocationWhenInUse]
// Info.plist: [NSLocationUsageDescription, NSLocationAlwaysAndWhenInUseUsageDescription, NSLocationWhenInUseUsageDescription]
// dart: [PermissionGroup.location, PermissionGroup.locationAlways, PermissionGroup.locationWhenInUse]
#ifndef PERMISSION_LOCATION
#define PERMISSION_LOCATION 1
#endif
// ios: PermissionGroupNotification
// dart: PermissionGroup.notification
#ifndef PERMISSION_NOTIFICATIONS
#define PERMISSION_NOTIFICATIONS 1
#endif
// ios: PermissionGroupMediaLibrary
// Info.plist: [NSAppleMusicUsageDescription, kTCCServiceMediaLibrary]
// dart: PermissionGroup.mediaLibrary
#ifndef PERMISSION_MEDIA_LIBRARY
#define PERMISSION_MEDIA_LIBRARY 1
#endif
// ios: PermissionGroupSensors
// Info.plist: NSMotionUsageDescription
// dart: PermissionGroup.sensors
#ifndef PERMISSION_SENSORS
#define PERMISSION_SENSORS 1
#endif
// ios: PermissionGroupBluetooth
// Info.plist: [NSBluetoothAlwaysUsageDescription, NSBluetoothPeripheralUsageDescription]
// dart: PermissionGroup.bluetooth
#ifndef PERMISSION_BLUETOOTH
#define PERMISSION_BLUETOOTH 1
#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
};
typedef NS_ENUM(int, PermissionStatus) {
PermissionStatusDenied = 0,
PermissionStatusGranted = 1,
PermissionStatusRestricted = 2,
PermissionStatusLimited = 3,
PermissionStatusPermanentlyDenied = 4
};
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]);
}
_methodResult = result;
NSArray *permissions = [Codec decodePermissionGroupsFrom:call.arguments];
[_permissionManager
requestPermissions:permissions completion:^(NSDictionary *permissionRequestResults) {
if (self->_methodResult != nil) {
self->_methodResult(permissionRequestResults);
}
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 "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 "PermissionHandlerEnums.h"
#import "Codec.h"
typedef void (^PermissionRequestCompletion)(NSDictionary *permissionRequestResults);
@interface PermissionManager : NSObject
- (instancetype)initWithStrategyInstances;
- (void)requestPermissions:(NSArray *)permissions completion:(PermissionRequestCompletion)completion;
+ (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 {
id <PermissionStrategy> permissionStrategy = [PermissionManager createPermissionStrategy:permission];
ServiceStatus status = [permissionStrategy checkServiceStatus:permission];
result([Codec encodeServiceStatus:status]);
}
- (void)requestPermissions:(NSArray *)permissions completion:(PermissionRequestCompletion)completion {
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;
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);
return;
}
}];
}
}
+ (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, *)) {
BOOL success = [[UIApplication sharedApplication] openURL:[NSURL URLWithString:UIApplicationOpenSettingsURLString]];
result([[NSNumber alloc] initWithBool:success]);
} else {
result(@false);
}
}
+ (id)createPermissionStrategy:(PermissionGroup)permission {
switch (permission) {
case PermissionGroupCalendar:
return [EventPermissionStrategy new];
case PermissionGroupCamera:
return [AudioVideoPermissionStrategy new];
case PermissionGroupContacts:
return [ContactPermissionStrategy new];
case PermissionGroupLocation:
case PermissionGroupLocationAlways:
case PermissionGroupLocationWhenInUse:
#if PERMISSION_LOCATION
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];
default:
return [UnknownPermissionStrategy new];
}
}
@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_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;
}
- (ServiceStatus)checkServiceStatus:(PermissionGroup)permission {
return ServiceStatusNotApplicable;
}
- (void)requestPermission:(PermissionGroup)permission completionHandler:(PermissionStatusHandler)completionHandler {
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
//
// 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>
@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
- (PermissionStatus)checkPermissionStatus:(PermissionGroup)permission {
if (@available(iOS 13.1, *)) {
CBManagerAuthorization blePermission = [CBCentralManager authorization];
return [BluetoothPermissionStrategy parsePermission:blePermission];
} else if (@available(iOS 13.0, *)){
CBCentralManager* manager = [[CBCentralManager alloc] init];
CBManagerAuthorization blePermission = [manager authorization];
return [BluetoothPermissionStrategy parsePermission:blePermission];
}
return PermissionStatusGranted;
}
- (ServiceStatus)checkServiceStatus:(PermissionGroup)permission {
CBCentralManager* manager = [[CBCentralManager alloc] init];
if (@available(iOS 10, *)) {
return [manager state] == CBManagerStatePoweredOn ? ServiceStatusEnabled : ServiceStatusDisabled;
}
return [manager state] == CBCentralManagerStatePoweredOn ? ServiceStatusEnabled : ServiceStatusDisabled;
}
- (void)requestPermission:(PermissionGroup)permission completionHandler:(PermissionStatusHandler)completionHandler {
completionHandler([self checkPermissionStatus:permission]);
}
+ (PermissionStatus)parsePermission:(CBManagerAuthorization)bluetoothPermission API_AVAILABLE(ios(13)){
switch(bluetoothPermission){
case CBManagerAuthorizationNotDetermined:
return PermissionStatusDenied;
case CBManagerAuthorizationRestricted:
return PermissionStatusRestricted;
case CBManagerAuthorizationDenied:
return PermissionStatusDenied;
case CBManagerAuthorizationAllowedAlways:
return PermissionStatusGranted;
}
}
@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];
}
- (ServiceStatus)checkServiceStatus:(PermissionGroup)permission {
return ServiceStatusNotApplicable;
}
- (void)requestPermission:(PermissionGroup)permission completionHandler:(PermissionStatusHandler)completionHandler {
PermissionStatus status = [self checkPermissionStatus:permission];
if (status != PermissionStatusDenied) {
completionHandler(status);
}
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 {
ABAuthorizationStatus status = ABAddressBookGetAuthorizationStatus();
switch (status) {
case kABAuthorizationStatusNotDetermined:
return PermissionStatusDenied;
case kABAuthorizationStatusRestricted:
return PermissionStatusRestricted;
case kABAuthorizationStatusDenied:
return PermissionStatusPermanentlyDenied;
case kABAuthorizationStatusAuthorized:
return PermissionStatusGranted;
}
}
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 {
ABAddressBookRequestAccessWithCompletion(ABAddressBookCreate(), ^(bool granted, CFErrorRef error) {
if (granted) {
completionHandler(PermissionStatusGranted);
} else {
completionHandler(PermissionStatusPermanentlyDenied);
}
});
}
@end
#else
@implementation ContactPermissionStrategy
@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_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_REMINDERS
@implementation EventPermissionStrategy
- (PermissionStatus)checkPermissionStatus:(PermissionGroup)permission {
if (permission == PermissionGroupCalendar) {
#if PERMISSION_EVENTS
return [EventPermissionStrategy permissionStatus:EKEntityTypeEvent];
#endif
} else if (permission == PermissionGroupReminders) {
#if PERMISSION_REMINDERS
return [EventPermissionStrategy permissionStatus:EKEntityTypeReminder];
#endif
}
return PermissionStatusDenied;
}
- (ServiceStatus)checkServiceStatus:(PermissionGroup)permission {
return ServiceStatusNotApplicable;
}
- (void)requestPermission:(PermissionGroup)permission completionHandler:(PermissionStatusHandler)completionHandler {
PermissionStatus permissionStatus = [self checkPermissionStatus:permission];
if (permissionStatus != PermissionStatusDenied) {
completionHandler(permissionStatus);
return;
}
EKEntityType entityType;
if (permission == PermissionGroupCalendar) {
#if PERMISSION_EVENTS
entityType = EKEntityTypeEvent;
#else
completionHandler(PermissionStatusDenied);
return;
#endif
} else if (permission == PermissionGroupReminders) {
#if PERMISSION_REMINDERS
entityType = EKEntityTypeReminder;
#else
completionHandler(PermissionStatusDenied);
return;
#endif
} else {
completionHandler(PermissionStatusPermanentlyDenied);
return;
}
EKEventStore *eventStore = [[EKEventStore alloc] init];
[eventStore requestAccessToEntityType:entityType completion:^(BOOL granted, NSError *error) {
if (granted) {
completionHandler(PermissionStatusGranted);
} else {
completionHandler(PermissionStatusPermanentlyDenied);
}
}];
}
+ (PermissionStatus)permissionStatus:(EKEntityType)entityType {
EKAuthorizationStatus status = [EKEventStore authorizationStatusForEntityType:entityType];
switch (status) {
case EKAuthorizationStatusNotDetermined:
return PermissionStatusDenied;
case EKAuthorizationStatusRestricted:
return PermissionStatusRestricted;
case EKAuthorizationStatusDenied:
return PermissionStatusPermanentlyDenied;
case EKAuthorizationStatusAuthorized:
return PermissionStatusGranted;
}
return PermissionStatusDenied;
}
@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
#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
@implementation LocationPermissionStrategy {
CLLocationManager *_locationManager;
PermissionStatusHandler _permissionStatusHandler;
PermissionGroup _requestedPermission;
}
- (instancetype)initWithLocationManager {
self = [super init];
if (self) {
_locationManager = [CLLocationManager new];
_locationManager.delegate = self;
}
return self;
}
- (PermissionStatus)checkPermissionStatus:(PermissionGroup)permission {
return [LocationPermissionStrategy permissionStatus:permission];
}
- (ServiceStatus)checkServiceStatus:(PermissionGroup)permission {
return [CLLocationManager locationServicesEnabled] ? ServiceStatusEnabled : ServiceStatusDisabled;
}
- (void)requestPermission:(PermissionGroup)permission completionHandler:(PermissionStatusHandler)completionHandler {
PermissionStatus status = [self checkPermissionStatus:permission];
if ([CLLocationManager authorizationStatus] == kCLAuthorizationStatusAuthorizedWhenInUse && permission == PermissionGroupLocationAlways) {
// don't do anything and continue requesting permissions
} else if (status != PermissionStatusDenied) {
completionHandler(status);
}
_permissionStatusHandler = completionHandler;
_requestedPermission = permission;
if (permission == PermissionGroupLocation) {
if ([[NSBundle mainBundle] objectForInfoDictionaryKey:@"NSLocationAlwaysUsageDescription"] != nil) {
[_locationManager requestAlwaysAuthorization];
} else if ([[NSBundle mainBundle] objectForInfoDictionaryKey:@"NSLocationWhenInUseUsageDescription"] != nil) {
[_locationManager requestWhenInUseAuthorization];
} else {
[[NSException exceptionWithName:NSInternalInconsistencyException reason:@"To use location in iOS8 you need to define either NSLocationWhenInUseUsageDescription or NSLocationAlwaysUsageDescription in the app bundle's Info.plist file" userInfo:nil] raise];
}
} else if (permission == PermissionGroupLocationAlways) {
if ([[NSBundle mainBundle] objectForInfoDictionaryKey:@"NSLocationAlwaysUsageDescription"] != nil) {
[_locationManager requestAlwaysAuthorization];
} else {
[[NSException exceptionWithName:NSInternalInconsistencyException reason:@"To use location in iOS8 you need to define NSLocationAlwaysUsageDescription in the app bundle's Info.plist file" userInfo:nil] raise];
}
} else if (permission == PermissionGroupLocationWhenInUse) {
if ([[NSBundle mainBundle] objectForInfoDictionaryKey:@"NSLocationWhenInUseUsageDescription"] != nil) {
[_locationManager requestWhenInUseAuthorization];
} else {
[[NSException exceptionWithName:NSInternalInconsistencyException reason:@"To use location in iOS8 you need to define NSLocationWhenInUseUsageDescription in the app bundle's Info.plist file" userInfo:nil] raise];
}
}
}
// {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 to 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.
- (void)locationManager:(CLLocationManager *)manager didChangeAuthorizationStatus:(CLAuthorizationStatus)status {
if (status == kCLAuthorizationStatusNotDetermined) {
return;
}
if (_permissionStatusHandler == nil || @(_requestedPermission) == nil) {
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];
}
- (ServiceStatus)checkServiceStatus:(PermissionGroup)permission {
return ServiceStatusNotApplicable;
}
- (void)requestPermission:(PermissionGroup)permission completionHandler:(PermissionStatusHandler)completionHandler {
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];
}
- (ServiceStatus)checkServiceStatus:(PermissionGroup)permission {
return ServiceStatusNotApplicable;
}
- (void)requestPermission:(PermissionGroup)permission completionHandler:(PermissionStatusHandler)completionHandler {
PermissionStatus status = [self checkPermissionStatus:permission];
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 (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 (^PermissionStatusHandler)(PermissionStatus permissionStatus);
@protocol PermissionStrategy <NSObject>
- (PermissionStatus)checkPermissionStatus:(PermissionGroup)permission;
- (ServiceStatus)checkServiceStatus:(PermissionGroup)permission;
- (void)requestPermission:(PermissionGroup)permission completionHandler:(PermissionStatusHandler)completionHandler;
@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;
}
- (ServiceStatus)checkServiceStatus:(PermissionGroup)permission {
// https://stackoverflow.com/a/5095058
if (![[UIApplication sharedApplication] canOpenURL:[NSURL URLWithString:@"tel://"]]) {
return ServiceStatusNotApplicable;
}
return [self canDevicePlaceAPhoneCall] ? ServiceStatusEnabled : ServiceStatusDisabled;
}
- (void)requestPermission:(PermissionGroup)permission completionHandler:(PermissionStatusHandler)completionHandler {
completionHandler(PermissionStatusPermanentlyDenied);
}
// https://stackoverflow.com/a/11595365
-(bool) canDevicePlaceAPhoneCall {
/*
* Returns YES if the device can place a phone call
*/
// Device supports phone calls, lets confirm it can place one right now
CTTelephonyNetworkInfo *netInfo = [[CTTelephonyNetworkInfo alloc] init];
CTCarrier *carrier = [netInfo subscriberCellularProvider];
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];
}
- (ServiceStatus)checkServiceStatus:(PermissionGroup)permission {
return ServiceStatusNotApplicable;
}
- (void)requestPermission:(PermissionGroup)permission completionHandler:(PermissionStatusHandler)completionHandler {
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];
}
- (ServiceStatus)checkServiceStatus:(PermissionGroup)permission {
if (@available(iOS 11.0, *)) {
return [CMMotionActivityManager isActivityAvailable]
? ServiceStatusEnabled
: ServiceStatusDisabled;
}
return ServiceStatusDisabled;
}
- (void)requestPermission:(PermissionGroup)permission completionHandler:(PermissionStatusHandler)completionHandler {
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];
}
- (ServiceStatus)checkServiceStatus:(PermissionGroup)permission {
return ServiceStatusNotApplicable;
}
- (void)requestPermission:(PermissionGroup)permission completionHandler:(PermissionStatusHandler)completionHandler {
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];
}
- (ServiceStatus)checkServiceStatus:(PermissionGroup)permission {
return ServiceStatusNotApplicable;
}
- (void)requestPermission:(PermissionGroup)permission completionHandler:(PermissionStatusHandler)completionHandler {
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;
}
- (ServiceStatus)checkServiceStatus:(PermissionGroup)permission {
return ServiceStatusDisabled;
}
- (void)requestPermission:(PermissionGroup)permission completionHandler:(PermissionStatusHandler)completionHandler {
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
#
# To learn more about a Podspec see http://guides.cocoapods.org/syntax/podspec.html
#
Pod::Spec.new do |s|
s.name = 'permission_handler'
s.version = '5.1.0+2'
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
end
import 'package:flutter/foundation.dart';
import 'package:permission_handler_platform_interface/permission_handler_platform_interface.dart';
export 'package:permission_handler_platform_interface/permission_handler_platform_interface.dart'
show
Permission,
PermissionStatus,
PermissionStatusGetters,
PermissionWithService,
FuturePermissionStatusGetters,
ServiceStatus,
ServiceStatusGetters,
FutureServiceStatusGetters;
PermissionHandlerPlatform get _handler => PermissionHandlerPlatform.instance;
/// Opens the app settings page.
///
/// Returns [true] if the app settings page could be opened, otherwise [false].
Future<bool> openAppSettings() => _handler.openAppSettings();
/// Actions that can be executed on a permission.
extension PermissionActions on Permission {
/// The current status of this permission.
///
/// The Android-only [PermissionStatus.permanentlyDenied] status will only be
/// calculated if the active context is an Activity. If it isn't,
/// [PermissionStatus.denied] will be returned.
Future<PermissionStatus> get status => _handler.checkPermissionStatus(this);
/// If you should show a rationale for requesting permission.
///
/// This is only implemented on Android, calling this on iOS always returns
/// [false].
Future<bool> get shouldShowRequestRationale async {
if (defaultTargetPlatform != TargetPlatform.android) {
return false;
}
return _handler.shouldShowRequestPermissionRationale(this);
}
/// Request the user for access to this [Permission], if access hasn't already
/// been grant access before.
///
/// Returns the new [PermissionStatus].
Future<PermissionStatus> request() async {
final permissionStatus = (await [this].request())[this];
return permissionStatus ?? PermissionStatus.denied;
}
}
/// Shortcuts for checking the [status] of a [Permission].
extension PermissionCheckShortcuts on Permission {
/// If the user granted this permission.
Future<bool> get isGranted => status.isGranted;
/// If the user denied this permission.
Future<bool> get isDenied => status.isDenied;
/// If the OS denied this permission. The user cannot change the status,
/// possibly due to active restrictions such as parental controls being in
/// place.
/// *Only supported on iOS.*
Future<bool> get isRestricted => status.isRestricted;
///User has authorized this application for limited photo library access.
/// *Only supported on iOS.(iOS14+)*
Future<bool> get isLimited => status.isLimited;
/// If the user denied this permission and selected to never again show a
/// request for it. The user may still change the permission's status in the
/// device settings.
/// *Only supported on Android.*
Future<bool> get isPermanentlyDenied => status.isPermanentlyDenied;
}
/// Actions that apply only to permissions that have an associated service.
extension ServicePermissionActions on PermissionWithService {
/// Checks the current status of the service associated with this 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> get serviceStatus => _handler.checkServiceStatus(this);
}
/// Actions that can be taken on a [List] of [Permission]s.
extension PermissionListActions on List<Permission> {
/// Requests the user for access to these permissions, if they haven't already
/// been granted before.
///
/// Returns a [Map] containing the status per requested [Permission].
Future<Map<Permission, PermissionStatus>> request() =>
_handler.requestPermissions(this);
}
name: permission_handler
description: Permission plugin for Flutter. This plugin provides a cross-platform (iOS, Android) API to request and check permissions.
version: 7.1.0
homepage: https://github.com/baseflowit/flutter-permission-handler
flutter:
plugin:
platforms:
android:
package: com.baseflow.permissionhandler
pluginClass: PermissionHandlerPlugin
ios:
pluginClass: PermissionHandlerPlugin
dependencies:
flutter:
sdk: flutter
meta: ^1.3.0
permission_handler_platform_interface: ^3.3.0
dev_dependencies:
flutter_test:
sdk: flutter
mockito: ^5.0.1
effective_dart: ^1.3.0
plugin_platform_interface: ^2.0.0
environment:
sdk: ">=2.12.0 <4.0.0"
flutter: ">=1.12.8"
#!/bin/bash
wget https://dl.google.com/android/repository/sdk-tools-linux-3859397.zip
mkdir android-sdk
unzip -qq sdk-tools-linux-3859397.zip -d $HOME/android-sdk
export ANDROID_HOME=$HOME/android-sdk
export PATH=$HOME/android-sdk/tools/bin:$PATH
mkdir -p /home/travis/.android # silence sdkmanager warning
echo 'count=0' > /home/travis/.android/repositories.cfg # silence sdkmanager warning
# suppressing output of sdkmanager to keep log under 4MB (travis limit)
echo y | sdkmanager "tools" >/dev/null
echo y | sdkmanager "platform-tools" >/dev/null
echo y | sdkmanager "build-tools;26.0.3" >/dev/null
echo y | sdkmanager "platforms;android-26" >/dev/null
echo y | sdkmanager "extras;android;m2repository" >/dev/null
echo y | sdkmanager "extras;google;m2repository" >/dev/null
echo y | sdkmanager "patcher;v4" >/dev/null
sdkmanager --list
wget http://services.gradle.org/distributions/gradle-4.1-bin.zip
unzip -qq gradle-4.1-bin.zip -d $HOME/gradle-4.1
export GRADLE_HOME=$HOME/gradle-4.1
export PATH=$GRADLE_HOME/bin:$PATH
gradle -v
git clone --single-branch --branch stable https://github.com/flutter/flutter.git $HOME/flutter
export PATH=$HOME/flutter/bin:$HOME/flutter/bin/cache/dart-sdk/bin:$PATH
flutter doctor
#!/bin/bash
brew update
brew install libimobiledevice
brew install ideviceinstaller
brew install ios-deploy
pod repo update
gem update cocoapods
git clone --single-branch --branch stable https://github.com/flutter/flutter.git $HOME/flutter
export PATH=$HOME/flutter/bin:$HOME/flutter/bin/cache/dart-sdk/bin:$PATH
flutter doctor
import 'package:flutter_test/flutter_test.dart';
import 'package:mockito/mockito.dart';
import 'package:permission_handler/permission_handler.dart';
import 'package:permission_handler_platform_interface/permission_handler_platform_interface.dart';
import 'package:plugin_platform_interface/plugin_platform_interface.dart';
void main() {
group('PermissionHandler', () {
setUp(() {
PermissionHandlerPlatform.instance = MockPermissionHandlerPlatform();
});
test('openAppSettings', () async {
final hasOpened = await openAppSettings();
expect(hasOpened, true);
});
test('PermissionActions on Permission: get status', () async {
final permissionStatus = await Permission.calendar.status;
expect(permissionStatus, PermissionStatus.granted);
});
test(
// ignore: lines_longer_than_80_chars
'PermissionActions on Permission: get shouldShowRequestRationale should return true when on android',
() async {
final mockPermissionHandlerPlatform = PermissionHandlerPlatform.instance;
when(mockPermissionHandlerPlatform
.shouldShowRequestPermissionRationale(Permission.calendar))
.thenAnswer((_) => Future.value(true));
await Permission.calendar.shouldShowRequestRationale;
verify(mockPermissionHandlerPlatform
.shouldShowRequestPermissionRationale(Permission.calendar))
.called(1);
});
test('PermissionActions on Permission: request()', () async {
final permissionRequest = Permission.calendar.request();
expect(permissionRequest, isA<Future<PermissionStatus>>());
});
test('PermissionCheckShortcuts on Permission: get isGranted', () async {
final isGranted = await Permission.calendar.isGranted;
expect(isGranted, true);
});
test('PermissionCheckShortcuts on Permission: get isDenied', () async {
final isDenied = await Permission.calendar.isDenied;
expect(isDenied, false);
});
test('PermissionCheckShortcuts on Permission: get isRestricted', () async {
final isRestricted = await Permission.calendar.isRestricted;
expect(isRestricted, false);
});
test('PermissionCheckShortcuts on Permission: get isLimited', () async {
final isLimited = await Permission.calendar.isLimited;
expect(isLimited, false);
});
test('PermissionCheckShortcuts on Permission: get isPermanentlyDenied',
() async {
final isPermanentlyDenied = await Permission.calendar.isPermanentlyDenied;
expect(isPermanentlyDenied, false);
});
test(
// ignore: lines_longer_than_80_chars
'ServicePermissionActions on PermissionWithService: get ServiceStatus returns the right service status',
() async {
var serviceStatus = await Permission.phone.serviceStatus;
expect(serviceStatus, ServiceStatus.enabled);
});
test(
// ignore: lines_longer_than_80_chars
'PermissionListActions on List<Permission>: request() on a list returns a Map<Permission, PermissionStatus>',
() async {
var permissionList = <Permission>[];
final permissionMap = await permissionList.request();
expect(permissionMap, isA<Map<Permission, PermissionStatus>>());
});
});
}
class MockPermissionHandlerPlatform extends Mock
with
// ignore: prefer_mixin
MockPlatformInterfaceMixin
implements
PermissionHandlerPlatform {
@override
Future<PermissionStatus> checkPermissionStatus(Permission permission) =>
Future.value(PermissionStatus.granted);
@override
Future<ServiceStatus> checkServiceStatus(Permission permission) =>
Future.value(ServiceStatus.enabled);
@override
Future<bool> openAppSettings() => Future.value(true);
@override
Future<Map<Permission, PermissionStatus>> requestPermissions(
List<Permission> permissions) {
var permissionsMap = <Permission, PermissionStatus>{};
return Future.value(permissionsMap);
}
@override
Future<bool> shouldShowRequestPermissionRationale(Permission? permission) {
return super.noSuchMethod(
Invocation.method(
#shouldShowPermissionRationale,
[permission],
),
returnValue: Future.value(true),
);
}
}
## 3.3.0
* Added support for system alert window permission.
## 3.2.0
* Added support for manage external storage permission available on Android 10 and up.
## 3.1.3
* Implemented equality operator for `Permission` class;
* Reverted services status check for notification permission. Turns out implementation does not fit with idea's of permission_handler plugin.
## 3.1.2
* Allow checking serviceStatus for notification permission.
## 3.1.1
* Fixed conversion issue where `PermissionStatus.denied` was not translated to the correct index.
* Added unit-tests to guard API against breaking changes.
## 3.1.0
* Added support for bluetooth permissions.
## 3.0.0+1
* **BREAKING**: Removed PermissionStatus.undetermined. This is now replaced by PermissionStatus.denied.
## 3.0.0
* Migrated to null safety.
## 2.0.2
* Added support for the limited photos permission available on iOS 14 and up.
## 2.0.1
* Update `platform_interface 1.0.2`
* Fix bug which allows requesting is the device has phone capabilities.
## 2.0.0
- **BREAKING**: Created 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 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/platform_interface_package/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 request 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
\ No newline at end of file
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/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].
Future<PermissionStatus> checkPermissionStatus(Permission permission) async {
final status = await _methodChannel.invokeMethod(
'checkPermissionStatus', permission.value);
return Codec.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.
Future<ServiceStatus> checkServiceStatus(Permission permission) async {
final status = await _methodChannel.invokeMethod(
'checkServiceStatus', permission.value);
return Codec.decodeServiceStatus(status);
}
/// Opens the app settings page.
///
/// Returns [true] if the app settings page could be opened, otherwise
/// [false].
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].
Future<Map<Permission, PermissionStatus>> requestPermissions(
List<Permission> permissions) async {
final data = Codec.encodePermissions(permissions);
final status =
await _methodChannel.invokeMethod('requestPermissions', data);
return Codec.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].
Future<bool> shouldShowRequestPermissionRationale(
Permission permission) async {
final shouldShowRationale = await _methodChannel.invokeMethod(
'shouldShowRequestPermissionRationale', permission.value);
return shouldShowRationale ?? false;
}
}
import '../../../permission_handler_platform_interface.dart';
/// Provides utility methods for encoding messages that are sent on the Flutter
/// message channel.
class Codec {
/// Converts the given [value] into a [PermissionStatus] instance.
static PermissionStatus decodePermissionStatus(int value) {
return PermissionStatusValue.statusByValue(value);
}
/// Converts the given [value] into a [ServiceStatus] instance.
static 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.
static 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.
static 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.
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,
///User has authorized this application for limited access.
/// *Only supported on iOS (iOS14+).*
limited,
/// The user denied access to the requested feature and selected to never
/// again show a request for this permission. The user may still change the
/// permission status in the settings.
/// *Only supported on Android.*
permanentlyDenied,
}
extension PermissionStatusValue on PermissionStatus {
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;
default:
throw UnimplementedError();
}
}
static PermissionStatus statusByValue(int value) {
return [
PermissionStatus.denied,
PermissionStatus.granted,
PermissionStatus.restricted,
PermissionStatus.limited,
PermissionStatus.permanentlyDenied,
][value];
}
}
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 user denied access to the requested feature and selected to never
/// again show a request for this permission. The user may still change the
/// permission status in the settings.
/// *Only supported on Android.*
bool get isPermanentlyDenied => this == PermissionStatus.permanentlyDenied;
bool get isLimited => this == PermissionStatus.limited;
}
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 user denied access to the requested feature and selected to never
/// again show a request for this permission. The user may still change the
/// permission status in the settings.
/// *Only supported on Android.*
Future<bool> get isPermanentlyDenied async =>
(await this).isPermanentlyDenied;
Future<bool> get isLimited async => (await this).isLimited;
}
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);
@visibleForTesting
const PermissionWithService.private(int value) : super._(value);
}
/// Defines the permissions which can be checked and requested.
@immutable
class Permission {
const Permission._(this.value);
factory Permission.byValue(int value) => values[value];
/// Integer representation of the [Permission].
final int value;
/// Android: Calendar
/// iOS: Calendar (Events)
static const calendar = Permission._(0);
/// Android: Camera
/// iOS: Photos (Camera Roll and Camera)
static const camera = Permission._(1);
/// Android: Contacts
/// iOS: AddressBook
static const contacts = Permission._(2);
/// Android: Fine and Coarse Location
/// iOS: CoreLocation (Always and WhenInUse)
static const location = PermissionWithService._(3);
/// Android:
/// When running on Android < Q: Fine and Coarse Location
/// When running on Android Q and above: Background Location Permission
/// iOS: CoreLocation - Always
static const locationAlways = PermissionWithService._(4);
/// Android: Fine and Coarse Location
/// iOS: CoreLocation - WhenInUse
static const locationWhenInUse = PermissionWithService._(5);
/// Android: None
/// iOS: MPMediaLibrary
static const mediaLibrary = Permission._(6);
/// Android: Microphone
/// iOS: Microphone
static const microphone = Permission._(7);
/// Android: Phone
/// iOS: Nothing
static const phone = PermissionWithService._(8);
/// Android: Nothing
/// iOS: Photos
/// iOS 14+ read & write access level
static const photos = Permission._(9);
/// Android: Nothing
/// iOS: Photos
/// iOS 14+ read & write access level
static const photosAddOnly = Permission._(10);
/// Android: Nothing
/// iOS: Reminders
static const reminders = Permission._(11);
/// Android: Body Sensors
/// iOS: CoreMotion
static const sensors = Permission._(12);
/// Android: Sms
/// iOS: Nothing
static const sms = Permission._(13);
/// Android: Microphone
/// iOS: Speech
static const speech = Permission._(14);
/// Android: External Storage
/// iOS: Access to folders like `Documents` or `Downloads`. Implicitly
/// granted.
static const storage = Permission._(15);
/// Android: Ignore Battery Optimizations
static const ignoreBatteryOptimizations = Permission._(16);
/// Android: Notification
/// iOS: Notification
static const notification = Permission._(17);
/// Android: Allows an application to access any geographic locations
/// persisted in the user's shared collection.
static const accessMediaLocation = Permission._(18);
/// When running on Android Q and above: Activity Recognition
/// When running on Android < Q: Nothing
/// iOS: Nothing
static const activityRecognition = Permission._(19);
/// The unknown only used for return type, never requested
static const unknown = Permission._(20);
/// iOS 13 and above: The authorization state of Core Bluetooth manager.
/// When running < iOS 13 or Android this is always allowed.
static const bluetooth = Permission._(21);
/// Android: Allows an application a broad access to external storage in
/// scoped storage.
/// iOS: Nothing
///
/// 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);
///Android: Allows an app to create windows shown on top of all other apps
///iOS: Nothing
static const systemAlertWindow = Permission._(23);
/// Returns a list of all possible [PermissionGroup] values.
static const List<Permission> values = <Permission>[
calendar,
camera,
contacts,
location,
locationAlways,
locationWhenInUse,
mediaLibrary,
microphone,
phone,
photos,
photosAddOnly,
reminders,
sensors,
sms,
speech,
storage,
ignoreBatteryOptimizations,
notification,
accessMediaLocation,
activityRecognition,
unknown,
bluetooth,
manageExternalStorage,
systemAlertWindow
];
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'
];
@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;
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,
}
extension ServiceStatusValue on ServiceStatus {
int get value {
switch (this) {
case ServiceStatus.disabled:
return 0;
case ServiceStatus.enabled:
return 1;
case ServiceStatus.notApplicable:
return 2;
default:
throw UnimplementedError();
}
}
static ServiceStatus statusByValue(int value) {
return [
ServiceStatus.disabled,
ServiceStatus.enabled,
ServiceStatus.notApplicable,
][value];
}
}
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;
}
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: 3.3.0
dependencies:
flutter:
sdk: flutter
meta: ^1.0.5
plugin_platform_interface: ^2.0.0
dev_dependencies:
flutter_test:
sdk: flutter
mockito: ^5.0.0
effective_dart: ^1.3.0
environment:
sdk: ">=2.12.0 <3.0.0"
flutter: ">=1.22.0"
import 'package:flutter/services.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) {
methodChannel.setMockMethodCallHandler(_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.calendar, Permission.camera, Permission.contacts});
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.calendar);
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.calendar);
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.calendar);
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.calendar);
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.calendar);
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.calendar);
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.calendar);
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.calendar);
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(Codec.decodePermissionStatus(0), PermissionStatus.denied);
});
test('decodeServiceStatus should a corresponding ServiceStatus', () {
expect(Codec.decodeServiceStatus(0), ServiceStatus.disabled);
});
test(
'decodePermissionRequestResult should convert a map<int, int>'
'to map<Permission, PermissionStatus>', () {
var value = <int, int>{
1: 1,
};
var permissionMap = Codec.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 = Codec.encodePermissions(permissions);
expect(integers.first, isA<int>());
});
});
}
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 'package:mockito/mockito.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();
}, throwsNoSuchMethodError);
});
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('PermissionSatus', () {
test('PermissionStatus should contain 5 options', () {
final values = PermissionStatus.values;
expect(values.length, 5);
});
test('PermissionStatus enum should have items in correct index', () {
final 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);
});
});
group('PermissionStatusValue', () {
test('PermissonStatusValue 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);
});
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);
});
});
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);
});
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);
});
});
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 PermissionGroup values',
() {
final values = Permission.values;
expect(values.length, 24);
});
test('check if byValue returns corresponding PermissionGroup value', () {
final 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', () {
var permissionWithService = PermissionWithService.private(0);
var permissionName = permissionWithService.toString();
expect(permissionName, 'Permission.calendar');
});
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', () {
final values = ServiceStatus.values;
expect(values.length, 3);
});
test('ServiceStatus enum should have items in correct index', () {
final 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);
});
});
}
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