extend AppCompatActivity vs extend flutterActivity

Viewed 1761
1 Answers

Can I use another java class for methodChannels?

Yes, you can use another java class for methodChannels. You can write it anywhere in your application like this:

public class MyFlutterActivity extends FlutterActivity {
private static final String CHANNEL = "samples.flutter.io/battery";

@Override
public void configureFlutterEngine(@NonNull FlutterEngine flutterEngine) {
    GeneratedPluginRegistrant.registerWith(flutterEngine);

    new MethodChannel(flutterEngine.getDartExecutor().getBinaryMessenger(), CHANNEL).setMethodCallHandler(((methodCall, result) -> {
        if (methodCall.method.equals("getBatteryLevel")) {

            result.success("batteryLevel"); // It returns string "batteryLevel".

        } else {
            result.notImplemented();
        }
    }));
 }
}

Then you can start that Flutter engine with related class like this:

startActivity(
  new FlutterActivity.NewEngineIntentBuilder(MyFlutterActivity.class).build(getApplicationContext())
 );

Of course, you need to define that class in your AndroidManifest.xml:

   <activity android:name=".MyFlutterActivity"
    android:theme="@style/AppTheme"
    android:configChanges="orientation|keyboardHidden|keyboard|screenSize|locale|layoutDirection|fontScale|screenLayout|density|uiMode"
    android:hardwareAccelerated="true"
    android:windowSoftInputMode="adjustResize"
    />
Related