diff --git a/.github/workflows/flutter-beta.yml b/.github/workflows/flutter-beta.yml
index 526ad9f8..99aca360 100644
--- a/.github/workflows/flutter-beta.yml
+++ b/.github/workflows/flutter-beta.yml
@@ -1,6 +1,7 @@
name: Build Flutter Beta
on:
+ workflow_dispatch:
push:
branches:
- flutter-beta
@@ -15,7 +16,10 @@ concurrency:
jobs:
quality:
name: Quality Checks
- runs-on: ubuntu-latest
+ runs-on: macos-14
+ defaults:
+ run:
+ working-directory: packages/home_widget
steps:
- uses: actions/checkout@v2
@@ -23,12 +27,13 @@ jobs:
- uses: subosito/flutter-action@v1
with:
channel: beta
- - name: Get Packages
- run: flutter pub get
+ - uses: bluefireteam/melos-action@v3
- name: Analyze
- run: flutter analyze
+ run: melos analyze
+ - name: Install Formatters
+ run: brew install swift-format ktfmt
- name: Format
- run: dart format . --set-exit-if-changed
+ run: melos format:all
- name: Publishability
run: flutter pub publish --dry-run
- name: Test
@@ -45,11 +50,10 @@ jobs:
uses: codecov/codecov-action@v1
with:
token: ${{ secrets.CODECOV_TOKEN }}
- - uses: VeryGoodOpenSource/very_good_coverage@v1.2.0
+ path: ./packages/home_widget/coverage/lcov.info
android:
name: Android Integration Tests
- needs: quality
runs-on: ubuntu-latest
steps:
@@ -57,6 +61,7 @@ jobs:
- uses: subosito/flutter-action@v1
with:
channel: beta
+ - uses: bluefireteam/melos-action@v3
- name: Enable KVM
run: |
echo 'KERNEL=="kvm", GROUP="kvm", MODE="0666", OPTIONS+="static_node=kvm"' | sudo tee /etc/udev/rules.d/99-kvm4all.rules
@@ -71,20 +76,22 @@ jobs:
uses: reactivecircus/android-emulator-runner@v2
with:
api-level: 29
- working-directory: example
script: flutter test integration_test/android_test.dart -d emulator-5554
+ working-directory: packages/home_widget/example
# iOS Test based on https://medium.com/flutter-community/run-flutter-driver-tests-on-github-actions-13c639c7e4ab
# by @kate_sheremet
ios:
name: iOS Integration Tests
- needs: quality
strategy:
matrix:
device:
- "iPhone 14"
fail-fast: false
runs-on: macos-14
+ defaults:
+ run:
+ working-directory: packages/home_widget/example
steps:
- uses: actions/checkout@v2
- uses: maxim-lobanov/setup-xcode@v1
@@ -93,10 +100,10 @@ jobs:
- uses: subosito/flutter-action@v1
with:
channel: beta
+ - uses: bluefireteam/melos-action@v3
- uses: futureware-tech/simulator-action@v1
id: simulator
with:
model: ${{ matrix.device }}
- name: "Run iOS integration tests"
- run: flutter test integration_test/ios_test.dart -d ${{steps.simulator.outputs.udid}}
- working-directory: example
\ No newline at end of file
+ run: flutter test integration_test/ios_test.dart -d ${{steps.simulator.outputs.udid}}
\ No newline at end of file
diff --git a/.github/workflows/main.yml b/.github/workflows/main.yml
index 1bbcb4e4..c71f178b 100644
--- a/.github/workflows/main.yml
+++ b/.github/workflows/main.yml
@@ -1,6 +1,7 @@
name: Build
on:
+ workflow_dispatch:
push:
branches:
- main
@@ -17,7 +18,10 @@ concurrency:
jobs:
quality:
name: Quality Checks
- runs-on: ubuntu-latest
+ runs-on: macos-14
+ defaults:
+ run:
+ working-directory: packages/home_widget
steps:
- uses: actions/checkout@v2
@@ -25,12 +29,13 @@ jobs:
- uses: subosito/flutter-action@v1
with:
channel: stable
- - name: Get Packages
- run: flutter pub get
+ - uses: bluefireteam/melos-action@v3
- name: Analyze
- run: flutter analyze
+ run: melos analyze
+ - name: Install Formatters
+ run: brew install swift-format ktfmt
- name: Format
- run: dart format . --set-exit-if-changed
+ run: melos format:all
- name: Publishability
run: flutter pub publish --dry-run
- name: Test
@@ -47,11 +52,10 @@ jobs:
uses: codecov/codecov-action@v1
with:
token: ${{ secrets.CODECOV_TOKEN }}
- - uses: VeryGoodOpenSource/very_good_coverage@v1.2.0
+ path: ./packages/home_widget/coverage/lcov.info
android:
name: Android Integration Tests
- needs: quality
runs-on: ubuntu-latest
steps:
@@ -59,6 +63,7 @@ jobs:
- uses: subosito/flutter-action@v1
with:
channel: stable
+ - uses: bluefireteam/melos-action@v3
- name: Enable KVM
run: |
echo 'KERNEL=="kvm", GROUP="kvm", MODE="0666", OPTIONS+="static_node=kvm"' | sudo tee /etc/udev/rules.d/99-kvm4all.rules
@@ -73,20 +78,22 @@ jobs:
uses: reactivecircus/android-emulator-runner@v2
with:
api-level: 29
- working-directory: example
script: flutter test integration_test/android_test.dart -d emulator-5554
+ working-directory: packages/home_widget/example
# iOS Test based on https://medium.com/flutter-community/run-flutter-driver-tests-on-github-actions-13c639c7e4ab
# by @kate_sheremet
ios:
name: iOS Integration Tests
- needs: quality
strategy:
matrix:
device:
- "iPhone 14"
fail-fast: false
runs-on: macos-14
+ defaults:
+ run:
+ working-directory: packages/home_widget/example
steps:
- uses: actions/checkout@v2
- uses: maxim-lobanov/setup-xcode@v1
@@ -95,10 +102,10 @@ jobs:
- uses: subosito/flutter-action@v1
with:
channel: stable
+ - uses: bluefireteam/melos-action@v3
- uses: futureware-tech/simulator-action@v1
id: simulator
with:
model: ${{ matrix.device }}
- name: "Run iOS integration tests"
- run: flutter test integration_test/ios_test.dart -d ${{steps.simulator.outputs.udid}}
- working-directory: example
\ No newline at end of file
+ run: flutter test integration_test/ios_test.dart -d ${{steps.simulator.outputs.udid}}
\ No newline at end of file
diff --git a/README.md b/README.md
deleted file mode 100644
index c325b116..00000000
--- a/README.md
+++ /dev/null
@@ -1,675 +0,0 @@
-# Home Widget
-
-[](https://pub.dartlang.org/packages/home_widget)
-[](https://pub.dev/packages/home_widget/score)
-[](https://pub.dev/packages/home_widget/score)
-[](https://pub.dev/packages/home_widget/score)
-[](https://github.com/ABausG/home_widget/actions/workflows/main.yml?query=branch%3Amain)
-[](https://codecov.io/gh/ABausG/home_widget)
-
-HomeWidget is a Plugin to make it easier to create HomeScreen Widgets on Android and iOS.
-HomeWidget does **not** allow writing Widgets with Flutter itself. It still requires writing the Widgets with native code. However, it provides a unified Interface for sending data, retrieving data and updating the Widgets
-
-| iOS | Android |
-|----------------------------------------------------------------------------------------------------------------|--------------------------------------------------------------------------------------------------------------------|
-|
|
|
-
-## Platform Setup
-In order to work correctly there needs to be some platform specific setup. Check below on how to add support for Android and iOS
-
-iOS
-
-### Add a Widget to your App in Xcode
-Add a widget extension by going File > New > Target > Widget Extension
-
-
-
-
-### Add GroupId
-You need to add a groupId to the App and the Widget Extension
-
-**Note: in order to add groupIds you need a paid Apple Developer Account**
-
-Go to your [Apple Developer Account](https://developer.apple.com/account/resources/identifiers/list/applicationGroup) and add a new group.
-Add this group to your Runner and the Widget Extension inside XCode: Signing & Capabilities > App Groups > +.
-(To swap between your App, and the Extension change the Target)
-
-
-
-### Sync CFBundleVersion (optional)
-This step is optional, this will sync the widget extension build version with your app version, so you don't get warnings of mismatch version from App Store Connect when uploading your app.
-
-
-
-In your Runner (app) target go to Build Phases > + > New Run Script Phase and add the following script:
-```bash
-generatedPath="$SRCROOT/Flutter/Generated.xcconfig"
-
-# Read and trim versionNumber and buildNumber
-versionNumber=$(grep FLUTTER_BUILD_NAME "$generatedPath" | cut -d '=' -f2 | xargs)
-buildNumber=$(grep FLUTTER_BUILD_NUMBER "$generatedPath" | cut -d '=' -f2 | xargs)
-
-infoPlistPath="$SRCROOT/HomeExampleWidget/Info.plist"
-
-# Check and add CFBundleVersion if it does not exist
-/usr/libexec/PlistBuddy -c "Print :CFBundleVersion" "$infoPlistPath" 2>/dev/null
-if [ $? != 0 ]; then
- /usr/libexec/PlistBuddy -c "Add :CFBundleVersion string $buildNumber" "$infoPlistPath"
-else
- /usr/libexec/PlistBuddy -c "Set :CFBundleVersion $buildNumber" "$infoPlistPath"
-fi
-
-# Check and add CFBundleShortVersionString if it does not exist
-/usr/libexec/PlistBuddy -c "Print :CFBundleShortVersionString" "$infoPlistPath" 2>/dev/null
-if [ $? != 0 ]; then
- /usr/libexec/PlistBuddy -c "Add :CFBundleShortVersionString string $versionNumber" "$infoPlistPath"
-else
- /usr/libexec/PlistBuddy -c "Set :CFBundleShortVersionString $versionNumber" "$infoPlistPath"
-fi
-
-```
-
-Replace `HomeExampleWidget` with the name of the widget extension folder that you have created.
-
-
-### Write your Widget
-Check the [Example App](example/ios/HomeWidgetExample/HomeWidgetExample.swift) for an Implementation of a Widget.
-A more detailed overview on how to write Widgets for iOS 14 can be found on the [Apple Developer documentation](https://developer.apple.com/documentation/swiftui/widget).
-In order to access the Data send with Flutter can be access with
-```swift
-let data = UserDefaults.init(suiteName:"YOUR_GROUP_ID")
-```
-
-
-Android (Jetpack Glance)
-
-### Add Jetpack Glance as a dependency to you app's Gradle File
-```groovy
-implementation 'androidx.glance:glance-appwidget:LATEST-VERSION'
-```
-
-### Create Widget Configuration into `android/app/src/main/res/xml`
-```xml
-
-
-```
-
-### Add WidgetReceiver to AndroidManifest
-```xml
-
-
-
-
-
-
-```
-
-### Create WidgetReceiver
-
-To get automatic Updates you should extend from [HomeWidgetGlanceWidgetReceiver](android/src/main/kotlin/es/antonborri/home_widget/HomeWidgetGlanceWidgetReceiver.kt)
-
-Your Receiver should then look like this
-
-```kotlin
-package es.antonborri.home_widget_example.glance
-
-import HomeWidgetGlanceWidgetReceiver
-
-class HomeWidgetReceiver : HomeWidgetGlanceWidgetReceiver() {
- override val glanceAppWidget = HomeWidgetGlanceAppWidget()
-}
-```
-
-### Build Your AppWidget
-
-```kotlin
-
-class HomeWidgetGlanceAppWidget : GlanceAppWidget() {
-
- /**
- * Needed for Updating
- */
- override val stateDefinition = HomeWidgetGlanceStateDefinition()
-
- override suspend fun provideGlance(context: Context, id: GlanceId) {
- provideContent {
- GlanceContent(context, currentState())
- }
- }
-
- @Composable
- private fun GlanceContent(context: Context, currentState: HomeWidgetGlanceState) {
- // Use data to access the data you save with
- val data = currentState.preferences
-
-
- // Build Your Composable Widget
- Column(
- ...
- }
-
-```
-
-
-
-Android (XML)
-
-### Create Widget Layout inside `android/app/src/main/res/layout`
-
-### Create Widget Configuration into `android/app/src/main/res/xml`
-```xml
-
-
-
-```
-
-### Add WidgetReceiver to AndroidManifest
-```xml
-
-
-
-
-
-
-```
-
-### Write your WidgetProvider
-For convenience, you can extend from [HomeWidgetProvider](android/src/main/kotlin/es/antonborri/home_widget/HomeWidgetProvider.kt) which gives you access to a SharedPreferences Object with the Data in the `onUpdate` method.
-In case you don't want to use the convenience Method you can access the Data using
-```kotlin
-import es.antonborri.home_widget.HomeWidgetPlugin
-...
-HomeWidgetPlugin.getData(context)
-```
-which will give you access to the same SharedPreferences
-
-### More Information
-For more Information on how to create and configure Android Widgets, check out [this guide](https://developer.android.com/develop/ui/views/appwidgets) on the Android Developers Page.
-
-
-
-## Usage
-
-### Setup
-iOS
-
-For iOS, you need to call `HomeWidget.setAppGroupId('YOUR_GROUP_ID');`
-Without this you won't be able to share data between your App and the Widget and calls to `saveWidgetData` and `getWidgetData` will return an error
-
-
-
-### Save Data
-In order to save Data call `HomeWidget.saveWidgetData('id', data)`
-
-### Update a Widget
-In order to force a reload of the HomeScreenWidget you need to call
-```dart
-HomeWidget.updateWidget(
- name: 'HomeWidgetExampleProvider',
- androidName: 'HomeWidgetExampleProvider',
- iOSName: 'HomeWidgetExample',
- qualifiedAndroidName: 'com.example.app.HomeWidgetExampleProvider',
-);
-```
-
-The name for Android will be chosen by checking `qualifiedAndroidName`, falling back to `.androidName` and if that was not provided it will fallback to `.name`.
-This Name needs to be equal to the Classname of the [WidgetProvider](#Write-your-Widget)
-
-The name for iOS will be chosen by checking `iOSName` if that was not provided it will fallback to `name`.
-This name needs to be equal to the Kind specified in you Widget
-
-#### Android (Jetpack Glance)
-
-If you followed the guide and use `HomeWidgetGlanceWidgetReceiver` as your Receiver, `HomeWidgetGlanceStateDefinition` as the AppWidgetStateDefinition, `currentState()` in the composable view and `currentState.preferences` for data access. No further work is necessary.
-
-#### Android (XML)
-Calling `HomeWidget.updateWidget` only notifies the specified provider.
-To update widgets using this provider,
-update them from the provider like this:
-
-```kotlin
-class HomeWidgetExampleProvider : HomeWidgetProvider() {
-
- override fun onUpdate(context: Context, appWidgetManager: AppWidgetManager, appWidgetIds: IntArray, widgetData: SharedPreferences) {
- appWidgetIds.forEach { widgetId ->
- val views = RemoteViews(context.packageName, R.layout.example_layout).apply {
- // ...
- }
-
- // Update widget.
- appWidgetManager.updateAppWidget(widgetId, views)
- }
- }
-}
-```
-
-
-### Retrieve Data
-To retrieve the current Data saved in the Widget call `HomeWidget.getWidgetData('id', defaultValue: data)`
-
-### Interactive Widgets
-
-Android and iOS (starting with iOS 17) allow widgets to have interactive Elements like Buttons
-
-Dart
-
-1. Write a **static** function that takes a Uri as an argument. This will get called when a user clicks on the View
- ```dart
- @pragma("vm:entry-point")
- FutureOr backgroundCallback(Uri data) async {
- // do something with data
- ...
- }
- ```
- `@pragma('vm:entry-point')` must be placed above the `callback` function to avoid tree shaking in release mode.
-
-2. Register the callback function by calling
- ```dart
- HomeWidget.registerInteractivityCallback(backgroundCallback);
- ```
-
-
-iOS
-
-1. Adjust your Podfile to add `home_widget` as a dependency to your WidgetExtension
- ```rb
- target 'YourWidgetExtension' do
- use_frameworks!
- use_modular_headers!
-
- pod 'home_widget', :path => '.symlinks/plugins/home_widget/ios'
- end
- ```
-2. To be able to use plugins with the Background Callback add this to your AppDelegate's `application` function
- ```swift
- if #available(iOS 17, *) {
- HomeWidgetBackgroundWorker.setPluginRegistrantCallback { registry in
- GeneratedPluginRegistrant.register(with: registry)
- }
- }
- ```
-3. Create a custom `AppIntent` in your App Target (Runner) and make sure to select both your App and your WidgetExtension in the Target Membership panel
-
- 
-
- In this Intent you should import `home_widget` and call `HomeWidgetBackgroundWorker.run(url: url, appGroup: appGroup!)` in the perform method. `url` and `appGroup` can be either hardcoded or set as parameters from the Widget
- ```swift
- import AppIntents
- import Flutter
- import Foundation
- import home_widget
-
- @available(iOS 16, *)
- public struct BackgroundIntent: AppIntent {
- static public var title: LocalizedStringResource = "HomeWidget Background Intent"
-
- @Parameter(title: "Widget URI")
- var url: URL?
-
- @Parameter(title: "AppGroup")
- var appGroup: String?
-
- public init() {}
-
- public init(url: URL?, appGroup: String?) {
- self.url = url
- self.appGroup = appGroup
- }
-
- public func perform() async throws -> some IntentResult {
- await HomeWidgetBackgroundWorker.run(url: url, appGroup: appGroup!)
-
- return .result()
- }
- }
- ```
-4. Add a Button to your Widget. This Button might be encapsulated by a Version check. Pass in an instance of the `AppIntent` created in the previous step
- ```swift
- Button(
- intent: BackgroundIntent(
- url: URL(string: "homeWidgetExample://titleClicked"), appGroup: widgetGroupId)
- ) {
- Text(entry.title).bold().font( /*@START_MENU_TOKEN@*/.title /*@END_MENU_TOKEN@*/)
- }.buttonStyle(.plain)
- ```
-5. With the current setup the Widget is now Interactive as long as the App is still in the background. If you want to have the Widget be able to wake the App up you need to add the following to your `AppIntent` file
- ```swift
- @available(iOS 16, *)
- @available(iOSApplicationExtension, unavailable)
- extension BackgroundIntent: ForegroundContinuableIntent {}
- ```
- This code tells the system to always perform the Intent in the App and not in a process attached to the Widget. Note however that this will start your Flutter App using the normal main entrypoint meaning your full app might be run in the background. To counter this you should add checks in the very first Widget you build inside `runApp` to only perform necessary calls/setups while the App is launched in the background
-
-
-
-Android Jetpack Glance
-
-1. Add the necessary Receiver and Service to your `AndroidManifest.xml` file
- ```
-
-
-
-
-
-
- ```
-2. Create a custom Action
- ```kotlin
- class InteractiveAction : ActionCallback {
- override suspend fun onAction(context: Context, glanceId: GlanceId, parameters: ActionParameters) {
- val backgroundIntent = HomeWidgetBackgroundIntent.getBroadcast(context, Uri.parse("homeWidgetExample://titleClicked"))
- backgroundIntent.send()
- }
- }
- ```
-3. Add the Action as a modifier to a view
- ```kotlin
- Text(
- title,
- style = TextStyle(fontSize = 36.sp, fontWeight = FontWeight.Bold),
- modifier = GlanceModifier.clickable(onClick = actionRunCallback()),
- )
- ```
-
-
-
-Android XML
-
-1. Add the necessary Receiver and Service to your `AndroidManifest.xml` file
- ```
-
-
-
-
-
-
- ```
-2. Add a `HomeWidgetBackgroundIntent.getBroadcast` PendingIntent to the View you want to add a click listener to
- ```kotlin
- val backgroundIntent = HomeWidgetBackgroundIntent.getBroadcast(
- context,
- Uri.parse("homeWidgetExample://titleClicked")
- )
- setOnClickPendingIntent(R.id.widget_title, backgroundIntent)
- ```
-
-
-### Using images of Flutter widgets
-
-In some cases, you may not want to rewrite UI code in the native frameworks for your widgets.
-
-Dart
-For example, say you have a chart in your Flutter app configured with `CustomPaint`:
-
-```dart
-class LineChart extends StatelessWidget {
- const LineChart({
- super.key,
- });
-
- @override
- Widget build(BuildContext context) {
- return CustomPaint(
- painter: LineChartPainter(),
- child: const SizedBox(
- height: 200,
- width: 200,
- ),
- );
- }
-}
-```
-
-
-
-Rewriting the code to create this chart on both Android and iOS might be time consuming.
-Instead, you can generate a png file of the Flutter widget and save it to a shared container
-between your Flutter app and the home screen widget.
-
-```dart
-var path = await HomeWidget.renderFlutterWidget(
- const LineChart(),
- key: 'lineChart',
- logicalSize: const Size(400, 400),
-);
-```
-- `LineChart()` is the widget that will be rendered as an image.
-- `key` is the key in the key/value storage on the device that stores the path of the file for easy retrieval on the native side
-
-
-iOS
-To retrieve the image and display it in a widget, you can use the following SwiftUI code:
-
-1. In your `TimelineEntry` struct add a property to retrieve the path:
- ```swift
- struct MyEntry: TimelineEntry {
- …
- let lineChartPath: String
- }
- ```
-
-2. Get the path from the `UserDefaults` in `getSnapshot`:
- ```swift
- func getSnapshot(
- ...
- let lineChartPath = userDefaults?.string(forKey: "lineChart") ?? "No screenshot available"
- ```
-3. Create a `View` to display the chart and resize the image based on the `displaySize` of the widget:
- ```swift
- struct WidgetEntryView : View {
- …
- var ChartImage: some View {
- if let uiImage = UIImage(contentsOfFile: entry.lineChartPath) {
- let image = Image(uiImage: uiImage)
- .resizable()
- .frame(width: entry.displaySize.height*0.5, height: entry.displaySize.height*0.5, alignment: .center)
- return AnyView(image)
- }
- print("The image file could not be loaded")
- return AnyView(EmptyView())
- }
- …
- }
- ```
-
-4. Display the chart in the body of the widget's `View`:
- ```swift
- VStack {
- Text(entry.title)
- Text(entry.description)
- ChartImage
- }
- ```
-
-
-
-
-Android (Jetpack Glance)
-
-```kotlin
-// Access data
-val data = currentState.preferences
-
-// Get Path
-val imagePath = data.getString("lineChart", null)
-
-// Add Image to Compose Tree
-imagePath?.let {
- val bitmap = BitmapFactory.decodeFile(it)
- Image(androidx.glance.ImageProvider(bitmap), null)
-}
-```
-
-
-
-Android (XML)
-
-1. Add an image UI element to your xml file:
- ```xml
-
- ```
-2. Update your Kotlin code to get the chart image and put it into the widget, if it exists.
- ```kotlin
- class NewsWidget : AppWidgetProvider() {
- override fun onUpdate(
- context: Context,
- appWidgetManager: AppWidgetManager,
- appWidgetIds: IntArray,
- ) {
- for (appWidgetId in appWidgetIds) {
- // Get reference to SharedPreferences
- val widgetData = HomeWidgetPlugin.getData(context)
- val views = RemoteViews(context.packageName, R.layout.news_widget).apply {
- // Get chart image and put it in the widget, if it exists
- val imagePath = widgetData.getString("lineChart", null)
- val imageFile = File(imagePath)
- val imageExists = imageFile.exists()
- if (imageExists) {
- val myBitmap: Bitmap = BitmapFactory.decodeFile(imageFile.absolutePath)
- setImageViewBitmap(R.id.widget_image, myBitmap)
- } else {
- println("image not found!, looked @: $imagePath")
- }
- // End new code
- }
- appWidgetManager.updateAppWidget(appWidgetId, views)
- }
- }
- }
- ```
-
-
-### Launch App and Detect which Widget was clicked
-To detect if the App has been initially started by clicking the Widget you can call `HomeWidget.initiallyLaunchedFromHomeWidget()` if the App was already running in the Background you can receive these Events by listening to `HomeWidget.widgetClicked`. Both methods will provide Uris, so you can easily send back data from the Widget to the App to for example navigate to a content page.
-
-In order for these methods to work you need to follow these steps:
-
-iOS
-
-Add `.widgetUrl` to your WidgetComponent
-```swift
-Text(entry.message)
- .font(.body)
- .widgetURL(URL(string: "homeWidgetExample://message?message=\(entry.message)&homeWidget"))
-```
-In order to only detect Widget Links you need to add the queryParameter`homeWidget` to the URL
-
-
-Android Jetpack Glance
-
-Add an `IntentFilter` to the `Activity` Section in your `AndroidManifest`
-```
-
-
-
-```
-
-Add the following modifier to your Widget (import from HomeWidget)
-```kotlin
-Text(
- message,
- style = TextStyle(fontSize = 18.sp),
- modifier = GlanceModifier.clickable(
- onClick = actionStartActivity(
- context,
- Uri.parse("homeWidgetExample://message?message=$message")
- )
- )
-)
-```
-
-
-
-Android XML
-
-Add an `IntentFilter` to the `Activity` Section in your `AndroidManifest`
-```
-
-
-
-```
-
-In your WidgetProvider add a PendingIntent to your View using `HomeWidgetLaunchIntent.getActivity`
-```kotlin
-val pendingIntentWithData = HomeWidgetLaunchIntent.getActivity(
- context,
- MainActivity::class.java,
- Uri.parse("homeWidgetExample://message?message=$message"))
-setOnClickPendingIntent(R.id.widget_message, pendingIntentWithData)
-```
-
-
-
-### Background Update
-As the methods of HomeWidget are static it is possible to use HomeWidget in the background to update the Widget even when the App is in the background.
-
-The example App is using the [flutter_workmanager](https://pub.dev/packages/workmanager) plugin to achieve this.
-Please follow the Setup Instructions for flutter_workmanager (or your preferred background code execution plugin). Most notably make sure that Plugins get registered in iOS in order to be able to communicate with the HomeWidget Plugin.
-In case of flutter_workmanager this achieved by adding:
-```swift
-WorkmanagerPlugin.setPluginRegistrantCallback { registry in
- GeneratedPluginRegistrant.register(with: registry)
-}
-```
-to [AppDelegate.swift](example/ios/Runner/AppDelegate.swift)
-
-### Request Pin Widget
-Requests to Pin (Add) the Widget to the users HomeScreen by pinning it to the users HomeScreen.
-
-```dart
-HomeWidget.requestPinWidget(
- name: 'HomeWidgetExampleProvider',
- androidName: 'HomeWidgetExampleProvider',
- qualifiedAndroidName: 'com.example.app.HomeWidgetExampleProvider',
-);
-```
-
-This method is only supported on [Android, API 26+](https://developer.android.com/develop/ui/views/appwidgets/configuration#pin).
-If you want to check whether it is supported on current device, use:
-
-```dart
-HomeWidget.isRequestPinWidgetSupported();
-```
-
----
-
-## Resources, Articles, Talks
-Please add to this list if you have interesting and helpful resources
-- [Google Codelab](https://codelabs.developers.google.com/flutter-home-screen-widgets#0)
-- [Interactive HomeScreen Widgets with Flutter using home_widget](https://medium.com/p/83cb0706a417)
-- [iOS Lockscreen Widgets with Flutter and home_widget](https://medium.com/p/0dfecc18cfa0)
diff --git a/README.md b/README.md
new file mode 120000
index 00000000..7b3e42dc
--- /dev/null
+++ b/README.md
@@ -0,0 +1 @@
+packages/home_widget/README.md
\ No newline at end of file
diff --git a/android/src/main/kotlin/es/antonborri/home_widget/HomeWidgetBackgroundReceiver.kt b/android/src/main/kotlin/es/antonborri/home_widget/HomeWidgetBackgroundReceiver.kt
deleted file mode 100644
index dcffdcc7..00000000
--- a/android/src/main/kotlin/es/antonborri/home_widget/HomeWidgetBackgroundReceiver.kt
+++ /dev/null
@@ -1,15 +0,0 @@
-package es.antonborri.home_widget
-
-import android.content.BroadcastReceiver
-import android.content.Context
-import android.content.Intent
-import io.flutter.FlutterInjector
-
-class HomeWidgetBackgroundReceiver : BroadcastReceiver() {
- override fun onReceive(context: Context, intent: Intent) {
- val flutterLoader = FlutterInjector.instance().flutterLoader()
- flutterLoader.startInitialization(context)
- flutterLoader.ensureInitializationComplete(context, null)
- HomeWidgetBackgroundService.enqueueWork(context, intent)
- }
-}
\ No newline at end of file
diff --git a/android/src/main/kotlin/es/antonborri/home_widget/HomeWidgetBackgroundService.kt b/android/src/main/kotlin/es/antonborri/home_widget/HomeWidgetBackgroundService.kt
deleted file mode 100644
index f2a28777..00000000
--- a/android/src/main/kotlin/es/antonborri/home_widget/HomeWidgetBackgroundService.kt
+++ /dev/null
@@ -1,91 +0,0 @@
-package es.antonborri.home_widget
-
-import android.content.Context
-import android.content.Intent
-import android.os.Handler
-import android.util.Log
-import androidx.core.app.JobIntentService
-import io.flutter.FlutterInjector
-import io.flutter.embedding.engine.FlutterEngine
-import io.flutter.embedding.engine.dart.DartExecutor
-import io.flutter.plugin.common.MethodCall
-import io.flutter.plugin.common.MethodChannel
-import io.flutter.view.FlutterCallbackInformation
-import java.util.*
-import java.util.concurrent.atomic.AtomicBoolean
-
-class HomeWidgetBackgroundService : MethodChannel.MethodCallHandler, JobIntentService() {
-
- private val queue = ArrayDeque>()
- private lateinit var channel: MethodChannel
- private lateinit var context: Context
-
- companion object {
- private const val TAG = "HomeWidgetService"
- private val JOB_ID = UUID.randomUUID().mostSignificantBits.toInt()
- private var engine: FlutterEngine? = null
-
- private val serviceStarted = AtomicBoolean(false)
-
- fun enqueueWork(context: Context, work: Intent) {
- enqueueWork(context, HomeWidgetBackgroundService::class.java, JOB_ID, work)
- }
- }
-
- override fun onCreate() {
- super.onCreate()
- synchronized(serviceStarted) {
- context = this
- if (engine == null) {
- val callbackHandle = HomeWidgetPlugin.getDispatcherHandle(context)
-
- if (callbackHandle == 0L) {
- Log.e(TAG, "No callbackHandle saved. Did you call HomeWidget.registerBackgroundCallback?")
- }
-
- engine = FlutterEngine(context)
-
- val callbackInfo = FlutterCallbackInformation.lookupCallbackInformation(callbackHandle) ?: return
-
-
-
- val callback = DartExecutor.DartCallback(
- context.assets,
- FlutterInjector.instance().flutterLoader().findAppBundlePath(),
- callbackInfo
- )
- engine?.dartExecutor?.executeDartCallback(callback)
- }
- }
- channel = MethodChannel(engine!!.getDartExecutor().getBinaryMessenger(),
- "home_widget/background")
- channel.setMethodCallHandler(this)
- }
-
- override fun onMethodCall(call: MethodCall, result: MethodChannel.Result) {
- if (call.method == "HomeWidget.backgroundInitialized") {
- synchronized(serviceStarted) {
- while (!queue.isEmpty()) {
- channel.invokeMethod("", queue.remove())
- }
- serviceStarted.set(true)
- }
- }
- }
-
- override fun onHandleWork(intent: Intent) {
- val data = intent.data?.toString() ?: ""
- val args = listOf(
- HomeWidgetPlugin.getHandle(context),
- data
- )
-
- synchronized(serviceStarted) {
- if (!serviceStarted.get()) {
- queue.add(args)
- } else {
- Handler(context.mainLooper).post { channel.invokeMethod("", args) }
- }
- }
- }
-}
diff --git a/android/src/main/kotlin/es/antonborri/home_widget/HomeWidgetGlanceState.kt b/android/src/main/kotlin/es/antonborri/home_widget/HomeWidgetGlanceState.kt
deleted file mode 100644
index 31e6595a..00000000
--- a/android/src/main/kotlin/es/antonborri/home_widget/HomeWidgetGlanceState.kt
+++ /dev/null
@@ -1,32 +0,0 @@
-import android.content.Context
-import android.content.SharedPreferences
-import android.os.Environment
-import androidx.datastore.core.DataStore
-import androidx.glance.state.GlanceStateDefinition
-import es.antonborri.home_widget.HomeWidgetPlugin
-import kotlinx.coroutines.flow.Flow
-import kotlinx.coroutines.flow.flow
-import java.io.File
-
-class HomeWidgetGlanceState(val preferences: SharedPreferences)
-
-class HomeWidgetGlanceStateDefinition : GlanceStateDefinition {
- override suspend fun getDataStore(context: Context, fileKey: String): DataStore {
- val preferences = context.getSharedPreferences(HomeWidgetPlugin.PREFERENCES, Context.MODE_PRIVATE)
- return HomeWidgetGlanceDataStore(preferences)
- }
-
- override fun getLocation(context: Context, fileKey: String): File {
- return Environment.getDataDirectory()
- }
-
-}
-
-private class HomeWidgetGlanceDataStore(private val preferences: SharedPreferences) : DataStore {
- override val data: Flow
- get() = flow { emit(HomeWidgetGlanceState(preferences)) }
-
- override suspend fun updateData(transform: suspend (t: HomeWidgetGlanceState) -> HomeWidgetGlanceState): HomeWidgetGlanceState {
- return transform(HomeWidgetGlanceState(preferences))
- }
-}
\ No newline at end of file
diff --git a/android/src/main/kotlin/es/antonborri/home_widget/HomeWidgetGlanceWidgetReceiver.kt b/android/src/main/kotlin/es/antonborri/home_widget/HomeWidgetGlanceWidgetReceiver.kt
deleted file mode 100644
index c4ee3413..00000000
--- a/android/src/main/kotlin/es/antonborri/home_widget/HomeWidgetGlanceWidgetReceiver.kt
+++ /dev/null
@@ -1,29 +0,0 @@
-import android.appwidget.AppWidgetManager
-import android.content.Context
-import androidx.glance.appwidget.GlanceAppWidget
-import androidx.glance.appwidget.GlanceAppWidgetManager
-import androidx.glance.appwidget.GlanceAppWidgetReceiver
-import androidx.glance.appwidget.state.updateAppWidgetState
-import kotlinx.coroutines.runBlocking
-
-abstract class HomeWidgetGlanceWidgetReceiver : GlanceAppWidgetReceiver() {
-
- abstract override val glanceAppWidget: T
-
- override fun onUpdate(context: Context, appWidgetManager: AppWidgetManager, appWidgetIds: IntArray) {
- super.onUpdate(context, appWidgetManager, appWidgetIds)
- runBlocking {
- appWidgetIds.forEach {
- val glanceId = GlanceAppWidgetManager(context).getGlanceIdBy(it)
- glanceAppWidget.apply {
- if (this.stateDefinition is HomeWidgetGlanceStateDefinition) {
- // Must Update State
- updateAppWidgetState(context = context, this.stateDefinition as HomeWidgetGlanceStateDefinition, glanceId) { currentState -> currentState }
- }
- // Update widget.
- update(context, glanceId)
- }
- }
- }
- }
-}
\ No newline at end of file
diff --git a/android/src/main/kotlin/es/antonborri/home_widget/HomeWidgetIntent.kt b/android/src/main/kotlin/es/antonborri/home_widget/HomeWidgetIntent.kt
deleted file mode 100644
index 770a1d3f..00000000
--- a/android/src/main/kotlin/es/antonborri/home_widget/HomeWidgetIntent.kt
+++ /dev/null
@@ -1,62 +0,0 @@
-package es.antonborri.home_widget
-
-import android.app.Activity
-import android.app.ActivityOptions
-import android.app.PendingIntent
-import android.content.Context
-import android.content.Intent
-import android.net.Uri
-import android.os.Build
-import androidx.glance.action.Action
-import androidx.glance.appwidget.action.actionStartActivity
-
-object HomeWidgetLaunchIntent {
-
- const val HOME_WIDGET_LAUNCH_ACTION = "es.antonborri.home_widget.action.LAUNCH"
-
- fun getActivity(context: Context, activityClass: Class, uri: Uri? = null): PendingIntent where T : Activity {
- val intent = Intent(context, activityClass)
- intent.data = uri
- intent.action = HOME_WIDGET_LAUNCH_ACTION
-
- var flags = PendingIntent.FLAG_UPDATE_CURRENT
- if (Build.VERSION.SDK_INT >= 23) {
- flags = flags or PendingIntent.FLAG_IMMUTABLE
- }
-
- if (Build.VERSION.SDK_INT < 34) {
- return PendingIntent.getActivity(context, 0, intent, flags)
- }
-
- val options = ActivityOptions.makeBasic()
- options.pendingIntentBackgroundActivityStartMode = ActivityOptions.MODE_BACKGROUND_ACTIVITY_START_ALLOWED
-
- return PendingIntent.getActivity(context, 0, intent, flags, options.toBundle())
- }
-}
-
-inline fun actionStartActivity(context: Context, uri: Uri? = null): Action {
- val intent = Intent(context, T::class.java)
- intent.data = uri
- intent.action = HomeWidgetLaunchIntent.HOME_WIDGET_LAUNCH_ACTION
-
- return actionStartActivity(intent)
-}
-
-
-object HomeWidgetBackgroundIntent {
- private const val HOME_WIDGET_BACKGROUND_ACTION = "es.antonborri.home_widget.action.BACKGROUND"
-
- fun getBroadcast(context: Context, uri: Uri? = null): PendingIntent {
- val intent = Intent(context, HomeWidgetBackgroundReceiver::class.java)
- intent.data = uri
- intent.action = HOME_WIDGET_BACKGROUND_ACTION
-
- var flags = PendingIntent.FLAG_UPDATE_CURRENT
- if (Build.VERSION.SDK_INT >= 23) {
- flags = flags or PendingIntent.FLAG_IMMUTABLE
- }
-
- return PendingIntent.getBroadcast(context, 0, intent, flags)
- }
-}
\ No newline at end of file
diff --git a/android/src/main/kotlin/es/antonborri/home_widget/HomeWidgetPlugin.kt b/android/src/main/kotlin/es/antonborri/home_widget/HomeWidgetPlugin.kt
deleted file mode 100644
index 03c7b042..00000000
--- a/android/src/main/kotlin/es/antonborri/home_widget/HomeWidgetPlugin.kt
+++ /dev/null
@@ -1,282 +0,0 @@
-package es.antonborri.home_widget
-
-import android.app.Activity
-import android.appwidget.AppWidgetManager
-import android.appwidget.AppWidgetProviderInfo
-import android.content.BroadcastReceiver
-import android.content.ComponentName
-import android.content.Context
-import android.content.Intent
-import android.content.SharedPreferences
-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.EventChannel
-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
-import io.flutter.plugin.common.PluginRegistry
-
-
-/** HomeWidgetPlugin */
-class HomeWidgetPlugin : FlutterPlugin, MethodCallHandler, ActivityAware,
- EventChannel.StreamHandler, PluginRegistry.NewIntentListener {
- private lateinit var channel: MethodChannel
- private lateinit var eventChannel: EventChannel
- private lateinit var context: Context
-
- private var activity: Activity? = null
- private var receiver: BroadcastReceiver? = null
- private val doubleLongPrefix : String = "home_widget.double."
-
- override fun onAttachedToEngine(flutterPluginBinding: FlutterPlugin.FlutterPluginBinding) {
- channel = MethodChannel(flutterPluginBinding.binaryMessenger, "home_widget")
- channel.setMethodCallHandler(this)
-
- eventChannel = EventChannel(flutterPluginBinding.binaryMessenger, "home_widget/updates")
- eventChannel.setStreamHandler(this)
- context = flutterPluginBinding.applicationContext
- }
- override fun onMethodCall(call: MethodCall, result: Result) {
- when (call.method) {
- "saveWidgetData" -> {
- if (call.hasArgument("id") && call.hasArgument("data")) {
- val id = call.argument("id")
- val data = call.argument("data")
- val prefs = context.getSharedPreferences(PREFERENCES, Context.MODE_PRIVATE).edit()
- if (data != null) {
- prefs.putBoolean("$doubleLongPrefix$id", data is Double)
- when (data) {
- is Boolean -> prefs.putBoolean(id, data)
- is Float -> prefs.putFloat(id, data)
- is String -> prefs.putString(id, data)
- is Double -> prefs.putLong(id, java.lang.Double.doubleToRawLongBits(data))
- is Int -> prefs.putInt(id, data)
- is Long -> prefs.putLong(id, data)
- else -> result.error("-10", "Invalid Type ${data!!::class.java.simpleName}. Supported types are Boolean, Float, String, Double, Long", IllegalArgumentException())
- }
- } else {
- prefs.remove(id)
- prefs.remove("$doubleLongPrefix$id")
- }
- result.success(prefs.commit())
- } else {
- result.error("-1", "InvalidArguments saveWidgetData must be called with id and data", IllegalArgumentException())
- }
- }
- "getWidgetData" -> {
- if (call.hasArgument("id")) {
- val id = call.argument("id")
- val defaultValue = call.argument("defaultValue")
-
- val prefs = context.getSharedPreferences(PREFERENCES, Context.MODE_PRIVATE)
-
- val value = prefs.all[id] ?: defaultValue
-
- if(value is Long && prefs.getBoolean("$doubleLongPrefix$id", false)) {
- result.success(java.lang.Double.longBitsToDouble(value))
- } else {
- result.success(value)
- }
- } else {
- result.error("-2", "InvalidArguments getWidgetData must be called with id", IllegalArgumentException())
- }
- }
- "updateWidget" -> {
- val qualifiedName = call.argument("qualifiedAndroidName")
- val className = call.argument("android") ?: call.argument("name")
- try {
- val javaClass = Class.forName(qualifiedName ?: "${context.packageName}.${className}")
- val intent = Intent(context, javaClass)
- intent.action = AppWidgetManager.ACTION_APPWIDGET_UPDATE
- val ids: IntArray = AppWidgetManager.getInstance(context.applicationContext).getAppWidgetIds(ComponentName(context, javaClass))
- intent.putExtra(AppWidgetManager.EXTRA_APPWIDGET_IDS, ids)
- context.sendBroadcast(intent)
- result.success(true)
- } catch (classException: ClassNotFoundException) {
- result.error("-3", "No Widget found with Name $className. Argument 'name' must be the same as your AppWidgetProvider you wish to update", classException)
- }
- }
- "setAppGroupId" -> {
- result.success(true)
- }
- "initiallyLaunchedFromHomeWidget" -> {
- return if (activity?.intent?.action?.equals(HomeWidgetLaunchIntent.HOME_WIDGET_LAUNCH_ACTION) == true) {
- result.success(activity?.intent?.data?.toString() ?: "")
- } else {
- result.success(null)
- }
- }
- "registerBackgroundCallback" -> {
- val dispatcher = ((call.arguments as Iterable<*>).toList()[0] as Number).toLong()
- val callback = ((call.arguments as Iterable<*>).toList()[1] as Number).toLong()
- saveCallbackHandle(context, dispatcher, callback)
- return result.success(true)
- }
- "isRequestPinWidgetSupported" -> {
- if (Build.VERSION.SDK_INT < Build.VERSION_CODES.O) {
- return result.success(false)
- }
-
- val appWidgetManager = AppWidgetManager.getInstance(context.applicationContext)
- return result.success(appWidgetManager.isRequestPinAppWidgetSupported)
- }
- "requestPinWidget" -> {
- if (Build.VERSION.SDK_INT < Build.VERSION_CODES.O) {
- return result.success(null)
- }
-
- val qualifiedName = call.argument("qualifiedAndroidName")
- val className = call.argument("android") ?: call.argument("name")
-
- try {
- val javaClass = Class.forName(qualifiedName ?: "${context.packageName}.${className}")
- val myProvider = ComponentName(context, javaClass)
-
- val appWidgetManager = AppWidgetManager.getInstance(context.applicationContext)
-
- if (appWidgetManager.isRequestPinAppWidgetSupported) {
- appWidgetManager.requestPinAppWidget(myProvider, null, null)
- }
-
- return result.success(null)
- } catch (classException: ClassNotFoundException) {
- result.error("-4", "No Widget found with Name $className. Argument 'name' must be the same as your AppWidgetProvider you wish to update", classException)
- }
- }
- "getInstalledWidgets" -> {
- try {
- val pinnedWidgetInfoList = getInstalledWidgets(context)
- result.success(pinnedWidgetInfoList)
- } catch (e: Exception) {
- result.error("-5", "Failed to get installed widgets: ${e.message}", null)
- }
- }
- else -> {
- result.notImplemented()
- }
- }
- }
-
- private fun getInstalledWidgets(context: Context): List