Skip to content
Draft
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension


Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
10 changes: 10 additions & 0 deletions packages/android_local_network/CHANGELOG.md
Original file line number Diff line number Diff line change
@@ -0,0 +1,10 @@
## 0.1.1

* `AndroidLocalAreaSocket.connect` now automatically requests permission on first use.
* Synchronized `AndroidLocalNetwork.requestPermission` to handle concurrent calls.

## 0.1.0

* Initial release.
* Added `AndroidLocalNetwork` to check and request `ACCESS_LOCAL_NETWORK` permission.
* Added `AndroidLocalAreaSocket` wrapper for `Socket.connect`.
27 changes: 27 additions & 0 deletions packages/android_local_network/README.md
Original file line number Diff line number Diff line change
@@ -0,0 +1,27 @@
# android_local_network

A Flutter package to handle the Android 17 Local Area Permission (`ACCESS_LOCAL_NETWORK`) for Dart sockets.

## Usage

Instead of using `Socket.connect` directly on Android 17+, use `AndroidLocalAreaSocket.connect`:

```dart
import 'package:android_local_network/android_local_network.dart';

final socket = await AndroidLocalAreaSocket.connect('192.168.1.1', 8080);
```

Or check and request the permission manually:

```dart
import 'package:android_local_network/android_local_network.dart';

if (await AndroidLocalNetwork.requestPermission()) {
// Permission granted
}
```

## Implementation Details

This package uses `jnigen` to interact with Android's permission system via FFI. This avoids the need for MethodChannels in the framework and provides a more direct way to handle permissions from Dart.
25 changes: 25 additions & 0 deletions packages/android_local_network/android/build.gradle.kts
Original file line number Diff line number Diff line change
@@ -0,0 +1,25 @@
group = "com.example.android_local_network"
version = "1.0-SNAPSHOT"

plugins {
id("com.android.library")
}

android {
namespace = "com.example.android_local_network"
compileSdk = 35

defaultConfig {
minSdk = 24
}

compileOptions {
sourceCompatibility = JavaVersion.VERSION_17
targetCompatibility = JavaVersion.VERSION_17
}
}

dependencies {
implementation("androidx.core:core:1.13.1")
implementation("io.flutter:flutter_embedding_debug:1.0.0-cafac705f02f2a77cd72743c41b33a0fa97714e0")
}
Original file line number Diff line number Diff line change
@@ -0,0 +1,136 @@
package com.example.android_local_network;

import android.app.Activity;
import android.content.pm.PackageManager;
import androidx.annotation.NonNull;
import androidx.core.app.ActivityCompat;
import androidx.core.content.ContextCompat;
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.PluginRegistry;

import android.os.Build;
import android.util.Log;

/**
* AndroidLocalNetwork handles the ACCESS_LOCAL_NETWORK permission.
* It can be used via jnigen to check and request permissions from Dart.
*/
public class AndroidLocalNetworkPlugin implements FlutterPlugin, ActivityAware, PluginRegistry.RequestPermissionsResultListener {
private static final String TAG = "AndroidLocalNetwork";
private static final String PERMISSION = "android.permission.ACCESS_LOCAL_NETWORK";
private static final int REQUEST_CODE = 4853; // Arbitrary request code

private Activity activity;
private PermissionCallback pendingCallback;

/**
* Interface for permission result callbacks.
*/
public interface PermissionCallback {
void onResult(boolean granted);
}

private static AndroidLocalNetworkPlugin instance;

public static AndroidLocalNetworkPlugin getInstance() {
Log.d(TAG, "getInstance called, instance is " + (instance == null ? "null" : "not null"));
return instance;
}

@Override
public void onAttachedToEngine(@NonNull FlutterPluginBinding binding) {
Log.d(TAG, "onAttachedToEngine");
instance = this;
}

@Override
public void onDetachedFromEngine(@NonNull FlutterPluginBinding binding) {
Log.d(TAG, "onDetachedFromEngine");
if (instance == this) {
instance = null;
}
}

@Override
public void onAttachedToActivity(@NonNull ActivityPluginBinding binding) {
Log.d(TAG, "onAttachedToActivity");
this.activity = binding.getActivity();
binding.addRequestPermissionsResultListener(this);
}

@Override
public void onDetachedFromActivityForConfigChanges() {
Log.d(TAG, "onDetachedFromActivityForConfigChanges");
this.activity = null;
}

@Override
public void onReattachedToActivityForConfigChanges(@NonNull ActivityPluginBinding binding) {
Log.d(TAG, "onReattachedToActivityForConfigChanges");
this.activity = binding.getActivity();
binding.addRequestPermissionsResultListener(this);
}

@Override
public void onDetachedFromActivity() {
Log.d(TAG, "onDetachedFromActivity");
this.activity = null;
}

/**
* Checks if the local area permission is granted.
*/
public boolean checkPermission() {
if (activity == null) {
Log.w(TAG, "checkPermission: activity is null");
return false;
}
try {
boolean granted = ContextCompat.checkSelfPermission(activity, PERMISSION) == PackageManager.PERMISSION_GRANTED;
Log.d(TAG, "checkPermission for " + PERMISSION + ": " + granted);
return granted;
} catch (Exception e) {
Log.e(TAG, "checkPermission error", e);
return false;
}
}

/**
* Requests the local area permission.
*/
public void requestPermission(PermissionCallback callback) {
Log.d(TAG, "requestPermission called. Current API: " + Build.VERSION.SDK_INT);

if (activity == null) {
Log.w(TAG, "requestPermission: activity is null");
callback.onResult(false);
return;
}

if (checkPermission()) {
callback.onResult(true);
return;
}

pendingCallback = callback;
Log.d(TAG, "requestPermission: requesting from OS: " + PERMISSION);
ActivityCompat.requestPermissions(activity, new String[]{PERMISSION}, REQUEST_CODE);
}

@Override
public boolean onRequestPermissionsResult(int requestCode, @NonNull String[] permissions, @NonNull int[] grantResults) {
Log.d(TAG, "onRequestPermissionsResult: requestCode=" + requestCode);
if (requestCode == REQUEST_CODE) {
boolean granted = grantResults.length > 0 && grantResults[0] == PackageManager.PERMISSION_GRANTED;
Log.d(TAG, "onRequestPermissionsResult: granted=" + granted);
if (pendingCallback != null) {
pendingCallback.onResult(granted);
pendingCallback = null;
}
return true;
}
return false;
}
}
45 changes: 45 additions & 0 deletions packages/android_local_network/example/.gitignore
Original file line number Diff line number Diff line change
@@ -0,0 +1,45 @@
# Miscellaneous
*.class
*.log
*.pyc
*.swp
.DS_Store
.atom/
.build/
.buildlog/
.history
.svn/
.swiftpm/
migrate_working_dir/

# IntelliJ related
*.iml
*.ipr
*.iws
.idea/

# The .vscode folder contains launch configuration and tasks you configure in
# VS Code which you may wish to be included in version control, so this line
# is commented out by default.
#.vscode/

# Flutter/Dart/Pub related
**/doc/api/
**/ios/Flutter/.last_build_id
.dart_tool/
.flutter-plugins-dependencies
.pub-cache/
.pub/
/build/
/coverage/

# Symbolication related
app.*.symbols

# Obfuscation related
app.*.map.json

# Android Studio will place build artifacts here
/android/app/debug
/android/app/profile
/android/app/release
30 changes: 30 additions & 0 deletions packages/android_local_network/example/.metadata
Original file line number Diff line number Diff line change
@@ -0,0 +1,30 @@
# 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: "aa55a185405913779b327aa3d6c6639d2487642f"
channel: "master"

project_type: app

# Tracks metadata for the flutter migrate command
migration:
platforms:
- platform: root
create_revision: aa55a185405913779b327aa3d6c6639d2487642f
base_revision: aa55a185405913779b327aa3d6c6639d2487642f
- platform: android
create_revision: aa55a185405913779b327aa3d6c6639d2487642f
base_revision: aa55a185405913779b327aa3d6c6639d2487642f

# User provided section

# List of Local paths (relative to this file) that should be
# ignored by the migrate tool.
#
# Files that are not part of the templates will be ignored by default.
unmanaged_files:
- 'lib/main.dart'
- 'ios/Runner.xcodeproj/project.pbxproj'
17 changes: 17 additions & 0 deletions packages/android_local_network/example/README.md
Original file line number Diff line number Diff line change
@@ -0,0 +1,17 @@
# example

A new Flutter project.

## Getting Started

This project is a starting point for a Flutter application.

A few resources to get you started if this is your first Flutter project:

- [Learn Flutter](https://docs.flutter.dev/get-started/learn-flutter)
- [Write your first Flutter app](https://docs.flutter.dev/get-started/codelab)
- [Flutter learning resources](https://docs.flutter.dev/reference/learning-resources)

For help getting started with Flutter development, view the
[online documentation](https://docs.flutter.dev/), which offers tutorials,
samples, guidance on mobile development, and a full API reference.
28 changes: 28 additions & 0 deletions packages/android_local_network/example/analysis_options.yaml
Original file line number Diff line number Diff line change
@@ -0,0 +1,28 @@
# This file configures the analyzer, which statically analyzes Dart code to
# check for errors, warnings, and lints.
#
# The issues identified by the analyzer are surfaced in the UI of Dart-enabled
# IDEs (https://dart.dev/tools#ides-and-editors). The analyzer can also be
# invoked from the command line by running `flutter analyze`.

# The following line activates a set of recommended lints for Flutter apps,
# packages, and plugins designed to encourage good coding practices.
include: package:flutter_lints/flutter.yaml

linter:
# The lint rules applied to this project can be customized in the
# section below to disable rules from the `package:flutter_lints/flutter.yaml`
# included above or to enable additional rules. A list of all available lints
# and their documentation is published at https://dart.dev/lints.
#
# Instead of disabling a lint rule for the entire project in the
# section below, it can also be suppressed for a single line of code
# or a specific dart file by using the `// ignore: name_of_lint` and
# `// ignore_for_file: name_of_lint` syntax on the line or in the file
# producing the lint.
rules:
# avoid_print: false # Uncomment to disable the `avoid_print` rule
# prefer_single_quotes: true # Uncomment to enable the `prefer_single_quotes` rule

# Additional information about this file can be found at
# https://dart.dev/guides/language/analysis-options
14 changes: 14 additions & 0 deletions packages/android_local_network/example/android/.gitignore
Original file line number Diff line number Diff line change
@@ -0,0 +1,14 @@
gradle-wrapper.jar
/.gradle
/captures/
/gradlew
/gradlew.bat
/local.properties
GeneratedPluginRegistrant.java
.cxx/

# Remember to never publicly share your keystore.
# See https://flutter.dev/to/reference-keystore
key.properties
**/*.keystore
**/*.jks
Original file line number Diff line number Diff line change
@@ -0,0 +1,44 @@
plugins {
id("com.android.application")
id("kotlin-android")
// The Flutter Gradle Plugin must be applied after the Android and Kotlin Gradle plugins.
id("dev.flutter.flutter-gradle-plugin")
}

android {
namespace = "com.example.example"
compileSdk = 36
ndkVersion = flutter.ndkVersion

compileOptions {
sourceCompatibility = JavaVersion.VERSION_17
targetCompatibility = JavaVersion.VERSION_17
}

kotlinOptions {
jvmTarget = JavaVersion.VERSION_17.toString()
}

defaultConfig {
// TODO: Specify your own unique Application ID (https://developer.android.com/studio/build/application-id.html).
applicationId = "com.example.example"
// You can update the following values to match your application needs.
// For more information, see: https://flutter.dev/to/review-gradle-config.
minSdk = 24
targetSdk = 36
versionCode = flutter.versionCode
versionName = flutter.versionName
}

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.getByName("debug")
}
}
}

flutter {
source = "../.."
}
Original file line number Diff line number Diff line change
@@ -0,0 +1,7 @@
<manifest xmlns:android="http://schemas.android.com/apk/res/android">
<!-- The INTERNET permission is required for development. Specifically,
the Flutter tool 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>
Loading
Loading