From eab20d377c9c0833a04e3d01a7299090f47a8f5a Mon Sep 17 00:00:00 2001 From: Yann Cabral Date: Thu, 22 Oct 2026 20:09:50 -0300 Subject: [PATCH] feat: expand settings APIs and improve platform reliability --- .github/workflows/publish.yml | 182 ++++++++--- CHANGELOG.md | 17 + README.md | 302 ++++++++++-------- analysis_options.yaml | 5 + android/build.gradle | 51 ++- .../OpenSettingsPlusPlugin.kt | 231 ++++++++------ .../OpenSettingsPlusPluginTest.kt | 165 ++++++++++ example/analysis_options.yaml | 5 + example/android/app/build.gradle | 5 +- example/lib/main.dart | 18 +- example/pubspec.lock | 30 +- example/test/widget_test.dart | 22 +- .../OpenSettingsPlusPlugin.swift | 109 ++++++- .../open_settings_plus_method_channel.dart | 64 ++++ ...open_settings_plus_platform_interface.dart | 34 ++ lib/core/open_settings_plus.dart | 82 ++++- lib/core/open_settings_plus_android.dart | 138 +++++--- lib/core/open_settings_plus_ios.dart | 24 +- lib/core/settings_open_result.dart | 18 ++ lib/core/settings_target.dart | 21 ++ lib/open_settings_plus.dart | 2 + test/native_ios/main.swift | 118 +++++++ test/open_settings_plus_test.dart | 26 +- test/settings_facade_test.dart | 142 ++++++++ test/settings_names_test.dart | 96 ++++++ test/settings_open_result_test.dart | 144 +++++++++ tool/test_native_ios.sh | 35 ++ 27 files changed, 1712 insertions(+), 374 deletions(-) create mode 100644 android/src/test/kotlin/br/com/yanncabral/open_settings_plus/OpenSettingsPlusPluginTest.kt create mode 100644 lib/core/settings_open_result.dart create mode 100644 lib/core/settings_target.dart create mode 100644 test/native_ios/main.swift create mode 100644 test/settings_facade_test.dart create mode 100644 test/settings_names_test.dart create mode 100644 test/settings_open_result_test.dart create mode 100755 tool/test_native_ios.sh diff --git a/.github/workflows/publish.yml b/.github/workflows/publish.yml index adc6c67..76189e7 100644 --- a/.github/workflows/publish.yml +++ b/.github/workflows/publish.yml @@ -2,59 +2,161 @@ name: Validate and publish on: push: - branches: - - 'main' - tags: - - 'v[0-9]+.[0-9]+.[0-9]+*' + branches: [main] + tags: ['v[0-9]+.[0-9]+.[0-9]+*'] pull_request: - branches: - - 'main' + branches: [main] + +permissions: + contents: read jobs: - validate-and-publish: - permissions: - id-token: write - runs-on: macos-latest + validate: + runs-on: ubuntu-latest + strategy: + fail-fast: false + matrix: + flutter: ['3.41.0', 'stable'] steps: - - name: ๐Ÿ“š Git Checkout - uses: actions/checkout@v4 + - uses: actions/checkout@v4 + - uses: subosito/flutter-action@v2 + with: + channel: stable + flutter-version: ${{ matrix.flutter == 'stable' && '' || matrix.flutter }} + cache: true + - run: flutter --version + - run: flutter pub get + - run: dart format --output=none --set-exit-if-changed . + - run: dart analyze --fatal-infos --fatal-warnings . + - run: flutter test + - name: Test example + run: flutter test + working-directory: example - - name: ๐Ÿฆ Setup Flutter - uses: subosito/flutter-action@v2 + android: + runs-on: ubuntu-latest + strategy: + fail-fast: false + matrix: + include: + - agp: '8.13.2' + gradle: '8.13' + built-in-kotlin: 'false' + flutter: '3.41.0' + - agp: '9.0.1' + gradle: '9.1.0' + built-in-kotlin: 'false' + flutter: '3.44.1' + - agp: '9.0.1' + gradle: '9.1.0' + built-in-kotlin: 'true' + flutter: 'stable' + - agp: '9.0.1' + gradle: '9.1.0' + built-in-kotlin: 'default' + flutter: 'stable' + steps: + - uses: actions/checkout@v4 + - uses: actions/setup-java@v4 + with: + distribution: temurin + java-version: '17' + - uses: android-actions/setup-android@v3 + - uses: subosito/flutter-action@v2 with: channel: stable + flutter-version: ${{ matrix.flutter == 'stable' && '' || matrix.flutter }} cache: true + - run: sdkmanager 'platforms;android-36' 'build-tools;36.0.0' 'ndk;27.0.12077973' + - name: Configure consumer compatibility matrix + env: + TEST_AGP: ${{ matrix.agp }} + TEST_GRADLE: ${{ matrix.gradle }} + TEST_BUILT_IN_KOTLIN: ${{ matrix.built-in-kotlin }} + run: | + python3 - <<'PY' + import os + from pathlib import Path + android = Path('example/android') + settings = android / 'settings.gradle' + settings.write_text(settings.read_text().replace('8.13.2', os.environ['TEST_AGP'])) + wrapper = android / 'gradle/wrapper/gradle-wrapper.properties' + wrapper.write_text(wrapper.read_text().replace('gradle-8.13-all', 'gradle-' + os.environ['TEST_GRADLE'] + '-all')) + kotlin_setting = os.environ['TEST_BUILT_IN_KOTLIN'] + built_in = int(os.environ['TEST_AGP'].split('.')[0]) >= 9 and kotlin_setting != 'false' + if os.environ['TEST_AGP'].startswith('9.'): + with (android / 'gradle.properties').open('a') as properties: + if kotlin_setting != 'default': + properties.write('\nandroid.builtInKotlin=' + str(built_in).lower() + '\n') + properties.write('\nandroid.newDsl=false\n') + if built_in: + app = android / 'app/build.gradle' + app.write_text(app.read_text().replace(' id "kotlin-android"\n', '').replace(" kotlinOptions {\n jvmTarget = '11'\n }\n", '') + '\nkotlin { compilerOptions { jvmTarget = org.jetbrains.kotlin.gradle.dsl.JvmTarget.JVM_11 } }\n') + PY + - run: flutter pub get + - name: Build Android consumer + run: flutter build apk --debug + working-directory: example + - name: Test native Android intent routing + if: matrix.agp == '8.13.2' + run: ./gradlew :open_settings_plus:testDebugUnitTest + working-directory: example/android - - name: ๐Ÿ”Ž Show tool versions + ios: + runs-on: macos-latest + strategy: + fail-fast: false + matrix: + integration: [swift-package-manager, cocoapods] + steps: + - uses: actions/checkout@v4 + - uses: subosito/flutter-action@v2 + with: + channel: stable + cache: true + - name: Show tool versions run: | flutter --version - dart --version xcodebuild -version pod --version - - - name: ๐Ÿ“ฆ Install Dependencies - run: flutter pub get - - - name: โœจ Check Formatting - run: dart format --set-exit-if-changed . - - - name: ๐Ÿ•ต๏ธ Analyze - run: dart analyze --fatal-infos --fatal-warnings . - - - name: ๐Ÿงช Test - run: flutter test - - - name: ๐ŸŽ Validate iOS example with Swift Package Manager + - name: Select Apple dependency manager + env: + INTEGRATION: ${{ matrix.integration }} run: | - flutter config --enable-swift-package-manager - flutter pub get - flutter build ios --no-codesign --verbose + if [ "$INTEGRATION" = 'cocoapods' ]; then + # The project's pubspec setting takes precedence over global config. + python3 - <<'PY' + from pathlib import Path + pubspec = Path('example/pubspec.yaml') + pubspec.write_text(pubspec.read_text().replace('enable-swift-package-manager: true', 'enable-swift-package-manager: false')) + PY + flutter config --no-enable-swift-package-manager + else + flutter config --enable-swift-package-manager + fi + - run: flutter pub get + - name: Test native iOS settings routing + if: matrix.integration == 'swift-package-manager' + run: | + flutter precache --ios + bash tool/test_native_ios.sh + - name: Build iOS consumer + run: flutter build ios --no-codesign working-directory: example - - name: ๐ŸŽฏ Setup Dart for pub.dev publishing - if: startsWith(github.ref, 'refs/tags/v') - uses: dart-lang/setup-dart@v1 - - - name: ๐Ÿš€ Publish - if: startsWith(github.ref, 'refs/tags/v') - run: dart pub publish --force + publish: + if: startsWith(github.ref, 'refs/tags/v') + needs: [validate, android, ios] + permissions: + contents: read + id-token: write + runs-on: ubuntu-latest + steps: + - uses: actions/checkout@v4 + - uses: subosito/flutter-action@v2 + with: + channel: stable + cache: true + - uses: dart-lang/setup-dart@v1 + - run: flutter pub get + - run: dart pub publish --force diff --git a/CHANGELOG.md b/CHANGELOG.md index 18cfc86..0f43beb 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -1,3 +1,20 @@ +## Unreleased + +- Fix iOS method-channel calls that never completed; report URL launch outcomes. +- Add public iOS notification settings routing and configurable detailed fallback. +- Add `SettingsOpenResult`, `SettingsTarget`, the shared `OpenSettingsPlus.open()` + API and detailed native target opening without removing existing bool APIs. +- Add explicit `currentAppSettings()` and Android `allAppSettings()` names; + deprecate ambiguous aliases while preserving their destinations. +- Route Android intents and panels through the platform interface; support + Activity-aware task placement, Android 10+ panels, app language, exact alarm + access and VPN settings. Correct app-specific intent routing and fallback. +- Add native iOS completion/fallback regression tests and expand Dart coverage. +- Align Android builds with SDK 36, AGP 8.13.2 and Kotlin 2.2.10, with conditional + support for AGP 9 built-in Kotlin. Keep Flutter 3.41/Dart 3.11 lower bounds. +- Validate Android consumer configurations and both Apple dependency managers in + CI; document supported iOS destinations separately from experimental URLs. + ## 0.5.1 ### ๐Ÿ”ง Bug Fixes diff --git a/README.md b/README.md index 55e8235..3efa615 100644 --- a/README.md +++ b/README.md @@ -1,140 +1,188 @@ -# `open_settings_plus` +# open_settings_plus -A comprehensive Flutter plugin to seamlessly navigate to various settings screens on both iOS and Android devices, ensuring compatibility with the latest versions of both platforms. +Open Android and iOS settings from Flutter, with platform-specific shortcuts and +explicit results for fallback, unsupported destinations and launch failures. -## Known Issues +## Installation -We are aware that the shortcuts in open_settings_plus are not functioning properly on the latest versions of iOS 18. This issue is currently under investigation, but progress has been challenging due to the lack of documentation or online resources regarding the new URL schemes. +```sh +flutter pub add open_settings_plus +``` -A fix is being actively worked on and will be released as soon as possible. +Requires Flutter 3.41+ and Dart 3.11+. Both CocoaPods and Swift Package Manager +(SPM) are supported. The plugin declares iOS 12.0 as its minimum; the Flutter SDK +and its engine can require a newer deployment target for the consuming app. +SPM integration must be enabled in projects using it. -## ๐Ÿ“ฆ Installation +## Common destinations -Add `open_settings_plus` to your `pubspec.yaml` as usual. On iOS, the plugin supports both CocoaPods and Swift Package Manager (SPM). CocoaPods remains supported for existing Flutter projects, while SPM is available when using Flutter `3.41.0` or newer with Flutter's Swift Package Manager integration enabled. The iOS deployment target is `12.0`. +```dart +import 'package:open_settings_plus/open_settings_plus.dart'; + +final result = await OpenSettingsPlus.open(SettingsTarget.appSettings); + +switch (result) { + case SettingsOpenResult.opened: + // The OS accepted the requested destination. + break; + case SettingsOpenResult.fallbackOpened: + // The requested destination was unavailable; this app's settings opened. + break; + case SettingsOpenResult.unsupported: + // No supported destination or implementation is available. + break; + case SettingsOpenResult.failed: + // Opening failed, including any attempted fallback. + break; +} +``` -## ๐Ÿš€ Usage +`SettingsTarget` includes `appSettings`, `notifications`, `wifi`, `bluetooth` +and `location`. The shared API selects the current platform without a switch. +Opening a screen does **not** confirm that a permission or preference changed. +Recheck the relevant permission when your app resumes. -To integrate `open_settings_plus` into your project, add it as a dependency in your `pubspec.yaml` file. +| Destination | Android | iOS | +| --- | --- | --- | +| This app's settings | App details | Public app settings URL | +| This app's notifications | App notification settings, with legacy extras | Public notification URL on iOS 15.4+ | +| Wi-Fi, Bluetooth, location | System settings | App settings fallback; no public direct destination | +| Other platforms | `unsupported` | `unsupported` | + +Fallback is enabled by default. To require the requested destination: ```dart -import 'package:flutter/material.dart'; -import 'package:open_settings_plus/open_settings_plus.dart'; +final result = await OpenSettingsPlus.open( + SettingsTarget.wifi, + fallbackToAppSettings: false, +); +``` + +On iOS this returns `unsupported` without opening an experimental URL. On Android, +the result also depends on OS version, hardware and the manufacturer's settings app. + +## Platform-specific APIs + +```dart +const android = OpenSettingsPlusAndroid(); +await android.currentAppSettings(); // This app's details. +await android.allAppSettings(); // List of installed apps. +await android.appNotification(); +await android.openByDefault(); + +const ios = OpenSettingsPlusIOS(); +await ios.currentAppSettings(); +await ios.appNotification(); // App settings fallback before iOS 15.4. +``` + +Existing shortcuts still return `Future`. `true` means a launch was accepted +and can include a fallback. For a detailed result use `openTarget(...)` on a +platform instance or `openSettingsTarget(...)` with a native action/URL. + +Android's legacy `appSettings()` and `applicationSettings()` still open the app +list; both are deprecated in favor of `allAppSettings()`. iOS `appSettings()` +remains an alias of `currentAppSettings()`. `applicationDetails()` remains +available on Android. These aliases preserve their previous destinations. + +### Android panels and additional destinations + +```dart +const android = OpenSettingsPlusAndroid(); -void main() => runApp(MaterialApp( - home: Scaffold( - body: Center( - child: ElevatedButton( - onPressed: () { - switch (OpenSettingsPlus.shared) { - OpenSettingsPlusAndroid settings => settings.wifi(), - OpenSettingsPlusIOS settings => settings.wifi(), - _ => throw Exception('Platform not supported'), - } - }, - child: Text('Wi-Fi Settings'), - ), - ), - ), - ) - ); +final panelResult = await android.openPanel(AndroidSettingsPanel.volume); +await android.appLocale(); +await android.exactAlarm(); +await android.vpn(); ``` -For more examples and use-cases, refer to the `example` directory. - -## ๐ŸŒŸ Features - -### Android: - -Navigate directly to: - -- Wi-Fi -- Data Roaming -- Location Source -- App Settings -- Bluetooth -- Notifications -- Security -- Sound -- Display -- Date & Time -- Device Information -- Internal Storage -- Memory Card -- Accessibility -- Add Account -- Airplane Mode -- APN Settings -- Application Details -- Application Development -- Application Notifications -- Open by Default -- Application Write Settings -- Battery Saver -- Captioning -- Cast -- Data Usage -- Mobile Hotspot & Tethering -- App Notification Bubble -- Search -- Biometric Enrollment -- Hardware Keyboard -- Home -- Ignore Background Data Restrictions -- Ignore Battery Optimization -- Input Method -- Locale -- Manage All Applications -- Manage External Sources -- Manage Overlay - ... and more features being added regularly! - -### iOS: - -Navigate directly to: - -- Wi-Fi -- General Settings -- About -- Accessibility -- Account Settings -- Auto Lock -- Battery -- Bluetooth -- Date & Time -- Face ID & Passcode -- Cellular -- Dictionary -- Display & Brightness -- FaceTime -- General -- HealthKit -- iCloud -- Music -- Keyboard -- Language & Region -- Location Services -- Personal Hotspot -- Phone -- Photos & Camera -- Privacy -- Profiles & Device Management -- Software Update -- Storage & Backup -- Siri -- Sounds & Haptics - ... and more features being added regularly! - -## ๐Ÿ™ Acknowledgments - -This package was innovatively crafted by [Yann Cabral](https://github.com/yanncabral). It was inspired by the fantastic work of [Ali Hoseinpoor](https://github.com/AliHoseinpoor/open_settings), aiming to overcome certain limitations. - -## ๐Ÿž Bugs or Feature Requests - -Encountered an issue or have a feature in mind? We'd love to hear from you! - -- Report issues or seek features [here](https://github.com/yanncabral/open_settings_plus/issues/new). -- Contributions via pull requests are always welcome! - ---- - -This revised README provides a more structured and polished presentation of the plugin's features and usage. +| API | Availability | Older or unavailable devices | +| --- | --- | --- | +| `openPanel(...)` | Android 10+ | `unsupported`; no fallback | +| `appLocale()` | Android 13+ | App details fallback | +| `exactAlarm()` | Android 12+ | App details fallback | +| `vpn()` | System VPN screen, including legacy Android route | Returns `false` if unavailable | + +Panels include `wifi`, `internetConnectivity`, `nfc` and `volume`. Per-app language +selection requires the app to declare supported languages. Exact alarm access +requires the appropriate app manifest configuration, such as +`SCHEDULE_EXACT_ALARM`; opening the screen does not grant access. + +Raw actions remain available, with package scoping when needed: + +```dart +await android.sendAndroidAppIntent( + 'android.settings.APP_LOCALE_SETTINGS', + asAnotherTask: false, +); + +final result = await android.openSettingsTarget( + 'android.settings.APP_LOCALE_SETTINGS', + appSpecific: true, + fallbackToAppSettings: false, +); +``` + +Legacy intents open a separate task by default. Set `asAnotherTask: false` to use +the attached Activity. Panels default to the attached Activity. Without one, +Android requires a new task. All Android routing goes through the platform +interface, so custom implementations and test doubles can intercept it. + +### Experimental iOS shortcuts + +Methods such as `wifi()`, `bluetooth()`, `general()` and `privacy()` use undocumented +`App-prefs:` URL schemes. Their availability and exact destination vary by iOS +release; known failures include iOS 18. They are best effort and are not covered +by the supported-destination promises of the shared API. Even an accepted URL +does not prove that iOS displayed the requested section. + +Legacy shortcuts preserve their existing behavior. To opt into an app-settings +fallback and inspect its result: + +```dart +const ios = OpenSettingsPlusIOS(); +final result = await ios.openSettingsTarget('App-prefs:WIFI'); +``` + +Prefer `currentAppSettings()`, `appNotification()` or the shared API for public +iOS destinations. Notification routing uses the official constants for iOS +15.4โ€“15.x and iOS 16+; older versions use the configured app-settings fallback. + +## Compatibility and verification + +Android compilation uses SDK 36, Kotlin 2.2.10 and Java 11 bytecode. The example +uses AGP 8.13.2 with Gradle 8.13; building it requires JDK 17. AGP 9 consumers using +legacy Kotlin require Flutter 3.44+; consumers using built-in Kotlin (the AGP 9 +default, or `android.builtInKotlin=true`) require Flutter 3.47+. The CI AGP 9 matrix uses +`android.newDsl=false`; it does not certify the new AGP DSL. + +The CI workflow checks the minimum and stable Flutter versions, Dart analysis +and tests, Android AGP 8/9 consumer builds, and iOS builds with both SPM and +CocoaPods. Native iOS regression tests compile the production plugin against +real UIKit and Flutter on a simulator, injecting URL launch outcomes to verify +completion and fallback. They do not certify every experimental settings URL +on every OS version. + +```sh +flutter pub get +flutter test +dart analyze --fatal-infos --fatal-warnings . +# macOS with Xcode, Flutter iOS artifacts and an installed iOS simulator: +flutter precache --ios +bash tool/test_native_ios.sh +# With Android SDK/JDK installed, after building the example: +cd example/android +./gradlew :open_settings_plus:testDebugUnitTest +``` + +See [the example](example/lib/main.dart) for the full shortcut catalog. Unsupported +hardware or vendor-specific settings can still prevent an Android action from +opening. macOS, Windows, Linux and web are not implemented by this plugin. + +## Contributing + +Report bugs and propose features in the +[issue tracker](https://github.com/yanncabral/open_settings_plus/issues/new). +Include the target API, OS version, device and observed result. + +Created by [Yann Cabral](https://github.com/yanncabral), inspired by +[Ali Hoseinpoor's open_settings](https://github.com/AliHoseinpoor/open_settings). diff --git a/analysis_options.yaml b/analysis_options.yaml index 9df80aa..b273948 100644 --- a/analysis_options.yaml +++ b/analysis_options.yaml @@ -1 +1,6 @@ +analyzer: + exclude: + - build/** + - android/** + - ios/** include: package:very_good_analysis/analysis_options.yaml diff --git a/android/build.gradle b/android/build.gradle index 58e3336..5a3b890 100644 --- a/android/build.gradle +++ b/android/build.gradle @@ -2,14 +2,14 @@ group 'br.com.yanncabral.open_settings_plus' version '1.0-SNAPSHOT' buildscript { - ext.kotlin_version = '1.8.20' + ext.kotlin_version = '2.2.10' repositories { google() mavenCentral() } dependencies { - classpath 'com.android.tools.build:gradle:8.2.1' + classpath 'com.android.tools.build:gradle:8.13.2' classpath "org.jetbrains.kotlin:kotlin-gradle-plugin:$kotlin_version" } } @@ -22,33 +22,54 @@ allprojects { } apply plugin: 'com.android.library' -apply plugin: 'kotlin-android' +// Match AGP / Flutter: built-in Kotlin defaults to enabled on AGP 9+, while +// consumers may explicitly disable it to keep using the legacy Kotlin plugin. +def agpMajorVersion = com.android.Version.ANDROID_GRADLE_PLUGIN_VERSION.tokenize('.')[0].toInteger() +def builtInKotlinProperty = project.findProperty('android.builtInKotlin') +def builtInKotlinEnabled = agpMajorVersion >= 9 && + (builtInKotlinProperty == null || builtInKotlinProperty.toString().toBoolean()) +if (!builtInKotlinEnabled) { + apply plugin: 'kotlin-android' +} android { - // Conditional for compatibility with AGP <4.2. - if (project.android.hasProperty("namespace")) { - namespace "br.com.yanncabral.open_settings_plus" - } -// Conditional for compatibility with AGP <4.2. - if (project.android.hasProperty("testNamespace")) { - testNamespace "br.com.yanncabral.open_settings_plus.test" - } - compileSdkVersion 34 + namespace "br.com.yanncabral.open_settings_plus" + testNamespace "br.com.yanncabral.open_settings_plus.test" + compileSdk = 36 compileOptions { sourceCompatibility JavaVersion.VERSION_11 targetCompatibility JavaVersion.VERSION_11 } - kotlinOptions { - jvmTarget = '11' + if (!builtInKotlinEnabled) { + kotlinOptions { + jvmTarget = '11' + } } sourceSets { main.java.srcDirs += 'src/main/kotlin' } + testOptions { + unitTests.includeAndroidResources = true + } + defaultConfig { - minSdkVersion 16 + minSdk = 16 } } + +if (builtInKotlinEnabled) { + kotlin { + compilerOptions { + jvmTarget = org.jetbrains.kotlin.gradle.dsl.JvmTarget.JVM_11 + } + } +} + +dependencies { + testImplementation 'junit:junit:4.13.2' + testImplementation 'org.robolectric:robolectric:4.14.1' +} diff --git a/android/src/main/kotlin/br/com/yanncabral/open_settings_plus/OpenSettingsPlusPlugin.kt b/android/src/main/kotlin/br/com/yanncabral/open_settings_plus/OpenSettingsPlusPlugin.kt index 52f071c..35b5bc1 100644 --- a/android/src/main/kotlin/br/com/yanncabral/open_settings_plus/OpenSettingsPlusPlugin.kt +++ b/android/src/main/kotlin/br/com/yanncabral/open_settings_plus/OpenSettingsPlusPlugin.kt @@ -1,137 +1,180 @@ package br.com.yanncabral.open_settings_plus -import androidx.annotation.NonNull +import android.app.Activity +import android.content.ActivityNotFoundException import android.content.Context import android.content.Intent import android.net.Uri - +import android.os.Build 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.MethodCall import io.flutter.plugin.common.MethodChannel import io.flutter.plugin.common.MethodChannel.MethodCallHandler import io.flutter.plugin.common.MethodChannel.Result -/** OpenSettingsPlusPlugin */ -class OpenSettingsPlusPlugin: FlutterPlugin, MethodCallHandler { - private lateinit var mContext : Context - /// The MethodChannel that will the communication between Flutter and native Android - /// - /// This local reference serves to register the plugin with the Flutter Engine and unregister it - /// when the Flutter Engine is detached from the Activity - private lateinit var channel : MethodChannel - - override fun onAttachedToEngine(@NonNull flutterPluginBinding: FlutterPlugin.FlutterPluginBinding) { - channel = MethodChannel(flutterPluginBinding.binaryMessenger, "open_settings_plus") +/** Opens settings without treating a launch as confirmation of a permission change. */ +class OpenSettingsPlusPlugin : FlutterPlugin, MethodCallHandler, ActivityAware { + private lateinit var mContext: Context + private lateinit var channel: MethodChannel + private var activity: Activity? = null + + override fun onAttachedToEngine(binding: FlutterPlugin.FlutterPluginBinding) { + channel = MethodChannel(binding.binaryMessenger, "open_settings_plus") channel.setMethodCallHandler(this) - mContext = flutterPluginBinding.getApplicationContext(); + mContext = binding.applicationContext } - private fun normalizeTarget(target: String): String { - return when (target) { - "android.settings.APPLICATION_NOTIFICATION_SETTINGS" -> { - "android.settings.APP_NOTIFICATION_SETTINGS" - } - else -> target - } + private fun normalizeTarget(target: String): String = when (target) { + "android.settings.APPLICATION_NOTIFICATION_SETTINGS" -> "android.settings.APP_NOTIFICATION_SETTINGS" + "android.settings.APPLICATION_WRITE_SETTINGS" -> "android.settings.action.MANAGE_WRITE_SETTINGS" + "android.settings.MANAGE_EXTERNAL_SOURCES_SETTINGS" -> "android.settings.MANAGE_UNKNOWN_APP_SOURCES" + "android.settings.VPN_SETTINGS" -> if (Build.VERSION.SDK_INT < 24) "android.net.vpn.SETTINGS" else target + else -> target } - private fun openSettings(target: String): Boolean { - val normalizedTarget = normalizeTarget(target) - val intent = Intent(normalizedTarget) - if (intent.action == null) return false - intent.flags = Intent.FLAG_ACTIVITY_NEW_TASK - return startIntentSafely(intent) + private fun requiresPackage(target: String): Boolean = when (target) { + "android.settings.APPLICATION_DETAILS_SETTINGS", + "android.settings.APP_NOTIFICATION_SETTINGS", + "android.settings.APP_NOTIFICATION_BUBBLE_SETTINGS", + "android.settings.APP_OPEN_BY_DEFAULT_SETTINGS", + "android.settings.action.MANAGE_WRITE_SETTINGS", + "android.settings.IGNORE_BACKGROUND_DATA_RESTRICTIONS_SETTINGS", + "android.settings.MANAGE_UNKNOWN_APP_SOURCES", + "android.settings.MANAGE_OVERLAY_PERMISSION", + "android.settings.APP_LOCALE_SETTINGS", + "android.settings.REQUEST_SCHEDULE_EXACT_ALARM" -> true + else -> false } - private fun openSettingsWithPackage(target: String): Boolean { - val normalizedTarget = normalizeTarget(target) - val intent = Intent(normalizedTarget) - if (intent.action == null) return false - - intent.flags = Intent.FLAG_ACTIVITY_NEW_TASK - applyAppSpecificTarget(normalizedTarget, intent) - - if (startIntentSafely(intent)) { - return true - } - - if (normalizedTarget != "android.settings.APPLICATION_DETAILS_SETTINGS") { - return openSettingsWithPackage("android.settings.APPLICATION_DETAILS_SETTINGS") - } - - return false + private fun minimumSdk(target: String): Int = when (target) { + "android.settings.APP_LOCALE_SETTINGS" -> 33 + "android.settings.REQUEST_SCHEDULE_EXACT_ALARM", + "android.settings.APP_OPEN_BY_DEFAULT_SETTINGS" -> 31 + "android.settings.panel.action.WIFI", + "android.settings.panel.action.INTERNET_CONNECTIVITY", + "android.settings.panel.action.NFC", + "android.settings.panel.action.VOLUME", + "android.settings.APP_NOTIFICATION_BUBBLE_SETTINGS" -> 29 + "android.settings.MANAGE_UNKNOWN_APP_SOURCES" -> 26 + "android.settings.IGNORE_BACKGROUND_DATA_RESTRICTIONS_SETTINGS" -> 24 + "android.settings.action.MANAGE_WRITE_SETTINGS", + "android.settings.MANAGE_OVERLAY_PERMISSION" -> 23 + else -> 1 } private fun applyAppSpecificTarget(target: String, intent: Intent) { - if (target != "android.settings.APP_NOTIFICATION_SETTINGS") { - intent.data = Uri.fromParts("package", mContext.packageName, null) - return - } - - if (android.os.Build.VERSION.SDK_INT >= android.os.Build.VERSION_CODES.O) { - intent.putExtra("android.provider.extra.APP_PACKAGE", mContext.packageName) - } else if (android.os.Build.VERSION.SDK_INT >= android.os.Build.VERSION_CODES.LOLLIPOP) { - intent.putExtra("app_package", mContext.packageName) - intent.putExtra("app_uid", mContext.applicationInfo.uid) + if (target == "android.settings.APP_NOTIFICATION_SETTINGS" || + target == "android.settings.APP_NOTIFICATION_BUBBLE_SETTINGS") { + if (Build.VERSION.SDK_INT >= 26) { + intent.putExtra("android.provider.extra.APP_PACKAGE", mContext.packageName) + } else if (Build.VERSION.SDK_INT >= 21) { + intent.putExtra("app_package", mContext.packageName) + intent.putExtra("app_uid", mContext.applicationInfo.uid) + } else { + intent.data = Uri.fromParts("package", mContext.packageName, null) + } } else { intent.data = Uri.fromParts("package", mContext.packageName, null) } } - private fun startIntentSafely(intent: Intent): Boolean { + private fun startIntentSafely(intent: Intent, asAnotherTask: Boolean): String { + val launchContext = if (asAnotherTask) mContext else activity ?: mContext + if (asAnotherTask || launchContext !is Activity) { + intent.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK) + } return try { - mContext.startActivity(intent) - true - } catch (_: Exception) { - false + launchContext.startActivity(intent) + "opened" + } catch (_: ActivityNotFoundException) { + "unsupported" + } catch (_: SecurityException) { + "failed" + } catch (_: IllegalArgumentException) { + "failed" + } + } + + private fun openTarget( + target: String, + appSpecific: Boolean, + asAnotherTask: Boolean, + fallbackToAppSettings: Boolean + ): String { + if (target.isBlank()) return "failed" + val normalized = normalizeTarget(target) + val outcome = if (Build.VERSION.SDK_INT < minimumSdk(normalized)) { + "unsupported" + } else { + val intent = Intent(normalized) + if (appSpecific || requiresPackage(normalized)) applyAppSpecificTarget(normalized, intent) + startIntentSafely(intent, asAnotherTask) } + if (outcome == "opened" || !fallbackToAppSettings || + normalized == "android.settings.APPLICATION_DETAILS_SETTINGS") return outcome + + val fallback = openTarget( + "android.settings.APPLICATION_DETAILS_SETTINGS", true, asAnotherTask, false + ) + return if (fallback == "opened") "fallbackOpened" else "failed" } - override fun onMethodCall(@NonNull call: MethodCall, @NonNull result: Result) { + override fun onMethodCall(call: MethodCall, result: Result) { when (call.method) { - "openSettings" -> { - val settingToOpen = call.argument("settingToOpen") - if (settingToOpen == null) { - result.success(false) + "openSettings", "openSettingsDetailed", "openAndroidIntent" -> { + val detailed = call.method == "openSettingsDetailed" + val target = call.argument( + if (call.method == "openAndroidIntent") "action" else "settingToOpen" + ) + if (target == null) { + result.success(if (detailed) "failed" else false) return } - - val success = when (settingToOpen) { - "android.settings.APPLICATION_DETAILS_SETTINGS", - "android.settings.APPLICATION_NOTIFICATION_SETTINGS", - "android.settings.APP_NOTIFICATION_SETTINGS" -> { - openSettingsWithPackage(settingToOpen) - } - else -> { - openSettings(settingToOpen) - } + val normalized = normalizeTarget(target) + val appSpecific = call.argument("appSpecific") ?: false + val fallback = call.argument("fallbackToAppSettings") + ?: (detailed || appSpecific || requiresPackage(normalized)) + val outcome = openTarget( + target, appSpecific, call.argument("asAnotherTask") ?: true, fallback + ) + result.success(if (detailed) outcome else outcome == "opened" || outcome == "fallbackOpened") + } + "openAndroidPanel" -> { + val target = when (call.argument("panel")) { + "wifi" -> "android.settings.panel.action.WIFI" + "internetConnectivity" -> "android.settings.panel.action.INTERNET_CONNECTIVITY" + "nfc" -> "android.settings.panel.action.NFC" + "volume" -> "android.settings.panel.action.VOLUME" + else -> null } - result.success(success) + result.success(if (target == null) "unsupported" else openTarget( + target, false, call.argument("asAnotherTask") ?: false, false + )) } - "openAndroidIntent" -> { - val action = call.argument("action") - val appSpecific = call.argument("appSpecific") ?: false + else -> result.notImplemented() + } + } - if (action == null) { - result.success(false) - return - } + override fun onAttachedToActivity(binding: ActivityPluginBinding) { + activity = binding.activity + } - val success = if (appSpecific) { - openSettingsWithPackage(action) - } else { - openSettings(action) - } + override fun onDetachedFromActivityForConfigChanges() { + activity = null + } - result.success(success) - } - else -> { - result.notImplemented() - } - } + override fun onReattachedToActivityForConfigChanges(binding: ActivityPluginBinding) { + onAttachedToActivity(binding) + } + + override fun onDetachedFromActivity() { + activity = null } - override fun onDetachedFromEngine(@NonNull binding: FlutterPlugin.FlutterPluginBinding) { + override fun onDetachedFromEngine(binding: FlutterPlugin.FlutterPluginBinding) { channel.setMethodCallHandler(null) + activity = null } } diff --git a/android/src/test/kotlin/br/com/yanncabral/open_settings_plus/OpenSettingsPlusPluginTest.kt b/android/src/test/kotlin/br/com/yanncabral/open_settings_plus/OpenSettingsPlusPluginTest.kt new file mode 100644 index 0000000..8889515 --- /dev/null +++ b/android/src/test/kotlin/br/com/yanncabral/open_settings_plus/OpenSettingsPlusPluginTest.kt @@ -0,0 +1,165 @@ +package br.com.yanncabral.open_settings_plus + +import android.app.Activity +import android.content.ActivityNotFoundException +import android.content.Context +import android.content.ContextWrapper +import android.content.Intent +import io.flutter.plugin.common.MethodCall +import io.flutter.plugin.common.MethodChannel +import org.junit.Assert.* +import org.junit.Test +import org.junit.runner.RunWith +import org.robolectric.Robolectric +import org.robolectric.Shadows.shadowOf +import org.robolectric.RobolectricTestRunner +import org.robolectric.RuntimeEnvironment +import org.robolectric.annotation.Config + +@RunWith(RobolectricTestRunner::class) +@Config(sdk = [33], manifest = Config.NONE) +class OpenSettingsPlusPluginTest { + private class LaunchContext(base: Context, private val failures: List) : ContextWrapper(base) { + val intents = mutableListOf() + override fun startActivity(intent: Intent) { + intents.add(intent) + failures.getOrNull(intents.size - 1)?.let { throw it } + } + } + + private class CapturedResult : MethodChannel.Result { + var calls = 0 + var value: Any? = null + override fun success(result: Any?) { calls++; value = result } + override fun error(code: String, message: String?, details: Any?) { + fail("Unexpected platform error: $code $message") + } + override fun notImplemented() { fail("Unexpected unimplemented method") } + } + + private fun run( + target: String, + method: String = "openSettingsDetailed", + options: Map = emptyMap(), + failures: List = emptyList(), + activity: Activity? = null + ): Pair { + val context = LaunchContext(RuntimeEnvironment.getApplication(), failures) + val plugin = OpenSettingsPlusPlugin() + // Keep production API unchanged while testing actual Android Intent behavior. + OpenSettingsPlusPlugin::class.java.getDeclaredField("mContext").apply { + isAccessible = true + set(plugin, context) + } + OpenSettingsPlusPlugin::class.java.getDeclaredField("activity").apply { + isAccessible = true + set(plugin, activity) + } + val targetKey = when (method) { + "openAndroidPanel" -> "panel" + "openAndroidIntent" -> "action" + else -> "settingToOpen" + } + val result = CapturedResult() + plugin.onMethodCall(MethodCall(method, options + (targetKey to target)), result) + assertEquals("Every call completes once", 1, result.calls) + return result.value to context + } + + @Test fun notificationAliasIncludesAppPackageAndNewTask() { + val (result, context) = run("android.settings.APPLICATION_NOTIFICATION_SETTINGS") + assertEquals("opened", result) + val intent = context.intents.single() + assertEquals("android.settings.APP_NOTIFICATION_SETTINGS", intent.action) + assertEquals(context.packageName, intent.getStringExtra("android.provider.extra.APP_PACKAGE")) + assertTrue(intent.flags and Intent.FLAG_ACTIVITY_NEW_TASK != 0) + } + + @Test fun unavailableDestinationReportsFallbackAndScopesPackage() { + val (result, context) = run("vendor.settings.MISSING", failures = listOf(ActivityNotFoundException())) + assertEquals("fallbackOpened", result) + assertEquals(2, context.intents.size) + assertEquals("android.settings.APPLICATION_DETAILS_SETTINGS", context.intents.last().action) + assertEquals("package:${context.packageName}", context.intents.last().data.toString()) + } + + @Test fun disabledFallbackPreservesUnsupported() { + val (result, context) = run("vendor.settings.MISSING", + options = mapOf("fallbackToAppSettings" to false), failures = listOf(ActivityNotFoundException())) + assertEquals("unsupported", result) + assertEquals(1, context.intents.size) + } + + @Test fun failedFallbackReportsFailed() { + val (result, context) = run("vendor.settings.MISSING", + failures = listOf(ActivityNotFoundException(), SecurityException())) + assertEquals("failed", result) + assertEquals(2, context.intents.size) + } + + @Test fun appSettingsFailureDoesNotRetryItself() { + val (result, context) = run("android.settings.APPLICATION_DETAILS_SETTINGS", + failures = listOf(SecurityException())) + assertEquals("failed", result) + assertEquals(1, context.intents.size) + } + + @Test @Config(sdk = [28]) fun panelsAreUnsupportedBelowAndroid10WithoutFallback() { + val (result, context) = run("wifi", method = "openAndroidPanel") + assertEquals("unsupported", result) + assertTrue(context.intents.isEmpty()) + } + + @Test @Config(sdk = [32]) fun appLanguageVersionGateCanFallback() { + val (result, context) = run("android.settings.APP_LOCALE_SETTINGS") + assertEquals("fallbackOpened", result) + assertEquals("android.settings.APPLICATION_DETAILS_SETTINGS", context.intents.single().action) + } + + @Test fun panelsUsePanelIntentWithoutAppPackage() { + val (result, context) = run("internetConnectivity", method = "openAndroidPanel") + assertEquals("opened", result) + assertEquals("android.settings.panel.action.INTERNET_CONNECTIVITY", context.intents.single().action) + assertNull(context.intents.single().data) + } + + @Test fun sameTaskUsesAttachedActivityWithoutNewTaskFlag() { + val controller = Robolectric.buildActivity(Activity::class.java).setup() + try { + val activity = controller.get() + val (result, context) = run("android.settings.WIFI_SETTINGS", + options = mapOf("asAnotherTask" to false), activity = activity) + assertEquals("opened", result) + assertTrue("Application context must not launch when an Activity is attached", context.intents.isEmpty()) + val intent = requireNotNull(shadowOf(activity).nextStartedActivity) { + "The attached Activity must launch the requested destination" + } + assertEquals("android.settings.WIFI_SETTINGS", intent.action) + assertEquals(0, intent.flags and Intent.FLAG_ACTIVITY_NEW_TASK) + } finally { + controller.pause().stop().destroy() + } + } + + @Test fun sameTaskWithoutActivityUsesApplicationContextAndNewTaskFlag() { + val (result, context) = run("android.settings.WIFI_SETTINGS", + options = mapOf("asAnotherTask" to false)) + assertEquals("opened", result) + val intent = context.intents.single() + assertEquals("android.settings.WIFI_SETTINGS", intent.action) + assertTrue(intent.flags and Intent.FLAG_ACTIVITY_NEW_TASK != 0) + } + + @Test @Config(sdk = [23]) fun vpnUsesLegacyActionBeforeAndroid7() { + val (result, context) = run("android.settings.VPN_SETTINGS") + assertEquals("opened", result) + assertEquals("android.net.vpn.SETTINGS", context.intents.single().action) + } + + @Test fun legacyIntentPreservesBooleanFallbackSuccess() { + val (result, context) = run("android.settings.APP_NOTIFICATION_SETTINGS", method = "openAndroidIntent", + failures = listOf(ActivityNotFoundException())) + assertEquals(true, result) + assertEquals(2, context.intents.size) + } +} diff --git a/example/analysis_options.yaml b/example/analysis_options.yaml index 0bd999b..c6381f5 100644 --- a/example/analysis_options.yaml +++ b/example/analysis_options.yaml @@ -1,3 +1,8 @@ +analyzer: + exclude: + - build/** + - android/** + - ios/** include: package:flutter_lints/flutter.yaml linter: diff --git a/example/android/app/build.gradle b/example/android/app/build.gradle index 00a216e..cb0068b 100644 --- a/example/android/app/build.gradle +++ b/example/android/app/build.gradle @@ -31,7 +31,7 @@ android { if (project.android.hasProperty("testNamespace")) { testNamespace "br.com.yanncabral.open_settings_plus_example" } - compileSdkVersion 34 + compileSdk = 36 ndkVersion "27.0.12077973" compileOptions { @@ -53,8 +53,7 @@ android { // You can update the following values to match your application needs. // For more information, see: https://docs.flutter.dev/deployment/android#reviewing-the-gradle-build-configuration. minSdkVersion flutter.minSdkVersion - targetSdkVersion 34 - compileSdkVersion 34 + targetSdk = 36 versionCode flutterVersionCode.toInteger() versionName flutterVersionName } diff --git a/example/lib/main.dart b/example/lib/main.dart index abf3b97..1f446df 100644 --- a/example/lib/main.dart +++ b/example/lib/main.dart @@ -35,6 +35,16 @@ class MyApp extends StatelessWidget { ListView _buildIOSList(OpenSettingsPlusIOS settings) { return ListView( children: [ + ListTile( + onTap: settings.currentAppSettings, + title: const Text("Open this app's settings"), + trailing: const Icon(Icons.chevron_right), + ), + ListTile( + onTap: settings.appNotification, + title: const Text("Open this app's notification settings"), + trailing: const Icon(Icons.chevron_right), + ), ListTile( onTap: settings, title: const Text("Open settings"), @@ -228,8 +238,8 @@ class MyApp extends StatelessWidget { trailing: const Icon(Icons.chevron_right), ), ListTile( - onTap: settings.appSettings, - title: const Text("Open app settings"), + onTap: settings.allAppSettings, + title: const Text("Open installed apps"), trailing: const Icon(Icons.chevron_right), ), ListTile( @@ -243,8 +253,8 @@ class MyApp extends StatelessWidget { trailing: const Icon(Icons.chevron_right), ), ListTile( - onTap: settings.applicationSettings, - title: const Text("Open application settings"), + onTap: settings.currentAppSettings, + title: const Text("Open this app's settings"), trailing: const Icon(Icons.chevron_right), ), ListTile( diff --git a/example/pubspec.lock b/example/pubspec.lock index 13e68a8..58876e1 100644 --- a/example/pubspec.lock +++ b/example/pubspec.lock @@ -21,10 +21,10 @@ packages: dependency: transitive description: name: characters - sha256: f71061c654a3380576a52b451dd5532377954cf9dbd272a78fc8479606670803 + sha256: faf38497bda5ead2a8c7615f4f7939df04333478bf32e4173fcb06d428b5716b url: "https://pub.dev" source: hosted - version: "1.4.0" + version: "1.4.1" clock: dependency: transitive description: @@ -111,33 +111,33 @@ packages: dependency: transitive description: name: matcher - sha256: dc58c723c3c24bf8d3e2d3ad3f2f9d7bd9cf43ec6feaa64181775e60190153f2 + sha256: "31bd099b47c10cd1aeb55146a2d46ce0277630ecef3f7dae54ad7873f36696cd" url: "https://pub.dev" source: hosted - version: "0.12.17" + version: "0.12.20" material_color_utilities: dependency: transitive description: name: material_color_utilities - sha256: f7142bb1154231d7ea5f96bc7bde4bda2a0945d2806bb11670e30b850d56bdec + sha256: "9c337007e82b1889149c82ed242ed1cb24a66044e30979c44912381e9be4c48b" url: "https://pub.dev" source: hosted - version: "0.11.1" + version: "0.13.0" meta: dependency: transitive description: name: meta - sha256: "23f08335362185a5ea2ad3a4e597f1375e78bce8a040df5c600c8d3552ef2394" + sha256: "307249ce4ff29d58a18e97f6345f539382eb9c9c29ecda628900f31de0443dd9" url: "https://pub.dev" source: hosted - version: "1.17.0" + version: "1.19.0" open_settings_plus: dependency: "direct main" description: path: ".." relative: true source: path - version: "0.4.2" + version: "0.5.1" path: dependency: transitive description: @@ -203,18 +203,18 @@ packages: dependency: transitive description: name: test_api - sha256: ab2726c1a94d3176a45960b6234466ec367179b87dd74f1611adb1f3b5fb9d55 + sha256: "2a122cbe059f8b610d3a5415f42e255b6c17b1f21eee1d960f31080237fb4f11" url: "https://pub.dev" source: hosted - version: "0.7.7" + version: "0.7.12" vector_math: dependency: transitive description: name: vector_math - sha256: d530bd74fea330e6e364cda7a85019c434070188383e1cd8d9777ee586914c5b + sha256: "92b9910f66ed1057fd4da7b040ae7c74cafacf885bdc81be496928d5049b032d" url: "https://pub.dev" source: hosted - version: "2.2.0" + version: "2.4.3" vm_service: dependency: transitive description: @@ -224,5 +224,5 @@ packages: source: hosted version: "15.0.0" sdks: - dart: ">=3.8.0-0 <4.0.0" - flutter: ">=3.18.0-18.0.pre.54" + dart: ">=3.11.0 <4.0.0" + flutter: ">=3.41.0" diff --git a/example/test/widget_test.dart b/example/test/widget_test.dart index 287ba90..c2d1d74 100644 --- a/example/test/widget_test.dart +++ b/example/test/widget_test.dart @@ -1,27 +1,11 @@ -// This is a basic Flutter widget test. -// -// To perform an interaction with a widget in your test, use the WidgetTester -// utility in the flutter_test package. For example, you can send tap and scroll -// gestures. You can also use WidgetTester to find child widgets in the widget -// tree, read text, and verify that the values of widget properties are correct. - -import 'package:flutter/material.dart'; import 'package:flutter_test/flutter_test.dart'; - import 'package:open_settings_plus_example/main.dart'; void main() { - testWidgets('Verify Platform version', (WidgetTester tester) async { - // Build our app and trigger a frame. + testWidgets('unsupported host shows the platform message', (tester) async { await tester.pumpWidget(const MyApp()); - // Verify that platform version is retrieved. - expect( - find.byWidgetPredicate( - (Widget widget) => - widget is Text && widget.data!.startsWith('Running on:'), - ), - findsOneWidget, - ); + expect(find.text('Open settings +'), findsOneWidget); + expect(find.text('Unsupported platform.'), findsOneWidget); }); } diff --git a/ios/open_settings_plus/Sources/open_settings_plus/OpenSettingsPlusPlugin.swift b/ios/open_settings_plus/Sources/open_settings_plus/OpenSettingsPlusPlugin.swift index bbb2df9..0073cc6 100644 --- a/ios/open_settings_plus/Sources/open_settings_plus/OpenSettingsPlusPlugin.swift +++ b/ios/open_settings_plus/Sources/open_settings_plus/OpenSettingsPlusPlugin.swift @@ -2,6 +2,11 @@ import Flutter import UIKit public class OpenSettingsPlusPlugin: NSObject, FlutterPlugin { + // Injectable for native tests without launching the Settings app. + var openURL: (URL, @escaping (Bool) -> Void) -> Void = { url, completion in + UIApplication.shared.open(url, options: [:], completionHandler: completion) + } + public static func register(with registrar: FlutterPluginRegistrar) { let channel = FlutterMethodChannel(name: "open_settings_plus", binaryMessenger: registrar.messenger()) let instance: OpenSettingsPlusPlugin = OpenSettingsPlusPlugin() @@ -9,17 +14,105 @@ public class OpenSettingsPlusPlugin: NSObject, FlutterPlugin { } public func handle(_ call: FlutterMethodCall, result: @escaping FlutterResult) { - if call.method == "openSettings" { - let arguments = call.arguments as? [String: Any] - let argument = arguments?["settingToOpen"] as? String ?? "" + guard call.method == "openSettings" || call.method == "openSettingsDetailed" else { + result(FlutterMethodNotImplemented) + return + } - print("OpenSettingsPlusPlugin: \(argument)") + let arguments = call.arguments as? [String: Any] + if call.method == "openSettingsDetailed" { + openSettingsDetailed(arguments, result: result) + return + } - if let url = URL(string: argument) { - UIApplication.shared.open(url, options: [:], completionHandler: nil) - } - } else { + if let target = arguments?["settingToOpen"] as? String, + target == "app-notification-settings" || target == "app-notification-settings:" { + // The new notification alias uses public APIs; legacy raw URLs stay unchanged. + openSettingsDetailed(arguments, result: { status in + result((status as? String) == "opened" || (status as? String) == "fallbackOpened") + }) + return + } + + guard let argument = arguments?["settingToOpen"] as? String, + !argument.isEmpty, + let url = URL(string: argument), + url.scheme != nil else { result(false) + return + } + + openURL(url) { opened in + result(opened) + } + } + + /// Reports whether iOS accepted the URL, not whether a permission changed. + /// Experimental App-prefs URLs cannot guarantee the exact destination shown. + private func openSettingsDetailed(_ arguments: [String: Any]?, result: @escaping FlutterResult) { + guard let target = arguments?["settingToOpen"] as? String, + !target.isEmpty else { + result("failed") + return + } + + let fallback = arguments?["fallbackToAppSettings"] as? Bool ?? true + let targetURL: String + switch target { + case "app-settings", "app-settings:": + targetURL = UIApplication.openSettingsURLString + case "wifi", "bluetooth", "location": + // The shared API only promises public destinations. Raw App-prefs URLs + // remain available separately as experimental shortcuts. + finishWithFallback(enabled: fallback, unavailable: "unsupported", result: result) + return + case "app-notification-settings", "app-notification-settings:": + if #available(iOS 16.0, *) { + targetURL = UIApplication.openNotificationSettingsURLString + } else if #available(iOS 15.4, *) { + targetURL = UIApplicationOpenNotificationSettingsURLString + } else { + finishWithFallback(enabled: fallback, unavailable: "unsupported", result: result) + return + } + default: + targetURL = target + } + + guard let url = URL(string: targetURL), url.scheme != nil else { + result("failed") + return + } + + openURL(url) { opened in + if opened { + result("opened") + } else { + // Opening app settings again cannot provide a distinct fallback. + self.finishWithFallback( + enabled: fallback && targetURL != UIApplication.openSettingsURLString, + unavailable: "failed", + result: result + ) + } + } + } + + private func finishWithFallback( + enabled: Bool, + unavailable: String, + result: @escaping FlutterResult + ) { + guard enabled else { + result(unavailable) + return + } + guard let url = URL(string: UIApplication.openSettingsURLString) else { + result("failed") + return + } + openURL(url) { opened in + result(opened ? "fallbackOpened" : "failed") } } } diff --git a/lib/bridge/open_settings_plus_method_channel.dart b/lib/bridge/open_settings_plus_method_channel.dart index 030aa4f..889c74b 100644 --- a/lib/bridge/open_settings_plus_method_channel.dart +++ b/lib/bridge/open_settings_plus_method_channel.dart @@ -1,6 +1,7 @@ import 'package:flutter/foundation.dart'; import 'package:flutter/services.dart'; import 'package:open_settings_plus/bridge/open_settings_plus_platform_interface.dart'; +import 'package:open_settings_plus/core/settings_open_result.dart'; /// An implementation of [OpenSettingsPlusPlatform] that uses method channels. class MethodChannelOpenSettingsPlus extends OpenSettingsPlusPlatform { @@ -16,4 +17,67 @@ class MethodChannelOpenSettingsPlus extends OpenSettingsPlusPlatform { return success ?? false; } + + @override + Future sendAndroidIntent( + String action, { + bool appSpecific = false, + bool asAnotherTask = true, + }) async { + final success = await methodChannel + .invokeMethod('openAndroidIntent', { + 'action': action, + 'appSpecific': appSpecific, + if (!asAnotherTask) 'asAnotherTask': false, + }); + return success ?? false; + } + + @override + Future openSettingsTarget( + String target, { + bool appSpecific = false, + bool asAnotherTask = true, + bool fallbackToAppSettings = true, + }) async { + try { + final status = await methodChannel + .invokeMethod('openSettingsDetailed', { + 'settingToOpen': target, + 'appSpecific': appSpecific, + 'asAnotherTask': asAnotherTask, + 'fallbackToAppSettings': fallbackToAppSettings, + }); + return _parseResult(status); + } on MissingPluginException { + return SettingsOpenResult.unsupported; + } on PlatformException { + return SettingsOpenResult.failed; + } + } + + @override + Future openAndroidPanel( + String panel, { + bool asAnotherTask = false, + }) async { + try { + final status = await methodChannel.invokeMethod( + 'openAndroidPanel', + {'panel': panel, 'asAnotherTask': asAnotherTask}, + ); + return _parseResult(status); + } on MissingPluginException { + return SettingsOpenResult.unsupported; + } on PlatformException { + return SettingsOpenResult.failed; + } + } + + static SettingsOpenResult _parseResult(Object? status) => switch (status) { + 'opened' => SettingsOpenResult.opened, + 'fallbackOpened' => SettingsOpenResult.fallbackOpened, + 'unsupported' => SettingsOpenResult.unsupported, + _ => SettingsOpenResult.failed, + }; } diff --git a/lib/bridge/open_settings_plus_platform_interface.dart b/lib/bridge/open_settings_plus_platform_interface.dart index 7190516..3f20011 100644 --- a/lib/bridge/open_settings_plus_platform_interface.dart +++ b/lib/bridge/open_settings_plus_platform_interface.dart @@ -1,4 +1,5 @@ import 'package:open_settings_plus/bridge/open_settings_plus_method_channel.dart'; +import 'package:open_settings_plus/core/settings_open_result.dart'; import 'package:plugin_platform_interface/plugin_platform_interface.dart'; /// The interface that implementations of open_settings_plus must implement. @@ -28,4 +29,37 @@ abstract class OpenSettingsPlusPlatform extends PlatformInterface { /// This way we can pass any message to native side and handle it there. /// Note: android and ios have different implementation. Future sendMessageToNative(String message); + + /// Opens an Android intent, optionally scoped to this app. + /// + /// Returns false when an implementation does not support Android intents. + /// Success confirms an opening request, never a permission change. + Future sendAndroidIntent( + String action, { + bool appSpecific = false, + bool asAnotherTask = true, + }) async => false; + + /// Opens an Android settings panel without changing the underlying setting. + /// + /// Returns [SettingsOpenResult.unsupported] when panels are unavailable. + Future openAndroidPanel( + String panel, { + bool asAnotherTask = false, + }) async => SettingsOpenResult.unsupported; + + /// Opens [target], distinguishing an exact destination from an app fallback. + /// + /// [appSpecific] scopes Android intents to this app. [asAnotherTask] controls + /// Android task placement. [fallbackToAppSettings] permits opening the app's + /// settings if the requested destination cannot open. + /// + /// Implementations without this API return [SettingsOpenResult.unsupported]. + /// No result implies that a setting or permission changed. + Future openSettingsTarget( + String target, { + bool appSpecific = false, + bool asAnotherTask = true, + bool fallbackToAppSettings = true, + }) async => SettingsOpenResult.unsupported; } diff --git a/lib/core/open_settings_plus.dart b/lib/core/open_settings_plus.dart index 871fee7..aaa198e 100644 --- a/lib/core/open_settings_plus.dart +++ b/lib/core/open_settings_plus.dart @@ -1,7 +1,8 @@ import 'dart:io'; -import 'package:flutter/services.dart'; import 'package:open_settings_plus/bridge/open_settings_plus_platform_interface.dart'; +import 'package:open_settings_plus/core/settings_open_result.dart'; +import 'package:open_settings_plus/core/settings_target.dart'; part 'open_settings_plus_android.dart'; part 'open_settings_plus_ios.dart'; @@ -35,6 +36,85 @@ class OpenSettingsPlus { /// You can use this instance to open settings in iOS or android. static final OpenSettingsPlus? shared = OpenSettingsPlus.build(); + /// Opens a common settings destination on the current platform. + /// + /// On iOS, Wi-Fi, Bluetooth and location lack a public settings destination. + /// They return [SettingsOpenResult.unsupported], or open this app's settings + /// and return [SettingsOpenResult.fallbackOpened] when fallback is enabled. + /// Opening settings never confirms a permission or preference change. + static Future open( + SettingsTarget target, { + bool asAnotherTask = true, + bool fallbackToAppSettings = true, + }) async => + await shared?.openTarget( + target, + asAnotherTask: asAnotherTask, + fallbackToAppSettings: fallbackToAppSettings, + ) ?? + SettingsOpenResult.unsupported; + + /// Opens a common destination using this instance's platform. + /// + /// [asAnotherTask] affects Android only. The base instance has no platform + /// and returns [SettingsOpenResult.unsupported]. + Future openTarget( + SettingsTarget target, { + bool asAnotherTask = true, + bool fallbackToAppSettings = true, + }) async { + final String nativeTarget; + var appSpecific = false; + if (this is OpenSettingsPlusAndroid) { + nativeTarget = switch (target) { + SettingsTarget.appSettings => + 'android.settings.APPLICATION_DETAILS_SETTINGS', + SettingsTarget.notifications => + 'android.settings.APP_NOTIFICATION_SETTINGS', + SettingsTarget.wifi => 'android.settings.WIFI_SETTINGS', + SettingsTarget.bluetooth => 'android.settings.BLUETOOTH_SETTINGS', + SettingsTarget.location => 'android.settings.LOCATION_SOURCE_SETTINGS', + }; + appSpecific = + target == SettingsTarget.appSettings || + target == SettingsTarget.notifications; + } else if (this is OpenSettingsPlusIOS) { + nativeTarget = switch (target) { + SettingsTarget.appSettings => 'app-settings:', + SettingsTarget.notifications => 'app-notification-settings:', + SettingsTarget.wifi => 'wifi', + SettingsTarget.bluetooth => 'bluetooth', + SettingsTarget.location => 'location', + }; + } else { + return SettingsOpenResult.unsupported; + } + return openSettingsTarget( + nativeTarget, + appSpecific: appSpecific, + asAnotherTask: asAnotherTask, + fallbackToAppSettings: fallbackToAppSettings, + ); + } + + /// Opens a raw platform destination and reports exact opening or fallback. + /// + /// Android accepts intent actions, with [appSpecific] scoping the request to + /// this app. iOS accepts URLs; experimental `App-prefs:` URLs are best effort + /// and an accepted URL does not guarantee the requested section appeared. + /// Prefer [openTarget] for common destinations backed by public APIs. + Future openSettingsTarget( + String target, { + bool appSpecific = false, + bool asAnotherTask = true, + bool fallbackToAppSettings = true, + }) => OpenSettingsPlusPlatform.instance.openSettingsTarget( + target, + appSpecific: appSpecific, + asAnotherTask: asAnotherTask, + fallbackToAppSettings: fallbackToAppSettings, + ); + /// Method used to pass custom message to native side. Future sendCustomMessage(String message) { return OpenSettingsPlusPlatform.instance.sendMessageToNative(message); diff --git a/lib/core/open_settings_plus_android.dart b/lib/core/open_settings_plus_android.dart index f228ec9..94fc8ba 100644 --- a/lib/core/open_settings_plus_android.dart +++ b/lib/core/open_settings_plus_android.dart @@ -9,30 +9,68 @@ class OpenSettingsPlusAndroid extends OpenSettingsPlus { /// {@macro open_settings_plus_android} const OpenSettingsPlusAndroid(); - static const MethodChannel _androidMethodChannel = MethodChannel( - 'open_settings_plus', - ); + /// Open a raw Android action in a separate task by default. + /// + /// With [asAnotherTask] false, uses the attached Activity when available. + /// Without an Activity, Android requires a new task even when false. + Future sendAndroidIntent(String action, {bool asAnotherTask = true}) { + return OpenSettingsPlusPlatform.instance.sendAndroidIntent( + action, + asAnotherTask: asAnotherTask, + ); + } - /// Open Android settings using a raw intent action. - /// returns operation successful or failure. - Future sendAndroidIntent(String action) async { - final success = await _androidMethodChannel.invokeMethod( - 'openAndroidIntent', - {'action': action, 'appSpecific': false}, + /// Open a raw Android action for the current app package. + /// + /// Falls back to the app details screen when the requested destination fails. + /// A true result reports a launch, including this fallback. + Future sendAndroidAppIntent( + String action, { + bool asAnotherTask = true, + }) { + return OpenSettingsPlusPlatform.instance.sendAndroidIntent( + action, + appSpecific: true, + asAnotherTask: asAnotherTask, + ); + } + + /// Open an Android 10+ settings panel above the calling app. + /// + /// Returns [SettingsOpenResult.unsupported] on older Android versions or when + /// the device has no matching panel. Panels never fall back. + /// Without an attached Activity, Android opens a new task. + Future openPanel( + AndroidSettingsPanel panel, { + bool asAnotherTask = false, + }) { + return OpenSettingsPlusPlatform.instance.openAndroidPanel( + panel.name, + asAnotherTask: asAnotherTask, ); + } - return success ?? false; + /// Open this app's language settings on Android 13+. + /// + /// Older versions fall back to this app's details. The app must declare its + /// supported languages for Android to offer per-app language selection. + Future appLocale() { + return sendAndroidAppIntent('android.settings.APP_LOCALE_SETTINGS'); } - /// Open Android settings for the current app package. - /// returns operation successful or failure. - Future sendAndroidAppIntent(String action) async { - final success = await _androidMethodChannel.invokeMethod( - 'openAndroidIntent', - {'action': action, 'appSpecific': true}, + /// Open this app's exact-alarm access settings on Android 12+. + /// + /// Declare SCHEDULE_EXACT_ALARM in the app manifest when requesting access. + /// Older versions fall back to app details. A launch does not grant access. + Future exactAlarm() { + return sendAndroidAppIntent( + 'android.settings.REQUEST_SCHEDULE_EXACT_ALARM', ); + } - return success ?? false; + /// Open Android's VPN settings. + Future vpn() { + return sendAndroidIntent('android.settings.VPN_SETTINGS'); } /// Open Android settings. @@ -64,12 +102,26 @@ class OpenSettingsPlusAndroid extends OpenSettingsPlus { return sendCustomMessage('android.settings.LOCATION_SOURCE_SETTINGS'); } - /// Open Android settings in `App Settings` section. - /// returns operation successful or failure. - Future appSettings() { + /// Open Android's list of installed apps. + /// + /// This legacy name opens the app list, rather than this app's settings. + @Deprecated('Use allAppSettings() for the app list or currentAppSettings().') + Future appSettings() => allAppSettings(); + + /// Open Android's list of installed apps. + Future allAppSettings() { return sendCustomMessage('android.settings.APPLICATION_SETTINGS'); } + /// Open the settings for the current app package. + /// + /// A true result confirms a launch request, never a permission change. + Future currentAppSettings() { + return sendAndroidAppIntent( + 'android.settings.APPLICATION_DETAILS_SETTINGS', + ); + } + /// Open Android settings in `Bluetooth` section. /// returns operation successful or failure. Future bluetooth() { @@ -148,13 +200,8 @@ class OpenSettingsPlusAndroid extends OpenSettingsPlus { return sendCustomMessage('android.settings.APN_SETTINGS'); } - /// Open Android settings in `Application Details` section. - /// returns operation successful or failure. - Future applicationDetails() { - return sendAndroidAppIntent( - 'android.settings.APPLICATION_DETAILS_SETTINGS', - ); - } + /// Open the current app's settings; alias for [currentAppSettings]. + Future applicationDetails() => currentAppSettings(); /// Open Android settings in `Application Development` section. /// returns operation successful or failure. @@ -171,16 +218,16 @@ class OpenSettingsPlusAndroid extends OpenSettingsPlus { return appNotification(); } - /// Open Android settings in `Application Settings` section. - /// returns operation successful or failure. - Future applicationSettings() { - return sendCustomMessage('android.settings.APPLICATION_SETTINGS'); - } + /// Open Android's list of installed apps. + @Deprecated('Use allAppSettings() for the app list or currentAppSettings().') + Future applicationSettings() => allAppSettings(); /// Open Android settings in `Application Write Settings` section. /// returns operation successful or failure. Future applicationWriteSettings() { - return sendCustomMessage('android.settings.APPLICATION_WRITE_SETTINGS'); + return sendAndroidAppIntent( + 'android.settings.action.MANAGE_WRITE_SETTINGS', + ); } /// Open Android settings in `Battery Saver` section. @@ -216,7 +263,7 @@ class OpenSettingsPlusAndroid extends OpenSettingsPlus { /// Open Android settings in `App Notification Bubble` section. /// returns operation successful or failure. Future appNotificationBubble() { - return sendCustomMessage( + return sendAndroidAppIntent( 'android.settings.APP_NOTIFICATION_BUBBLE_SETTINGS', ); } @@ -262,7 +309,7 @@ class OpenSettingsPlusAndroid extends OpenSettingsPlus { /// Open Android settings in `Ignore Background Data Restrictions` section. /// returns operation successful or failure. Future ignoreBackgroundDataRestrictions() { - return sendCustomMessage( + return sendAndroidAppIntent( 'android.settings.IGNORE_BACKGROUND_DATA_RESTRICTIONS_SETTINGS', ); } @@ -316,14 +363,27 @@ class OpenSettingsPlusAndroid extends OpenSettingsPlus { /// Open Android settings in `Manage External Sources` section. /// returns operation successful or failure. Future manageExternalSources() { - return sendCustomMessage( - 'android.settings.MANAGE_EXTERNAL_SOURCES_SETTINGS', - ); + return sendAndroidAppIntent('android.settings.MANAGE_UNKNOWN_APP_SOURCES'); } /// Open Android settings in `Manage Overlay` section. /// returns operation successful or failure. Future manageOverlay() { - return sendCustomMessage('android.settings.MANAGE_OVERLAY_PERMISSION'); + return sendAndroidAppIntent('android.settings.MANAGE_OVERLAY_PERMISSION'); } } + +/// Android 10+ floating settings panels. +enum AndroidSettingsPanel { + /// Wi-Fi connectivity controls. + wifi, + + /// Internet connection controls. + internetConnectivity, + + /// NFC controls, when supported by the device. + nfc, + + /// Volume controls for all streams. + volume, +} diff --git a/lib/core/open_settings_plus_ios.dart b/lib/core/open_settings_plus_ios.dart index e7d9b1a..11c3829 100644 --- a/lib/core/open_settings_plus_ios.dart +++ b/lib/core/open_settings_plus_ios.dart @@ -4,6 +4,11 @@ part of 'open_settings_plus.dart'; /// The iOS implementation of `OpenSettingsPlusPlatform`. You /// can use this class to open settings in iOS. /// Note: This class should only be used in iOS. +/// +/// Prefer [currentAppSettings] and [appNotification], which use public system +/// destinations. Other shortcuts use experimental `App-prefs:` URLs. Their +/// availability and destination depend on the iOS version; a successful launch +/// does not guarantee that the requested settings section was displayed. /// {@endtemplate} class OpenSettingsPlusIOS extends OpenSettingsPlus { /// {@macro open_settings_plus_ios} @@ -25,12 +30,25 @@ class OpenSettingsPlusIOS extends OpenSettingsPlus { return sendCustomMessage('App-prefs:'); } - /// Open the app settings. - /// returns operation successful or failure. - Future appSettings() { + /// Open the current app's settings; alias for [currentAppSettings]. + @Deprecated('Use currentAppSettings() for an explicit cross-platform name.') + Future appSettings() => currentAppSettings(); + + /// Open the current app's settings using the public iOS destination. + /// + /// A true result confirms a launch request, never a permission change. + Future currentAppSettings() { return sendCustomMessage('app-settings:'); } + /// Open the current app's notification settings on iOS 15.4 or later. + /// + /// Older versions fall back to the app's settings. A true result can include + /// that fallback; use the detailed API when the distinction matters. + Future appNotification() { + return sendCustomMessage('app-notification-settings:'); + } + /// Open iOS settings in `About` section. /// returns operation successful or failure. Future about() { diff --git a/lib/core/settings_open_result.dart b/lib/core/settings_open_result.dart new file mode 100644 index 0000000..6fbc8e0 --- /dev/null +++ b/lib/core/settings_open_result.dart @@ -0,0 +1,18 @@ +/// The outcome of asking the operating system to open a settings screen. +/// +/// Opening a screen does not mean that the user changed a setting or granted a +/// permission. Even [opened] only confirms that the system accepted the +/// request. +enum SettingsOpenResult { + /// The system accepted the requested destination. + opened, + + /// The requested destination could not open, so the app's settings opened. + fallbackOpened, + + /// The destination or detailed-opening API is unavailable on this platform. + unsupported, + + /// The opening request failed, including any enabled fallback. + failed, +} diff --git a/lib/core/settings_target.dart b/lib/core/settings_target.dart new file mode 100644 index 0000000..db6fd0d --- /dev/null +++ b/lib/core/settings_target.dart @@ -0,0 +1,21 @@ +/// Common destinations available through `OpenSettingsPlus.open`. +/// +/// Availability depends on the platform and OS version. iOS can use public +/// APIs for this app's settings and notifications; other destinations can +/// fall back to this app's settings when requested. +enum SettingsTarget { + /// Settings for the calling app, rather than the system's list of apps. + appSettings, + + /// Notification settings for the calling app. + notifications, + + /// System Wi-Fi settings. + wifi, + + /// System Bluetooth settings. + bluetooth, + + /// System location settings. + location, +} diff --git a/lib/open_settings_plus.dart b/lib/open_settings_plus.dart index ae619c6..99e690e 100644 --- a/lib/open_settings_plus.dart +++ b/lib/open_settings_plus.dart @@ -1 +1,3 @@ export 'core/open_settings_plus.dart'; +export 'core/settings_open_result.dart'; +export 'core/settings_target.dart'; diff --git a/test/native_ios/main.swift b/test/native_ios/main.swift new file mode 100644 index 0000000..da22c34 --- /dev/null +++ b/test/native_ios/main.swift @@ -0,0 +1,118 @@ +// Compiled with the production plugin, real UIKit and Flutter for iOS Simulator. +// Inject only URL opening: never navigate the simulator away from the test runner. +import Foundation +import Flutter +import UIKit + +private var assertions = 0 +private func check(_ condition: @autoclosure () -> Bool, _ message: String) { + assertions += 1 + guard condition() else { + fputs("FAIL: \(message)\n", stderr) + exit(1) + } +} + +private func invoke( + method: String = "openSettingsDetailed", + arguments: Any?, + outcomes: [Bool], + expected: Any, + expectedURLs: [String] +) { + let plugin = OpenSettingsPlusPlugin() + var urls: [String] = [] + var calls = 0 + var received: Any? + plugin.openURL = { url, completion in + urls.append(url.absoluteString) + check(urls.count <= outcomes.count, "unexpected URL open: \(url)") + completion(outcomes[urls.count - 1]) + } + plugin.handle(FlutterMethodCall(methodName: method, arguments: arguments)) { result in + calls += 1 + received = result + } + check(calls == 1, "\(method) must complete exactly once; completed \(calls) times") + check(NSDictionary(dictionary: ["result": received ?? NSNull()]) == + NSDictionary(dictionary: ["result": expected]), "unexpected result: \(String(describing: received))") + check(urls == expectedURLs, "unexpected URL sequence: \(urls)") +} + +// The channel must complete from the asynchronous OS callback, not before it. +for method in ["openSettings", "openSettingsDetailed"] { + let deferredPlugin = OpenSettingsPlusPlugin() + var complete: ((Bool) -> Void)? + var callbacks = 0 + var response: Any? + deferredPlugin.openURL = { _, completion in complete = completion } + deferredPlugin.handle(FlutterMethodCall(methodName: method, + arguments: ["settingToOpen": "app-settings:"])) { value in + callbacks += 1 + response = value + } + check(callbacks == 0, "result must wait for OS completion") + check(complete != nil, "must request URL opening") + complete?(true) + check(callbacks == 1, "deferred result must complete exactly once") + if method == "openSettings" { + check(response as? Bool == true, "legacy deferred success") + } else { + check(response as? String == "opened", "detailed deferred success") + } +} +for opened in [true, false] { + invoke(method: "openSettings", arguments: ["settingToOpen": "app-settings:"], + outcomes: [opened], expected: opened, expectedURLs: ["app-settings:"]) +} +for arguments: Any? in [nil, "invalid", [:], ["settingToOpen": 42], + ["settingToOpen": ""], ["settingToOpen": "relative/path"]] { + invoke(method: "openSettings", arguments: arguments, + outcomes: [], expected: false, expectedURLs: []) + invoke(arguments: arguments, outcomes: [], expected: "failed", expectedURLs: []) +} +let experimental = "App-prefs:WIFI" +invoke(arguments: ["settingToOpen": experimental], outcomes: [true], + expected: "opened", expectedURLs: [experimental]) +invoke(arguments: ["settingToOpen": experimental], outcomes: [false, true], + expected: "fallbackOpened", expectedURLs: [experimental, UIApplication.openSettingsURLString]) +invoke(arguments: ["settingToOpen": experimental], outcomes: [false, false], + expected: "failed", expectedURLs: [experimental, UIApplication.openSettingsURLString]) +invoke(arguments: ["settingToOpen": experimental, "fallbackToAppSettings": false], + outcomes: [false], expected: "failed", expectedURLs: [experimental]) +for target in ["app-settings", "app-settings:"] { + invoke(arguments: ["settingToOpen": target], outcomes: [false], expected: "failed", + expectedURLs: [UIApplication.openSettingsURLString]) +} +if #available(iOS 16.0, *) { + for target in ["app-notification-settings", "app-notification-settings:"] { + invoke(arguments: ["settingToOpen": target], outcomes: [true], expected: "opened", + expectedURLs: [UIApplication.openNotificationSettingsURLString]) + invoke(method: "openSettings", arguments: ["settingToOpen": target], + outcomes: [false, true], expected: true, + expectedURLs: [UIApplication.openNotificationSettingsURLString, UIApplication.openSettingsURLString]) + } +} else if #available(iOS 15.4, *) { + invoke(arguments: ["settingToOpen": "app-notification-settings"], outcomes: [true], + expected: "opened", expectedURLs: [UIApplicationOpenNotificationSettingsURLString]) +} else { + invoke(arguments: ["settingToOpen": "app-notification-settings", "fallbackToAppSettings": false], + outcomes: [], expected: "unsupported", expectedURLs: []) + invoke(arguments: ["settingToOpen": "app-notification-settings"], outcomes: [true], + expected: "fallbackOpened", expectedURLs: [UIApplication.openSettingsURLString]) +} +for target in ["wifi", "bluetooth", "location"] { + invoke(arguments: ["settingToOpen": target, "fallbackToAppSettings": false], + outcomes: [], expected: "unsupported", expectedURLs: []) + invoke(arguments: ["settingToOpen": target], outcomes: [true], + expected: "fallbackOpened", expectedURLs: [UIApplication.openSettingsURLString]) +} +let plugin = OpenSettingsPlusPlugin() +var unknownResults = 0 +plugin.handle(FlutterMethodCall(methodName: "unknown", arguments: nil)) { result in + unknownResults += 1 + check((result as AnyObject?) === (FlutterMethodNotImplemented as AnyObject), + "unknown methods must preserve FlutterMethodNotImplemented") +} +check(unknownResults == 1, "unknown method must complete once") +print("PASS: \(assertions) native iOS assertions (iOS \(UIDevice.current.systemVersion))") diff --git a/test/open_settings_plus_test.dart b/test/open_settings_plus_test.dart index 3cea948..320ec11 100644 --- a/test/open_settings_plus_test.dart +++ b/test/open_settings_plus_test.dart @@ -3,17 +3,15 @@ import 'package:flutter_test/flutter_test.dart'; import 'package:open_settings_plus/bridge/open_settings_plus_method_channel.dart'; import 'package:open_settings_plus/bridge/open_settings_plus_platform_interface.dart'; import 'package:open_settings_plus/open_settings_plus.dart'; -import 'package:plugin_platform_interface/plugin_platform_interface.dart'; -class MockOpenSettingsPlusPlatform - with MockPlatformInterfaceMixin - implements OpenSettingsPlusPlatform { +class MockOpenSettingsPlusPlatform extends OpenSettingsPlusPlatform { String? lastCalled; + bool succeeds = true; @override Future sendMessageToNative(String message) async { lastCalled = message; - return true; + return succeeds; } } @@ -23,11 +21,19 @@ void main() { final initialPlatform = OpenSettingsPlusPlatform.instance; const channel = MethodChannel('open_settings_plus'); + setUp(() { + OpenSettingsPlusPlatform.instance = MethodChannelOpenSettingsPlus(); + }); + + tearDown(() { + OpenSettingsPlusPlatform.instance = initialPlatform; + }); + test('$MethodChannelOpenSettingsPlus is the default instance', () { expect(initialPlatform, isInstanceOf()); }); - test('getPlatformVersion', () async { + test('custom messages route through the registered platform', () async { const openSettingsPlusPlugin = OpenSettingsPlus.iOS(); final fakePlatform = MockOpenSettingsPlusPlatform(); OpenSettingsPlusPlatform.instance = fakePlatform; @@ -36,6 +42,14 @@ void main() { expect(fakePlatform.lastCalled, 'wifi'); }); + test('custom message preserves an unsuccessful platform result', () async { + final fakePlatform = MockOpenSettingsPlusPlatform()..succeeds = false; + OpenSettingsPlusPlatform.instance = fakePlatform; + + expect(await const OpenSettingsPlusIOS().sendCustomMessage('wifi'), false); + expect(fakePlatform.lastCalled, 'wifi'); + }); + test('android tether shortcut', () async { const settings = OpenSettingsPlusAndroid(); final fakePlatform = MockOpenSettingsPlusPlatform(); diff --git a/test/settings_facade_test.dart b/test/settings_facade_test.dart new file mode 100644 index 0000000..5680fd5 --- /dev/null +++ b/test/settings_facade_test.dart @@ -0,0 +1,142 @@ +import 'dart:io'; + +import 'package:flutter_test/flutter_test.dart'; +import 'package:open_settings_plus/bridge/open_settings_plus_platform_interface.dart'; +import 'package:open_settings_plus/open_settings_plus.dart'; + +class _RecordingPlatform extends OpenSettingsPlusPlatform { + final calls = >[]; + SettingsOpenResult result = SettingsOpenResult.opened; + + @override + Future sendMessageToNative(String message) async => true; + + @override + Future openSettingsTarget( + String target, { + bool appSpecific = false, + bool asAnotherTask = true, + bool fallbackToAppSettings = true, + }) async { + calls.add({ + 'target': target, + 'appSpecific': appSpecific, + 'asAnotherTask': asAnotherTask, + 'fallbackToAppSettings': fallbackToAppSettings, + }); + return result; + } +} + +void main() { + late OpenSettingsPlusPlatform previous; + late _RecordingPlatform bridge; + + setUp(() { + previous = OpenSettingsPlusPlatform.instance; + bridge = _RecordingPlatform(); + OpenSettingsPlusPlatform.instance = bridge; + }); + + tearDown(() => OpenSettingsPlusPlatform.instance = previous); + + test( + 'Android common destinations use correct action and app scope', + () async { + const targets = { + SettingsTarget.appSettings: + 'android.settings.APPLICATION_DETAILS_SETTINGS', + SettingsTarget.notifications: + 'android.settings.APP_NOTIFICATION_SETTINGS', + SettingsTarget.wifi: 'android.settings.WIFI_SETTINGS', + SettingsTarget.bluetooth: 'android.settings.BLUETOOTH_SETTINGS', + SettingsTarget.location: 'android.settings.LOCATION_SOURCE_SETTINGS', + }; + const settings = OpenSettingsPlus.android(); + for (final target in targets.entries) { + expect( + await settings.openTarget(target.key), + SettingsOpenResult.opened, + ); + expect(bridge.calls.last, { + 'target': target.value, + 'appSpecific': + target.key == SettingsTarget.appSettings || + target.key == SettingsTarget.notifications, + 'asAnotherTask': true, + 'fallbackToAppSettings': true, + }); + } + }, + ); + + test( + 'iOS facade uses public URLs and symbolic unsupported targets', + () async { + const targets = { + SettingsTarget.appSettings: 'app-settings:', + SettingsTarget.notifications: 'app-notification-settings:', + SettingsTarget.wifi: 'wifi', + SettingsTarget.bluetooth: 'bluetooth', + SettingsTarget.location: 'location', + }; + bridge.result = SettingsOpenResult.fallbackOpened; + const settings = OpenSettingsPlus.iOS(); + for (final target in targets.entries) { + expect( + await settings.openTarget( + target.key, + asAnotherTask: false, + fallbackToAppSettings: false, + ), + SettingsOpenResult.fallbackOpened, + ); + expect(bridge.calls.last, { + 'target': target.value, + 'appSpecific': false, + 'asAnotherTask': false, + 'fallbackToAppSettings': false, + }); + } + }, + ); + + test( + 'raw detailed opening preserves caller target, options and outcome', + () async { + bridge.result = SettingsOpenResult.unsupported; + expect( + await const OpenSettingsPlus.android().openSettingsTarget( + 'custom.intent.SETTINGS', + appSpecific: true, + asAnotherTask: false, + fallbackToAppSettings: false, + ), + SettingsOpenResult.unsupported, + ); + expect(bridge.calls.single, { + 'target': 'custom.intent.SETTINGS', + 'appSpecific': true, + 'asAnotherTask': false, + 'fallbackToAppSettings': false, + }); + }, + ); + + test('base instance does not dispatch platform destinations', () async { + expect( + await const OpenSettingsPlus().openTarget(SettingsTarget.wifi), + SettingsOpenResult.unsupported, + ); + expect(bridge.calls, isEmpty); + }); + + test('static facade on unsupported host does not invoke bridge', () async { + if (Platform.isAndroid || Platform.isIOS) return; + expect( + await OpenSettingsPlus.open(SettingsTarget.appSettings), + SettingsOpenResult.unsupported, + ); + expect(bridge.calls, isEmpty); + }); +} diff --git a/test/settings_names_test.dart b/test/settings_names_test.dart new file mode 100644 index 0000000..af759fe --- /dev/null +++ b/test/settings_names_test.dart @@ -0,0 +1,96 @@ +import 'package:flutter_test/flutter_test.dart'; +import 'package:open_settings_plus/bridge/open_settings_plus_platform_interface.dart'; +import 'package:open_settings_plus/open_settings_plus.dart'; + +class _RecordingPlatform extends OpenSettingsPlusPlatform { + String? message; + bool? appSpecific; + + @override + Future sendMessageToNative(String message) async { + this.message = message; + appSpecific = null; + return true; + } + + @override + Future sendAndroidIntent( + String action, { + bool appSpecific = false, + bool asAnotherTask = true, + }) async { + message = action; + this.appSpecific = appSpecific; + return true; + } +} + +void main() { + late OpenSettingsPlusPlatform previous; + late _RecordingPlatform platform; + + setUp(() { + previous = OpenSettingsPlusPlatform.instance; + platform = _RecordingPlatform(); + OpenSettingsPlusPlatform.instance = platform; + }); + + tearDown(() => OpenSettingsPlusPlatform.instance = previous); + + test( + 'Android current app settings and legacy details scope the package', + () async { + const settings = OpenSettingsPlusAndroid(); + for (final open in [ + settings.currentAppSettings, + settings.applicationDetails, + ]) { + expect(await open(), isTrue); + expect( + platform.message, + 'android.settings.APPLICATION_DETAILS_SETTINGS', + ); + expect(platform.appSpecific, isTrue); + } + }, + ); + + test( + 'Android installed apps aliases retain the system-wide destination', + () async { + const settings = OpenSettingsPlusAndroid(); + for (final open in [ + settings.allAppSettings, + // ignore: deprecated_member_use_from_same_package + settings.appSettings, + // ignore: deprecated_member_use_from_same_package + settings.applicationSettings, + ]) { + expect(await open(), isTrue); + expect(platform.message, 'android.settings.APPLICATION_SETTINGS'); + expect(platform.appSpecific, isNull); + } + }, + ); + + test( + 'iOS current app settings and legacy alias use the public destination', + () async { + const settings = OpenSettingsPlusIOS(); + for (final open in [ + settings.currentAppSettings, + // ignore: deprecated_member_use_from_same_package + settings.appSettings, + ]) { + expect(await open(), isTrue); + expect(platform.message, 'app-settings:'); + } + }, + ); + + test('iOS notifications use the native public-destination alias', () async { + const settings = OpenSettingsPlusIOS(); + expect(await settings.appNotification(), isTrue); + expect(platform.message, 'app-notification-settings:'); + }); +} diff --git a/test/settings_open_result_test.dart b/test/settings_open_result_test.dart new file mode 100644 index 0000000..963a6b9 --- /dev/null +++ b/test/settings_open_result_test.dart @@ -0,0 +1,144 @@ +import 'package:flutter/services.dart'; +import 'package:flutter_test/flutter_test.dart'; +import 'package:open_settings_plus/bridge/open_settings_plus_method_channel.dart'; +import 'package:open_settings_plus/bridge/open_settings_plus_platform_interface.dart'; +import 'package:open_settings_plus/open_settings_plus.dart'; + +class _LegacyPlatform extends OpenSettingsPlusPlatform { + @override + Future sendMessageToNative(String message) async => true; +} + +void main() { + TestWidgetsFlutterBinding.ensureInitialized(); + final platform = MethodChannelOpenSettingsPlus(); + final messenger = + TestDefaultBinaryMessengerBinding.instance.defaultBinaryMessenger; + + tearDown(() { + messenger.setMockMethodCallHandler(platform.methodChannel, null); + }); + + test('detailed opening passes target and explicit options', () async { + messenger.setMockMethodCallHandler(platform.methodChannel, (call) async { + expect(call.method, 'openSettingsDetailed'); + expect(call.arguments, { + 'settingToOpen': 'android.settings.APPLICATION_DETAILS_SETTINGS', + 'appSpecific': true, + 'asAnotherTask': false, + 'fallbackToAppSettings': false, + }); + return 'fallbackOpened'; + }); + expect( + await platform.openSettingsTarget( + 'android.settings.APPLICATION_DETAILS_SETTINGS', + appSpecific: true, + asAnotherTask: false, + fallbackToAppSettings: false, + ), + SettingsOpenResult.fallbackOpened, + ); + }); + + for (final result in SettingsOpenResult.values) { + test('parses native result ${result.name}', () async { + messenger.setMockMethodCallHandler( + platform.methodChannel, + (_) async => result.name, + ); + expect(await platform.openSettingsTarget('wifi'), result); + }); + } + + for (final malformed in [ + null, + true, + 1, + 'unknown', + {'opened': true}, + ]) { + test('malformed result $malformed is a failure', () async { + messenger.setMockMethodCallHandler( + platform.methodChannel, + (_) async => malformed, + ); + expect( + await platform.openSettingsTarget('wifi'), + SettingsOpenResult.failed, + ); + }); + } + + test('missing native detailed API is unsupported', () async { + expect( + await platform.openSettingsTarget('wifi'), + SettingsOpenResult.unsupported, + ); + expect( + await platform.openAndroidPanel('wifi'), + SettingsOpenResult.unsupported, + ); + }); + + test('native errors become failed results', () async { + messenger.setMockMethodCallHandler(platform.methodChannel, (_) async { + throw PlatformException(code: 'OPEN_FAILED'); + }); + expect( + await platform.openSettingsTarget('wifi'), + SettingsOpenResult.failed, + ); + expect(await platform.openAndroidPanel('wifi'), SettingsOpenResult.failed); + }); + + test('Android panel forwards task option and native outcome', () async { + messenger.setMockMethodCallHandler(platform.methodChannel, (call) async { + expect(call.method, 'openAndroidPanel'); + expect(call.arguments, {'panel': 'wifi', 'asAnotherTask': false}); + return 'opened'; + }); + expect(await platform.openAndroidPanel('wifi'), SettingsOpenResult.opened); + }); + + test( + 'legacy intent keeps default payload and supports task option', + () async { + final calls = []; + messenger.setMockMethodCallHandler(platform.methodChannel, (call) async { + calls.add(call); + return true; + }); + expect(await platform.sendAndroidIntent('wifi'), isTrue); + expect(calls.first.method, 'openAndroidIntent'); + expect(calls.first.arguments, {'action': 'wifi', 'appSpecific': false}); + expect( + await platform.sendAndroidIntent( + 'app', + appSpecific: true, + asAnotherTask: false, + ), + isTrue, + ); + expect(calls.last.arguments, { + 'action': 'app', + 'appSpecific': true, + 'asAnotherTask': false, + }); + }, + ); + + test('legacy subclasses inherit unsupported defaults for new APIs', () async { + final legacy = _LegacyPlatform(); + expect(await legacy.sendMessageToNative('wifi'), isTrue); + expect(await legacy.sendAndroidIntent('wifi'), isFalse); + expect( + await legacy.openSettingsTarget('wifi'), + SettingsOpenResult.unsupported, + ); + expect( + await legacy.openAndroidPanel('wifi'), + SettingsOpenResult.unsupported, + ); + }); +} diff --git a/tool/test_native_ios.sh b/tool/test_native_ios.sh new file mode 100755 index 0000000..56247e2 --- /dev/null +++ b/tool/test_native_ios.sh @@ -0,0 +1,35 @@ +#!/usr/bin/env bash +# Run production Swift against real UIKit/Flutter; URL opening is injected. +# Requires macOS, Xcode, Flutter's iOS artifacts and an installed iOS simulator. +set -euo pipefail +repo_root="$(cd "$(dirname "$0")/.." && pwd)" +if [[ -z "${FLUTTER_ROOT:-}" ]]; then + flutter_path="$(command -v flutter)" + FLUTTER_ROOT="$(python3 -c 'import os,sys; print(os.path.dirname(os.path.dirname(os.path.realpath(sys.argv[1]))))' "$flutter_path")" +fi +framework_dir="$FLUTTER_ROOT/bin/cache/artifacts/engine/ios/Flutter.xcframework/ios-arm64_x86_64-simulator" +if [[ ! -d "$framework_dir/Flutter.framework" ]]; then + echo 'Flutter iOS artifacts missing. Run flutter precache --ios first.' >&2 + exit 1 +fi +work_dir="$(mktemp -d)" +trap 'rm -rf "$work_dir"' EXIT +simulator_id="${IOS_SIMULATOR_UDID:-$(xcrun simctl list devices available -j | python3 -c 'import json,sys; devices=[d for runtime,group in json.load(sys.stdin)["devices"].items() if ".iOS-" in runtime for d in group if d["isAvailable"]]; print(next((d["udid"] for d in devices if d["state"] == "Booted"), devices[0]["udid"] if devices else ""))')}" +if [[ -z "$simulator_id" ]]; then + echo 'No available iOS simulator. Install an iOS runtime in Xcode.' >&2 + exit 1 +fi +# A device already booted by the developer may be reused. +if ! xcrun simctl list devices booted -j | python3 -c 'import json,sys; target=sys.argv[1]; sys.exit(not any(d["udid"] == target for group in json.load(sys.stdin)["devices"].values() for d in group))' "$simulator_id"; then + xcrun simctl boot "$simulator_id" +fi +xcrun simctl bootstatus "$simulator_id" -b +architecture="$(uname -m)" +xcrun --sdk iphonesimulator swiftc \ + -target "$architecture-apple-ios15.0-simulator" \ + -sdk "$(xcrun --sdk iphonesimulator --show-sdk-path)" \ + -F "$framework_dir" -framework Flutter \ + -Xlinker -rpath -Xlinker "$framework_dir" \ + "$repo_root/ios/open_settings_plus/Sources/open_settings_plus/OpenSettingsPlusPlugin.swift" \ + "$repo_root/test/native_ios/main.swift" -o "$work_dir/native-tests" +xcrun simctl spawn "$simulator_id" "$work_dir/native-tests"