How can an EMM/MDM controlled device's flutter built app read the mananged application config profile information?
Background. The application currently is reading environment variables that are getting pushed in via the build process and I am looking to change this to using an MDM application profile that we can control.
Today:
const environment = String.fromEnvironment('environment', defaultValue: 'dev');
Where I want to go is implement this in flutter but I can't determine how to get access to:RestrictionsManager:
var myRestrictionsMgr =
activity?.getSystemService(Context.RESTRICTIONS_SERVICE) as RestrictionsManager
I was able to figure this out. In the MainActivity.kt:
class MainActivity: FlutterActivity() {
private val CHANNEL = "com.yourstuff.whatever/something"
override fun configureFlutterEngine(flutterEngine: FlutterEngine) {
super.configureFlutterEngine(flutterEngine)
MethodChannel(flutterEngine.dartExecutor.binaryMessenger, CHANNEL).setMethodCallHandler {
call, result ->
var myRestrictionsMgr =
activity?.getSystemService(Context.RESTRICTIONS_SERVICE) as RestrictionsManager
var appRestrictions: Bundle = myRestrictionsMgr.applicationRestrictions
result.success(appRestrictions.getString(call.method))
}
}
}
And in flutter to call it:
const platform = const MethodChannel("com.yourstuff.whatever/something");
platform.invokeMethod("restrictionname");
Related
I am trying to integrate stripe terminal code with my android app build using kotlin, unfortunately I am getting the following run time error which I could not able to fix
java.lang.IllegalStateException: initTerminal must be called before attempting to get the instance
The code I have added is used below
override fun onCreate(savedInstanceState: Bundle?) {
super.onCreate(savedInstanceState)
setContentView(R.layout.activity_pay_screen)
onDiscoverReaders()
}
fun onDiscoverReaders() {
val config = DiscoveryConfiguration(
timeout = 0,
discoveryMethod = DiscoveryMethod.LOCAL_MOBILE,
isSimulated = false,
location = "xxxxxxxxxxxxxxx"
)
// Save this cancelable to an instance variable
discoveryCancelable = Terminal.getInstance().discoverReaders(config,
discoveryListener = object : DiscoveryListener {
override fun onUpdateDiscoveredReaders(readers: List<Reader>) {
}
}
, object : Callback {
override fun onSuccess() {
println("Finished discovering readers")
}
override fun onFailure(e: TerminalException) {
e.printStackTrace()
}
})
}
I have added this to one of my activity and my intention is to check if my phone is supporting stripe tap on mobile
I guess the issue could be calling onDiscoverReaders() from a wrong place, someone please help me to fix this issue
Thanks in advance
In stripe docs you can check
// Create your listener object. Override any methods that you want to be notified about
val listener = object : TerminalListener {
}
// Choose the level of messages that should be logged to your console
val logLevel = LogLevel.VERBOSE
// Create your token provider.
val tokenProvider = TokenProvider()
// Pass in the current application context, your desired logging level, your token provider, and the listener you created
if (!Terminal.isInitialized()) {
Terminal.initTerminal(applicationContext, logLevel, tokenProvider, listener)
}
// Since the Terminal is a singleton, you can call getInstance whenever you need it
Terminal.getInstance()
might be you missed to initialise terminal before getting Instance so try add above code before onDiscoverReaders()
The error speaks for itself - first you need to initialize the api terminal, and then call the terminal instance.
Based on the documentation, we follow the following steps to get started with the api terminal:
Initialize the terminal application in the application class of the
application
class App : Application() {
override fun onCreate() {
super.onCreate()
TerminalApplicationDelegate.onCreate(this)
}
}
We request the necessary permissions for correct work with the
terminal search (bluetooth, geolocation), if everything is provided,
we call the init terminal with parameters like that:
Terminal.initTerminal(
context = context,
logLevel = LogLevel.VERBOSE,
tokenProvider = TokenProvider(),
listener = object : TerminalListener {
override fun onUnexpectedReaderDisconnect(reader: Reader) {
Log.d("log", "onUnexpectedReaderDisconnect")
}
override fun onConnectionStatusChange(status: ConnectionStatus) {
super.onConnectionStatusChange(status)
Log.d("log", "onConnectionStatusChange")
}
override fun onPaymentStatusChange(status: PaymentStatus) {
super.onPaymentStatusChange(status)
Log.d("log", "onPaymentStatusChange")
}
}
)
After this initialization, you can call the terminal instance and
work with it.
I am trying to open FlutterActivity in my existing android application. Before I was creating new flutter engine every time I was opening activity like this:
FlutterActivity
.withNewEngine()
.build(context)
And everything was working fine besides a little lag while opening the activity. To get rid of the lag I wanted to switch to using cached engine. I followed this official tutorial: LINK
And ended up with smething like this:
In my Application class:
class App : Application() {
lateinit var flutterEngine: FlutterEngine
override fun onCreate() {
...
flutterEngine = FlutterEngine(this)
flutterEngine.dartExecutor.executeDartEntrypoint(
DartExecutor.DartEntrypoint.createDefault()
)
FlutterEngineCache
.getInstance()
.put("myEngineId", flutterEngine)
}
}
And later in my application on the button click, in the same place that I was successfully opening FlutterActivity:
FlutterActivity
.withCachedEngine("myEngineId")
.build(context)
So I basically followed the all the instructions but the effect that I get now is after the button click there is even longer lag than before and then there is only black screen being displayed. My flutter screen is not displayed and application is kind of frozen I can't go back or do anything. There is also no error or any useful info in the logs. I have no idea what is going on. What am I doing wrong?
To Use cached FlutterEngine
In FlutterActivity you must declare provideFlutterEngine method.
class DemoActivity : FlutterActivity() {
override fun provideFlutterEngine(context: Context): FlutterEngine? =
FlutterEngineCache.getInstance().get(FlutterConstants.ENGINE_ID)
override fun configureFlutterEngine(flutterEngine: FlutterEngine) {
super.configureFlutterEngine(flutterEngine)
MethodChannel(flutterEngine.dartExecutor.binaryMessenger, "demo-channel")
.setMethodCallHandler { call, result ->
if (call.method == "demo-method") {
demoMethod()
result.success(null)
} else {
result.notImplemented()
}
}
}
private fun demoMethod() {
// Do native code
}
}
I want to send data with intent from native android app to flutter app, So if flutter app is closed below code working fine to fetch intent data in main.dart file. If flutter app is in foreground and i tries to send data from native app to flutter app nothing happens. Is their anything else to need implement for this case?
Native app code to start flutter app
var intent = getPackageManager().getLaunchIntentForPackage("com.flutterapp");
intent.putString( "MapParams", jsonObj.toString())
startActivity(intent)
Flutter app code
class MainActivity: FlutterActivity()
var sharedData="";
override fun configureFlutterEngine(#NonNull flutterEngine: FlutterEngine) {
super.configureFlutterEngine(flutterEngine)
GeneratedPluginRegistrant.registerWith(flutterEngine)
MethodChannel(flutterEngine.dartExecutor.binaryMessenger,
"share_channel").setMethodCallHandler { call, result ->
if (call.method == "MapParams") {
handleIntent()
result.success(sharedData)
sharedData = ""
}
}
}
private fun handleIntent() {
if (getIntent().hasExtra("MapParams")) {
getIntent().getSerializableExtra("MapParams")?.let { intentData ->
sharedData = intentData.toString()
}
}
}
Main.Dart file
Future<String> getSharedData() async {
return await MethodChannel('share_channel')
.invokeMethod("MapParams") ??
"";
}
I am building a Flutter Application, and for one of the API's I am using, it does not have Flutter support, only Android and iOS. My solution to this was to use Platform Channels, but how would I pass an Image as an argument?
To explain a little further, I am picking an image from the gallery with ImagePicker().getImage in the dart file, and I want to send the image selected to the method in the Kotlin file that will do something with the image on its end and return a string.
After looking at the docs, I was able to make a channel like this:
static const platform = const MethodChannel('app.dev/channel');
final string result = await platform.invokeMethod('returnStringfromImage');
And in the Kotlin file:
private val CHANNEL = "app.dev/channel"
override fun configureFlutterEngine(#NonNull flutterEngine: FlutterEngine) {
super.configureFlutterEngine(flutterEngine)
MethodChannel(flutterEngine.dartExecutor.binaryMessenger, CHANNEL).setMethodCallHandler {
// Note: this method is invoked on the main thread.
call, result ->
if (call.method == "returnStringfromImage") {
val return = returnStringfromImage(call.arguments)
}
else {
result.notImplemented()
}
}
}
How would I send the image over, and pass it as an argument for the returnStringfromImage() method? Thank you!
You need to convert the picked image to any of these supported types, most probably as bytes (Uint8list) to send over to the platform side.
ImagePicker would return a File, so You can call readAsBytes on it to get Uint8list. Then you can pass it via arguments of invokeMethod.
I have successfully integrated flutter module in my native android application by following steps here .
The process of caching flutter engine I have already done in Application class. I am launching my flutter screen with this from android fragment.
startActivity(
FlutterActivity
.withCachedEngine("my_engine_id")
.build(currentActivity)
);
Now I want to pass my auth token to flutter module for making api calls.
I am following the process from here and created method channel in dart code but I do not know where to create the method channel in the native side.
If I am creating it in project/moduleName/.android/app/src/main/java/com/package/host/MainActivity.java
It is giving exception Unhandled Exception: MissingPluginException(No implementation found for method
Also note that this folder is placed in .gitignore by default when I created this flutter module in Android studio.
I already has a look at older tutiorals but this caching of flutter engine option is not there in them.
Please tell where am I doing wrong ?
You need to have a reference for the Flutter Engine and then use it to create the Method Channel. Take in account that the activity/fragment that launch the Flutter activity is in charge to manage the Method Channel.
private const val FLUTTER_ENGINE_ID = "flutter_engine"
private const val CHANNEL = "myApp.flutter.dev/auth"
class MainActivity : AppCompatActivity(R.layout.activity_main) {
private lateinit var flutterEngine: FlutterEngine
override fun onCreate(savedInstanceState: Bundle?) {
super.onCreate(savedInstanceState)
setupFlutterEngine()
setupMethodChannel()
setSupportActionBar(findViewById(R.id.toolbar))
fab.setOnClickListener {
launchFlutterModule()
}
}
private fun setupFlutterEngine() {
createAndConfigureFlutterEngine()
FlutterEngineCache
.getInstance()
.put(FLUTTER_ENGINE_ID, flutterEngine)
}
private fun createAndConfigureFlutterEngine() {
flutterEngine = FlutterEngine(this)
flutterEngine.dartExecutor.executeDartEntrypoint(DartExecutor.DartEntrypoint.createDefault())
}
private fun setupMethodChannel() {
MethodChannel(
flutterEngine.dartExecutor.binaryMessenger,
CHANNEL
).setMethodCallHandler { call, result ->
// All your implementation for auth token
}
}
private fun launchFlutterModule() {
startActivity(getFlutterIntent())
}
private fun getFlutterIntent(): Intent {
return FlutterActivity
.withCachedEngine(FLUTTER_ENGINE_ID)
.backgroundMode(FlutterActivityLaunchConfigs.BackgroundMode.transparent)
.build(this)
}
}
You can make a Wrapper where you can hold the method channel code and flutter engine setup, and this wrapper is init in your Application class or maybe init and injected with Dagger or Hilt where is needed.
You can pass simple data as request parameters.
Android code:
FlutterActivity
.withNewEngine()
.initialRoute("/MyPage?username=my_user&age=30&gender=male")
.build(MainActivity.this)
Flutter code, I use GetX library to get the parameters
Map<String, String?> parameters = Get.parameters;
print("parameters: $parameters");
Output:
parameters: {username: my_user, age: 30, gender: male}
First create flutter platform client with channel
set methodCallHamdler passing same channel
Refer this official doc-
https://flutter.dev/docs/development/platform-integration/platform-channels