Skip to main content

Flutter How to Start Android Activity from Flutter View


Flutter and Dart is an excellent combination for creating the UI, but for accessing the platform-specific service we need to open platform-specific activity. So lets in this article we will explore how to start an android activity and access the service from Flutter View.

Create a Project for this Android Activity Flutter View Demo

Create a Project
  1. From File menu select the New Flutter Project
  2. Enter the project name
  3. Select the AndroidX support and click on next
  4. After the above, we step click on Finish
    We will have the following project structure created. Flutter Project Structure

Create the Second Activity in Android


Just go to the android folder and open it in separate windows. We will have the following project structure.





Start Activity From Flutter View




Create the Activity

Just right click on the Kotlin folder and create a blank activity from the menu. If you create the activity then you may be required to upgrade the Gradle and do some import. So Just click on update and wait for the project sync completed.

Update the project build config build.gradle file

Due to some problem, it may happen that we have some error in the build.gradle file.

   ext.kotlin_version = '1.3.41' '1.2.71'

Now, remove the '1.2.71' from the ext.kolin_version and start the sync again. If all these issues resolved then the sync will be completed successfully;

Go to ou newly created activity and add the dependency by clicking on Alt+Enter key. Or alternatively, you can add the appcompat dependency directly into your build.gradle files like below.


dependencies {
    implementation "org.jetbrains.kotlin:kotlin-stdlib-jdk7:$kotlin_version"
    implementation 'androidx.constraintlayout:constraintlayout:1.1.3'
    testImplementation 'junit:junit:4.12'
    androidTestImplementation 'androidx.test:runner:1.1.1'
    androidTestImplementation 'androidx.test.espresso:espresso-core:3.1.1'
    implementation 'androidx.appcompat:appcompat:1.1.0'
}

Create the Theme for our activity

Now, we need to create an AppCompat Theme for our activity. So go to res->value->style.xml files and add the theme.

<style name="MyTheme" parent="@style/Theme.AppCompat.Light.DarkActionBar">
        <item name="colorPrimary">#7B1FA2</item>
        <item name="colorPrimaryDark">#4A148C</item>
        <item name="colorAccent">@android:color/holo_blue_light</item>
        <item name="android:windowBackground">@drawable/launch_background</item>
    </style>

Set the theme to Android Activity

Open the file AndroidMenifest.xml file and set the theme like below.

 <activity android:name=".KotlinActivity"
            android:theme="@style/MyTheme">  
 </activity>

Create the method to start the second Activity

Go to the main activity again and add the required method as like below.

package com.nplix.android_activity_demo

import android.content.Intent
import android.os.Bundle

import io.flutter.app.FlutterActivity
import io.flutter.plugin.common.MethodChannel
import io.flutter.plugins.GeneratedPluginRegistrant

class MainActivity: FlutterActivity() {
  private val CHANNEL = "com.startActivity/testChannel"
  override fun onCreate(savedInstanceState: Bundle?) {
    super.onCreate(savedInstanceState)
    GeneratedPluginRegistrant.registerWith(this)

    MethodChannel(flutterView,CHANNEL).setMethodCallHandler{ call,result ->
      if(call.method.equals("StartSecondActivity")){
        val intent=Intent(this,KotlinActivity::class.java)
        startActivity(intent)
        result.success("ActivityStarted")
      }
      else{
        result.notImplemented()
      }
    }
  }
}

So what we are doing here?
  • First of all, we are defining a channel using the line private val CHANNEL = "com.startActivity/testChannel" we will use this to create the platform from the flutter view.
  • Create a method handler in the line

MethodChannel(flutterView,CHANNEL).setMethodCallHandler{ call,result ->
      if(call.method.equals("StartSecondActivity")){
        val intent=Intent(this,KotlinActivity::class.java)
        startActivity(intent)
        result.success("ActivityStarted")
      }
      else{
        result.notImplemented()
      }
    }

  • Third, we are comparing the called method using the if condition and starting the activity.
  • In the case method not match then we will throw the method not implemented the method using the below line.

 else{
        result.notImplemented()
      }

Call the Android Method from Flutter View

Now time call the android method to start the activity from Flutter View. So let's create a button to start the activity.
 RaisedButton(
              color: Colors.blue,
              onPressed: (){
                _startActivity();
              },
              child: Padding(
                padding: const EdgeInsets.all(16.0),
                child: Text(
                  'Start Android Activity',
                  style: TextStyle(color: Colors.white,fontSize: 24),
                ),
              ),
            ),

Create the _startActivity()
Future<void> _startActivity() async {
    try {
      final String result = await platform.invokeMethod('StartSecondActivity');
      debugPrint('Result: $result ');
    } on PlatformException catch (e) {
      debugPrint("Error: '${e.message}'.");
    }
  }

So before that, we need to create the platform as well using the below code.
 static const platform = const MethodChannel('com.startActivity/testChannel');




Run and Test the App


Let's test the application. If you run it it will be like below.


Start Activity From Flutter View


Start Activity From Flutter View




Wrapping Up

This is just a very basic demo of how to call the platform-specific method, service or function from flutter view. In short, we can say that using this you can perform anything that you can do in normal android application written in Kotlin or Java.





Comments

  1. Could I get the sourcecode for this demo. I'm not sure where there Kotlin class goes.

    ReplyDelete
  2. Kotlin class goes inside the android folder for example: demo\android\app\src\main\kotlin\com\nplix\demo\MainActivity.kt where package name is com.nplix.demo.
    Its better to open the android directory as separate module for platform specific code.

    ReplyDelete
  3. However, I have updated the source code at https://github.com/debugandroid/flutter_android_activity_demo for reference.

    ReplyDelete

Post a Comment

Popular posts from this blog

WordPress Android App with REST API And Retrofit

Retrofit is the library which converts your JSON data into Java object. In this tutorial, we will learn about how to implement the Retrofit to create a WordPress Mobile App. As we all know, WordPress is the one of the biggest CMS (Content Management System) of the world. Wordpress full fill the requirements for all most every type of the website. So, in this tutorial, I am going to learn how to create an Android App using the WordPress REST API and Retrofit.
What is Retrofit?
If you want to know about Retrofit, I would like to give you just a simple one-line explanation of the Retrofit. It is a library which converts your REST HTTP request to Java interface. We will learn how we can do all these stuff using some very simple steps.

Further, you can check the Retrofit Library here.

So, In this tutorial, we will use the Retrofit to retrieve all post and there except ( A short Description of Post) form a WordPress website.
Prerequisite for using the Retrofit for WordPress Android App
There is s…

WP Android App using REST and volley

In this tutorial, we are going to create a sample app for WordPress using the rest API for Android. For successful implementation of the rest API for WordPress we need to it in two parts. In the first part, we will learn some basic configuration on the server side and configure the Android project in android using the Android Studio.


WP Android App using REST and volley part1
WP Android App using REST and volley part2
LiveData and ViewModel for WP Android App using REST and volley part3


Requirement to create the Android App for WordPress


WordPress API is included in core release of the WordPress version 4.7 and above.
For older version, you need to install the WordPress plugin API
Android Studio 2.X.X or 3.X.X


If you are using the WordPress version 4.7 and above you do not require any special configuration for this, you can just test your configuration by sending the sample request to the  http://yoursite/wp-json/ . You will get the output into the JSON format.

Now, If you are using the older …