Migration to the new Android Embedding for the Plugin

This commit is contained in:
gianlucaparadise 2021-09-26 17:26:16 +02:00
parent d8292ab59b
commit eabde21593
8 changed files with 412 additions and 45 deletions

View file

@ -2,7 +2,7 @@ group 'com.gianlucaparadise.flutter_cast_framework'
version '1.0-SNAPSHOT'
buildscript {
ext.kotlin_version = '1.2.71'
ext.kotlin_version = '1.5.31'
repositories {
google()
jcenter()

Binary file not shown.

View file

@ -0,0 +1,5 @@
distributionBase=GRADLE_USER_HOME
distributionPath=wrapper/dists
distributionUrl=https\://services.gradle.org/distributions/gradle-6.5-bin.zip
zipStoreBase=GRADLE_USER_HOME
zipStorePath=wrapper/dists

185
android/gradlew vendored Executable file
View file

@ -0,0 +1,185 @@
#!/usr/bin/env sh
#
# Copyright 2015 the original author or authors.
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# https://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS,
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
# See the License for the specific language governing permissions and
# limitations under the License.
#
##############################################################################
##
## Gradle start up script for UN*X
##
##############################################################################
# Attempt to set APP_HOME
# Resolve links: $0 may be a link
PRG="$0"
# Need this for relative symlinks.
while [ -h "$PRG" ] ; do
ls=`ls -ld "$PRG"`
link=`expr "$ls" : '.*-> \(.*\)$'`
if expr "$link" : '/.*' > /dev/null; then
PRG="$link"
else
PRG=`dirname "$PRG"`"/$link"
fi
done
SAVED="`pwd`"
cd "`dirname \"$PRG\"`/" >/dev/null
APP_HOME="`pwd -P`"
cd "$SAVED" >/dev/null
APP_NAME="Gradle"
APP_BASE_NAME=`basename "$0"`
# Add default JVM options here. You can also use JAVA_OPTS and GRADLE_OPTS to pass JVM options to this script.
DEFAULT_JVM_OPTS='"-Xmx64m" "-Xms64m"'
# Use the maximum available, or set MAX_FD != -1 to use that value.
MAX_FD="maximum"
warn () {
echo "$*"
}
die () {
echo
echo "$*"
echo
exit 1
}
# OS specific support (must be 'true' or 'false').
cygwin=false
msys=false
darwin=false
nonstop=false
case "`uname`" in
CYGWIN* )
cygwin=true
;;
Darwin* )
darwin=true
;;
MINGW* )
msys=true
;;
NONSTOP* )
nonstop=true
;;
esac
CLASSPATH=$APP_HOME/gradle/wrapper/gradle-wrapper.jar
# Determine the Java command to use to start the JVM.
if [ -n "$JAVA_HOME" ] ; then
if [ -x "$JAVA_HOME/jre/sh/java" ] ; then
# IBM's JDK on AIX uses strange locations for the executables
JAVACMD="$JAVA_HOME/jre/sh/java"
else
JAVACMD="$JAVA_HOME/bin/java"
fi
if [ ! -x "$JAVACMD" ] ; then
die "ERROR: JAVA_HOME is set to an invalid directory: $JAVA_HOME
Please set the JAVA_HOME variable in your environment to match the
location of your Java installation."
fi
else
JAVACMD="java"
which java >/dev/null 2>&1 || die "ERROR: JAVA_HOME is not set and no 'java' command could be found in your PATH.
Please set the JAVA_HOME variable in your environment to match the
location of your Java installation."
fi
# Increase the maximum file descriptors if we can.
if [ "$cygwin" = "false" -a "$darwin" = "false" -a "$nonstop" = "false" ] ; then
MAX_FD_LIMIT=`ulimit -H -n`
if [ $? -eq 0 ] ; then
if [ "$MAX_FD" = "maximum" -o "$MAX_FD" = "max" ] ; then
MAX_FD="$MAX_FD_LIMIT"
fi
ulimit -n $MAX_FD
if [ $? -ne 0 ] ; then
warn "Could not set maximum file descriptor limit: $MAX_FD"
fi
else
warn "Could not query maximum file descriptor limit: $MAX_FD_LIMIT"
fi
fi
# For Darwin, add options to specify how the application appears in the dock
if $darwin; then
GRADLE_OPTS="$GRADLE_OPTS \"-Xdock:name=$APP_NAME\" \"-Xdock:icon=$APP_HOME/media/gradle.icns\""
fi
# For Cygwin or MSYS, switch paths to Windows format before running java
if [ "$cygwin" = "true" -o "$msys" = "true" ] ; then
APP_HOME=`cygpath --path --mixed "$APP_HOME"`
CLASSPATH=`cygpath --path --mixed "$CLASSPATH"`
JAVACMD=`cygpath --unix "$JAVACMD"`
# We build the pattern for arguments to be converted via cygpath
ROOTDIRSRAW=`find -L / -maxdepth 1 -mindepth 1 -type d 2>/dev/null`
SEP=""
for dir in $ROOTDIRSRAW ; do
ROOTDIRS="$ROOTDIRS$SEP$dir"
SEP="|"
done
OURCYGPATTERN="(^($ROOTDIRS))"
# Add a user-defined pattern to the cygpath arguments
if [ "$GRADLE_CYGPATTERN" != "" ] ; then
OURCYGPATTERN="$OURCYGPATTERN|($GRADLE_CYGPATTERN)"
fi
# Now convert the arguments - kludge to limit ourselves to /bin/sh
i=0
for arg in "$@" ; do
CHECK=`echo "$arg"|egrep -c "$OURCYGPATTERN" -`
CHECK2=`echo "$arg"|egrep -c "^-"` ### Determine if an option
if [ $CHECK -ne 0 ] && [ $CHECK2 -eq 0 ] ; then ### Added a condition
eval `echo args$i`=`cygpath --path --ignore --mixed "$arg"`
else
eval `echo args$i`="\"$arg\""
fi
i=`expr $i + 1`
done
case $i in
0) set -- ;;
1) set -- "$args0" ;;
2) set -- "$args0" "$args1" ;;
3) set -- "$args0" "$args1" "$args2" ;;
4) set -- "$args0" "$args1" "$args2" "$args3" ;;
5) set -- "$args0" "$args1" "$args2" "$args3" "$args4" ;;
6) set -- "$args0" "$args1" "$args2" "$args3" "$args4" "$args5" ;;
7) set -- "$args0" "$args1" "$args2" "$args3" "$args4" "$args5" "$args6" ;;
8) set -- "$args0" "$args1" "$args2" "$args3" "$args4" "$args5" "$args6" "$args7" ;;
9) set -- "$args0" "$args1" "$args2" "$args3" "$args4" "$args5" "$args6" "$args7" "$args8" ;;
esac
fi
# Escape application args
save () {
for i do printf %s\\n "$i" | sed "s/'/'\\\\''/g;1s/^/'/;\$s/\$/' \\\\/" ; done
echo " "
}
APP_ARGS=`save "$@"`
# Collect all arguments for the java command, following the shell quoting and substitution rules
eval set -- $DEFAULT_JVM_OPTS $JAVA_OPTS $GRADLE_OPTS "\"-Dorg.gradle.appname=$APP_BASE_NAME\"" -classpath "\"$CLASSPATH\"" org.gradle.wrapper.GradleWrapperMain "$APP_ARGS"
exec "$JAVACMD" "$@"

104
android/gradlew.bat vendored Normal file
View file

@ -0,0 +1,104 @@
@rem
@rem Copyright 2015 the original author or authors.
@rem
@rem Licensed under the Apache License, Version 2.0 (the "License");
@rem you may not use this file except in compliance with the License.
@rem You may obtain a copy of the License at
@rem
@rem https://www.apache.org/licenses/LICENSE-2.0
@rem
@rem Unless required by applicable law or agreed to in writing, software
@rem distributed under the License is distributed on an "AS IS" BASIS,
@rem WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
@rem See the License for the specific language governing permissions and
@rem limitations under the License.
@rem
@if "%DEBUG%" == "" @echo off
@rem ##########################################################################
@rem
@rem Gradle startup script for Windows
@rem
@rem ##########################################################################
@rem Set local scope for the variables with windows NT shell
if "%OS%"=="Windows_NT" setlocal
set DIRNAME=%~dp0
if "%DIRNAME%" == "" set DIRNAME=.
set APP_BASE_NAME=%~n0
set APP_HOME=%DIRNAME%
@rem Resolve any "." and ".." in APP_HOME to make it shorter.
for %%i in ("%APP_HOME%") do set APP_HOME=%%~fi
@rem Add default JVM options here. You can also use JAVA_OPTS and GRADLE_OPTS to pass JVM options to this script.
set DEFAULT_JVM_OPTS="-Xmx64m" "-Xms64m"
@rem Find java.exe
if defined JAVA_HOME goto findJavaFromJavaHome
set JAVA_EXE=java.exe
%JAVA_EXE% -version >NUL 2>&1
if "%ERRORLEVEL%" == "0" goto init
echo.
echo ERROR: JAVA_HOME is not set and no 'java' command could be found in your PATH.
echo.
echo Please set the JAVA_HOME variable in your environment to match the
echo location of your Java installation.
goto fail
:findJavaFromJavaHome
set JAVA_HOME=%JAVA_HOME:"=%
set JAVA_EXE=%JAVA_HOME%/bin/java.exe
if exist "%JAVA_EXE%" goto init
echo.
echo ERROR: JAVA_HOME is set to an invalid directory: %JAVA_HOME%
echo.
echo Please set the JAVA_HOME variable in your environment to match the
echo location of your Java installation.
goto fail
:init
@rem Get command-line arguments, handling Windows variants
if not "%OS%" == "Windows_NT" goto win9xME_args
:win9xME_args
@rem Slurp the command line arguments.
set CMD_LINE_ARGS=
set _SKIP=2
:win9xME_args_slurp
if "x%~1" == "x" goto execute
set CMD_LINE_ARGS=%*
:execute
@rem Setup the command line
set CLASSPATH=%APP_HOME%\gradle\wrapper\gradle-wrapper.jar
@rem Execute Gradle
"%JAVA_EXE%" %DEFAULT_JVM_OPTS% %JAVA_OPTS% %GRADLE_OPTS% "-Dorg.gradle.appname=%APP_BASE_NAME%" -classpath "%CLASSPATH%" org.gradle.wrapper.GradleWrapperMain %CMD_LINE_ARGS%
:end
@rem End local scope for the variables with windows NT shell
if "%ERRORLEVEL%"=="0" goto mainEnd
:fail
rem Set variable GRADLE_EXIT_CONSOLE if you need the _script_ return code instead of
rem the _cmd.exe /c_ return code!
if not "" == "%GRADLE_EXIT_CONSOLE%" exit 1
exit /b 1
:mainEnd
if "%OS%"=="Windows_NT" endlocal
:omega

View file

@ -1,48 +1,107 @@
package com.gianlucaparadise.flutter_cast_framework
import android.app.Activity
import android.content.Context
import android.util.Log
import androidx.lifecycle.Lifecycle
import androidx.lifecycle.LifecycleObserver
import androidx.lifecycle.OnLifecycleEvent
import androidx.lifecycle.ProcessLifecycleOwner
import androidx.mediarouter.app.MediaRouteChooserDialog
import androidx.mediarouter.app.MediaRouteControllerDialog
import com.gianlucaparadise.flutter_cast_framework.cast.CastDialogOpener
import com.gianlucaparadise.flutter_cast_framework.cast.MessageCastingChannel
import com.google.android.gms.cast.framework.CastContext
import com.google.android.gms.cast.framework.CastSession
import com.google.android.gms.cast.framework.SessionManager
import com.google.android.gms.cast.framework.SessionManagerListener
import io.flutter.embedding.engine.plugins.FlutterPlugin
import io.flutter.embedding.engine.plugins.activity.ActivityAware
import io.flutter.embedding.engine.plugins.activity.ActivityPluginBinding
import io.flutter.plugin.common.BinaryMessenger
import io.flutter.plugin.common.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.Registrar
class FlutterCastFrameworkPlugin(private val registrar: Registrar, private val channel: MethodChannel) : MethodCallHandler, LifecycleObserver {
class FlutterCastFrameworkPlugin : FlutterPlugin, MethodCallHandler, ActivityAware, LifecycleObserver {
companion object {
const val TAG = "AndroidCastPlugin"
@JvmStatic
fun registerWith(registrar: Registrar) {
val channel = MethodChannel(registrar.messenger(), "flutter_cast_framework")
channel.setMethodCallHandler(FlutterCastFrameworkPlugin(registrar, channel))
val plugin = FlutterCastFrameworkPlugin()
plugin.onAttachedToEngine(registrar.context(), registrar.messenger())
}
}
init {
ProcessLifecycleOwner.get().lifecycle.addObserver(this)
CastContext.getSharedInstance(registrar.activeContext()).addCastStateListener { i ->
Log.d(TAG, "Cast state changed: $i")
channel.invokeMethod(MethodNames.onCastStateChanged, i)
}
}
//region FlutterPlugin interface
override fun onAttachedToEngine(binding: FlutterPlugin.FlutterPluginBinding) {
Log.d(TAG, "onAttachedToEngine")
onAttachedToEngine(binding.applicationContext, binding.binaryMessenger)
}
private fun onAttachedToEngine(applicationContext: Context, messenger: BinaryMessenger) {
this.applicationContext = applicationContext
val methodChannel = MethodChannel(messenger, "flutter_cast_framework")
methodChannel.setMethodCallHandler(this)
channel = methodChannel
mMessageCastingChannel = MessageCastingChannel(methodChannel)
CastContext.getSharedInstance(applicationContext).addCastStateListener { i ->
Log.d(TAG, "Cast state changed: $i")
methodChannel.invokeMethod(MethodNames.onCastStateChanged, i)
}
mSessionManager = CastContext.getSharedInstance(applicationContext).sessionManager
mCastSession = mSessionManager.currentCastSession
}
override fun onDetachedFromEngine(binding: FlutterPlugin.FlutterPluginBinding) {
Log.d(TAG, "onDetachedFromEngine")
applicationContext = null;
channel?.setMethodCallHandler(null);
channel = null;
mMessageCastingChannel = null
}
//endregion
//region ActivityAware
override fun onAttachedToActivity(binding: ActivityPluginBinding) {
Log.d(TAG, "onAttachedToActivity")
activity = binding.activity
}
override fun onDetachedFromActivityForConfigChanges() {
Log.d(TAG, "onDetachedFromActivityForConfigChanges")
activity = null
}
override fun onReattachedToActivityForConfigChanges(binding: ActivityPluginBinding) {
Log.d(TAG, "onReattachedToActivityForConfigChanges")
activity = binding.activity
}
override fun onDetachedFromActivity() {
Log.d(TAG, "onDetachedFromActivity")
activity = null
}
//endregion
private lateinit var mSessionManager: SessionManager
private val mSessionManagerListener = CastSessionManagerListener()
private val mMessageCastingChannel = MessageCastingChannel(channel)
private var channel: MethodChannel? = null
private var applicationContext: Context? = null
private var activity: Activity? = null
private var mMessageCastingChannel: MessageCastingChannel? = null
private var mCastSession: CastSession? = null
set(value) {
@ -53,14 +112,13 @@ class FlutterCastFrameworkPlugin(private val registrar: Registrar, private val c
field = value
channel.invokeMethod(MethodNames.getSessionMessageNamespaces, null, result)
channel?.invokeMethod(MethodNames.getSessionMessageNamespaces, null, result)
}
//region LifecycleObserver
@OnLifecycleEvent(Lifecycle.Event.ON_CREATE)
fun onCreate() {
Log.d(TAG, "App: ON_CREATE")
mSessionManager = CastContext.getSharedInstance(registrar.activeContext()).sessionManager
mCastSession = mSessionManager.currentCastSession
}
@OnLifecycleEvent(Lifecycle.Event.ON_RESUME)
@ -69,8 +127,13 @@ class FlutterCastFrameworkPlugin(private val registrar: Registrar, private val c
mSessionManager.addSessionManagerListener(mSessionManagerListener, CastSession::class.java)
mCastSession = mSessionManager.currentCastSession
val castState = CastContext.getSharedInstance(registrar.activeContext()).castState
channel.invokeMethod(MethodNames.onCastStateChanged, castState)
val context = applicationContext
if (context == null) {
Log.d(TAG, "App: ON_RESUME - missing context")
return
}
val castState = CastContext.getSharedInstance(context).castState
channel?.invokeMethod(MethodNames.onCastStateChanged, castState)
}
@OnLifecycleEvent(Lifecycle.Event.ON_PAUSE)
@ -83,14 +146,24 @@ class FlutterCastFrameworkPlugin(private val registrar: Registrar, private val c
// I can't set this to null because I need the cast session to send commands from notification
// mCastSession = null
}
//endregion
override fun onMethodCall(call: MethodCall, result: Result) {
val method = call.method
val arguments = call.arguments
when (method) {
MethodNames.showCastDialog -> CastDialogOpener.showCastDialog(registrar)
MethodNames.sendMessage -> this.mMessageCastingChannel.sendMessage(mCastSession, arguments)
MethodNames.showCastDialog -> {
val context = applicationContext
val activity = this.activity
if (context == null || activity == null) {
Log.d(TAG, "onMethodCall - missing context")
return
}
CastDialogOpener.showCastDialog(context, activity)
}
MethodNames.sendMessage -> this.mMessageCastingChannel?.sendMessage(mCastSession, arguments)
else -> result.notImplemented()
}
}
@ -122,8 +195,7 @@ class FlutterCastFrameworkPlugin(private val registrar: Registrar, private val c
try {
oldSession?.removeMessageReceivedCallbacks(it)
newSession?.setMessageReceivedCallbacks(it, mMessageCastingChannel)
}
catch (e: java.lang.Exception) {
} catch (e: java.lang.Exception) {
Log.e(TAG, "Updating mCastSession - Exception while creating channel", e)
}
}
@ -134,56 +206,56 @@ class FlutterCastFrameworkPlugin(private val registrar: Registrar, private val c
private var TAG = "SessionManagerListenerImpl"
override fun onSessionSuspended(session: CastSession?, p1: Int) {
Log.d(TAG, "onSessionSuspended")
channel.invokeMethod(MethodNames.onSessionSuspended, null)
Log.d(TAG, "onSessionSuspended - channel is null? ${channel == null}")
channel?.invokeMethod(MethodNames.onSessionSuspended, null)
}
override fun onSessionStarting(session: CastSession?) {
Log.d(TAG, "onSessionStarting")
channel.invokeMethod(MethodNames.onSessionStarting, null)
Log.d(TAG, "onSessionStarting - channel is null? ${channel == null}")
channel?.invokeMethod(MethodNames.onSessionStarting, null)
mCastSession = session
}
override fun onSessionResuming(session: CastSession?, p1: String?) {
Log.d(TAG, "onSessionResuming")
channel.invokeMethod(MethodNames.onSessionResuming, null)
Log.d(TAG, "onSessionResuming - channel is null? ${channel == null}")
channel?.invokeMethod(MethodNames.onSessionResuming, null)
mCastSession = session
}
override fun onSessionEnding(session: CastSession?) {
Log.d(TAG, "onSessionEnding")
channel.invokeMethod(MethodNames.onSessionEnding, null)
Log.d(TAG, "onSessionEnding - channel is null? ${channel == null}")
channel?.invokeMethod(MethodNames.onSessionEnding, null)
}
override fun onSessionStartFailed(session: CastSession?, p1: Int) {
Log.d(TAG, "onSessionStartFailed")
channel.invokeMethod(MethodNames.onSessionStartFailed, null)
Log.d(TAG, "onSessionStartFailed - channel is null? ${channel == null}")
channel?.invokeMethod(MethodNames.onSessionStartFailed, null)
}
override fun onSessionResumeFailed(session: CastSession?, p1: Int) {
Log.d(TAG, "onSessionResumeFailed")
channel.invokeMethod(MethodNames.onSessionResumeFailed, null)
Log.d(TAG, "onSessionResumeFailed - channel is null? ${channel == null}")
channel?.invokeMethod(MethodNames.onSessionResumeFailed, null)
}
override fun onSessionStarted(session: CastSession, sessionId: String) {
Log.d(TAG, "onSessionStarted")
channel.invokeMethod(MethodNames.onSessionStarted, null)
Log.d(TAG, "onSessionStarted - channel is null? ${channel == null}")
channel?.invokeMethod(MethodNames.onSessionStarted, null)
mCastSession = session
}
override fun onSessionResumed(session: CastSession, wasSuspended: Boolean) {
Log.d(TAG, "onSessionResumed")
channel.invokeMethod(MethodNames.onSessionResumed, null)
Log.d(TAG, "onSessionResumed - channel is null? ${channel == null}")
channel?.invokeMethod(MethodNames.onSessionResumed, null)
mCastSession = session
}
override fun onSessionEnded(session: CastSession, error: Int) {
Log.d(TAG, "onSessionEnded")
channel.invokeMethod(MethodNames.onSessionEnded, null)
Log.d(TAG, "onSessionEnded - channel is null? ${channel == null}")
channel?.invokeMethod(MethodNames.onSessionEnded, null)
}
}
}

View file

@ -1,5 +1,7 @@
package com.gianlucaparadise.flutter_cast_framework.cast
import android.app.Activity
import android.content.Context
import android.util.Log
import androidx.mediarouter.app.MediaRouteChooserDialog
import androidx.mediarouter.app.MediaRouteControllerDialog
@ -8,21 +10,20 @@ import com.google.android.gms.cast.framework.CastContext
import io.flutter.plugin.common.PluginRegistry
object CastDialogOpener {
fun showCastDialog(registrar: PluginRegistry.Registrar) {
val castContext = CastContext.getSharedInstance(registrar.activeContext())
fun showCastDialog(applicationContext: Context, activity: Activity) {
val castContext = CastContext.getSharedInstance(applicationContext)
val castSession = castContext.sessionManager.currentCastSession
val activity = registrar.activity()
val themeResId = activity.packageManager.getActivityInfo(activity.componentName, 0).themeResource
try {
if (castSession != null) {
// This dialog allows the user to control or disconnect from the currently selected route.
MediaRouteControllerDialog(registrar.activeContext(), themeResId)
MediaRouteControllerDialog(applicationContext, themeResId)
.show()
} else {
// This dialog allows the user to choose a route that matches a given selector.
MediaRouteChooserDialog(registrar.activeContext(), themeResId).apply {
MediaRouteChooserDialog(applicationContext, themeResId).apply {
routeSelector = castContext.mergedSelector
show()
}

View file

@ -1 +1 @@
{"info":"This is a generated file; do not edit or check into version control.","plugins":{"ios":[{"name":"flutter_cast_framework","path":"/Users/gianluca.paradiso/mydev/cast-your-instructions/flutter_cast_framework/","dependencies":[]}],"android":[{"name":"flutter_cast_framework","path":"/Users/gianluca.paradiso/mydev/cast-your-instructions/flutter_cast_framework/","dependencies":[]}],"macos":[],"linux":[],"windows":[],"web":[]},"dependencyGraph":[{"name":"flutter_cast_framework","dependencies":[]}],"date_created":"2021-09-24 07:06:05.488267","version":"2.5.1"}
{"info":"This is a generated file; do not edit or check into version control.","plugins":{"ios":[{"name":"flutter_cast_framework","path":"/Users/gianluca.paradiso/mydev/cast-your-instructions/flutter_cast_framework/","dependencies":[]}],"android":[{"name":"flutter_cast_framework","path":"/Users/gianluca.paradiso/mydev/cast-your-instructions/flutter_cast_framework/","dependencies":[]}],"macos":[],"linux":[],"windows":[],"web":[]},"dependencyGraph":[{"name":"flutter_cast_framework","dependencies":[]}],"date_created":"2021-09-26 17:19:53.237182","version":"2.5.1"}