I want my flutter app to get a notification every time the android system back button is pressed, and furthermore, I want to otherwise disable the back button. So this is the code I have on the kotlin side of things:
package com.example.ui
import io.flutter.embedding.android.FlutterActivity
import io.flutter.embedding.engine.FlutterEngine
import io.flutter.plugin.common.MethodChannel
class MainActivity: FlutterActivity() {
override fun onBackPressed() {
// send message to flutter that the system back button was pressed
val flutterEngine = getFlutterEngine()
if (flutterEngine != null) {
MethodChannel(flutterEngine!!.dartExecutor.binaryMessenger, "backButtonChannel").invokeMethod("backButtonPressed", null)
}
}
}
and here's my flutter app main function:
Future<void> backButtonPressed() async {
// Code to run when the back button is pressed
print('PRESSED!');
}
const platform = MethodChannel('com.example.ui/back_button');
void main() {
WidgetsFlutterBinding.ensureInitialized();
platform.setMethodCallHandler((call) async {
if (call.method == "backButtonPressed") {
return backButtonPressed();
}
});
return runApp(MyApp());
}
Unfortunately it seems to have no effect, are you able to see why?
You should make a call by using registered MethodChannel channel
Your kotlin code should be like
MethodChannel(flutterEngine!!.dartExecutor.binaryMessenger, "com.example.ui/back_button").invokeMethod("backButtonPressed", null)
I suggest to use WillPopScope widget to handle back press from dart code
Related
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") ??
"";
}
How do you trigger a native Android back button press from inside a React Native button that is handled somewhere else in the application.
For example,
<Pressable onPress={nativeGoBack} />
The event is then handled in another component using the BackHandler API.
BackHandler.addEventListener('hardwareBackPress', () => {
// Perform action
});
NB: This is not a React Navigation specific question (So navigation.goBack() is not a solution).
If you want to communicate from react native to adnroid, you should use Native modules.
See documentation https://reactnative.dev/docs/native-modules-android
In short:
Create a native module which handle backbutton from specific activity
class BackPressReactModule(reactContext: ReactApplicationContext?) : ReactContextBaseJavaModule(reactContext) {
override fun getName(): String {
return "BackPressReactModule"
}
#ReactMethod
fun goBack() {
val context = reactApplicationContext
val currentActivity = context.currentActivity as Activity
currentActivity.onBackPressed()
}
}
Register BackPressReactModule into your packages in ReactNativeHost. (See documentation)
After successfully exposing module, you can call it from javascript like this:
import {NativeModules} from 'react-native';
const {BackPressReactModule} = NativeModules;
BackPressReactModule.goBack();
I am working on a native Android widget in a Flutter App. In which there is refresh button, on click of that I have to call a method in the Flutter code. I am using Flutter Method Channel for the communication and it is working fine when app is in foreground. But it does not work when app is minimised or closed. I get error PlatformException(NO_ACTIVITY, null, null). Below is my code.
Android (AppWidgetProvider)
if (methodChannel == null && context != null) {
FlutterMain.startInitialization(context)
FlutterMain.ensureInitializationComplete(context, arrayOf())
// Instantiate a FlutterEngine.
val engine = FlutterEngine(context.applicationContext)
// Define a DartEntrypoint
val entrypoint: DartEntrypoint = DartEntrypoint.createDefault()
// Execute the DartEntrypoint within the FlutterEngine.
engine.dartExecutor.executeDartEntrypoint(entrypoint)
// Register Plugins when in background. When there
// is already an engine running, this will be ignored (although there will be some
// warnings in the log).
//GeneratedPluginRegistrant.registerWith(engine)
methodChannel = MethodChannel(engine.dartExecutor.binaryMessenger, MainActivity.CHANNEL)
}
methodChannel!!.invokeMethod("fetchNewData", "", object : MethodChannel.Result {
override fun notImplemented() {
Toast.makeText(context, "method not implemented", Toast.LENGTH_SHORT).show()
}
override fun error(errorCode: String?, errorMessage: String?, errorDetails: Any?) {
Toast.makeText(context, errorMessage, Toast.LENGTH_SHORT).show()
}
override fun success(result: Any?) {
Toast.makeText(context, "success", Toast.LENGTH_SHORT).show()
}
})
Flutter
/// calling in main
static Future<void> attachListeners() async {
WidgetsFlutterBinding.ensureInitialized();
var bloc = new AqiCnDashboardBloc();
_channel.setMethodCallHandler((call) {
switch (call.method) {
case 'fetchNewData':
bloc.getAqiCn(false);
return null;
default:
throw MissingPluginException('notImplemented');
}
});
}
I am collecting information/discussion that redirects us to run flutter engine in background.
void callbackDispatcher() {
WidgetsFlutterBinding.ensureInitialized();
print("Our background job ran!");
}
void main() {
static const MethodChannel _channel = const MethodChannel("channel-name");
Future<void> initialize(final Function callbackDispatcher) async {
final callback = PluginUtilities.getCallbackHandle(callbackDispatcher);
await _channel.invokeMethod('initialize', callback.toRawHandle());
}
}
As stated here How to run Flutter in the background?
When a background job is started by native the Flutter engine is not active. So we are unable to run Dart.
Can Android/iOS starts the Flutter engine in the background?
Yes! We’ll first need to register a Dart callback function which will only be invoked whenever a background job is started by the native code.
This callback function is referred to as a callbackDispatcher.
Also please check out these stackoverflow discussions.
Flutter : Run an app as a background service
How to create a service in Flutter to make an app to run always in background?
How to create a Flutter background service that works also when app closed
Executing Dart in the Background with Flutter Plugins and Geofencing
You may start the Flutter Engine in the background by register a Dart callback function which will only be invoked whenever a background job is started in Flutter.
Try this.
https://medium.com/vrt-digital-studio/flutter-workmanager-81e0cfbd6f6e
I have searched the Flutter documentation and googled this, but with zero result. I am developing my first Flutter app for android and I would like to create a custom quick settings tile for it. I am targeting Nougat and above. I know it's possible in Java and Kotlin (e.g. https://android.jlelse.eu/develop-a-custom-tile-with-quick-settings-tile-api-74073e849457), but how about Dart/Flutter?
You can do it natively (makes more sense since it is an Android-only feature).
Every Flutter contains an android and ios folder. Inside of those folders, you will find the wrapper apps for Android and iOS.
Just open the Android project in Android Studio and follow the tutorial you linked.
You can create Quick setting tile natively
Go to android/app/src/main/kotlin/package_name(folder)
Create a service class MyTileService.kt
MyTileService.kt
#RequiresApi(Build.VERSION_CODES.N)
//Quick Tile feature can be used Build.VERSION_CODES.N or Greater
class MyTileService : TileService() {
// Called when the user adds your tile.
override fun onTileAdded() {
super.onTileAdded()
}
// Called when your app can update your tile.
override fun onStartListening() {
super.onStartListening()
val tile = qsTile // this is getQsTile() method form java, used in Kotlin as a property
tile.label = "Set Alarm"
tile.state = Tile.STATE_ACTIVE
tile.icon = Icon.createWithResource(this, R.drawable.baseline_alarm_24)
tile.updateTile() // you need to call this method to apply changes
}
// Called when your app can no longer update your tile.
override fun onStopListening() {
super.onStopListening()
}
// Called when the user taps on your tile in an active or inactive state.
override fun onClick() {
super.onClick()
try{
// to open flutter activity
val newIntent= FlutterActivity.withNewEngine().dartEntrypointArgs(listOf("launchFromQuickTile")).build(this)
newIntent.flags= Intent.FLAG_ACTIVITY_NEW_TASK
startActivityAndCollapse(newIntent)
}
catch (e:Exception){
Log.d("debug","Exception ${e.toString()}")
}
}
// Called when the user removes your tile.
override fun onTileRemoved() {
super.onTileRemoved()
}
}
In AndroidManifest.xml
<service
android:name=".MyTileService"
android:exported="true"
android:icon="#drawable/baseline_alarm_24" //your_vector_icon
android:label="Set Alarm" //tile lable
android:permission="android.permission.BIND_QUICK_SETTINGS_TILE">
<intent-filter>
<action
android:name="android.service.quicksettings.action.QS_TILE" />
</intent-filter>
</service>
running your app will create a quick setting tile for your app
if not showing -> try to edit the notification panel icons (xiaomi/mi devices)
onClick on this quick settings icon we want to show our flutter screen
Inside main.dart
Future<void> main(List<String> arguments) async {
WidgetsFlutterBinding.ensureInitialized();
runApp(MyApp(
msg: arguments.isNotEmpty ? arguments[0] : null,
));
}
class MyApp extends StatelessWidget {
const MyApp({Key? key, this.msg}) : super(key: key);
final String? msg;
#override
Widget build(BuildContext context) {
return MaterialApp(
initialRoute: msg == "launchFromQuickTile" ? Create.routeName :
Home.routeName,
routes: //your routes,
);
}
}
For more information about quick settings tile