Run flutter code when android application class starts

Run flutter code when android application class starts

By : Gerard TV
Date : November 29 2020, 12:01 PM
I wish this helpful for you Short answer, Yes
You can call a Dart method in background using it's handle key.
code :
public class MyApp extends FlutterApplication implements PluginRegistry.PluginRegistrantCallback {

    public void registerWith(io.flutter.plugin.common.PluginRegistry registry) {
        // For apps using FlutterEmbedding v1
       // App with V2 will initialize plugins automatically, you might need to register your own however
/// Define this TopLevel or static
void _setup() async {
  MethodChannel backgroundChannel = const MethodChannel('flutter_background');
  // Setup Flutter state needed for MethodChannels.

  // This is where the magic happens and we handle background events from the
  // native portion of the plugin.
  backgroundChannel.setMethodCallHandler((MethodCall call) async {
    if (call.method == 'handleBackgroundMessage') {
      final CallbackHandle handle =
      final Function handlerFunction =
      try {
        var dataArg = call.arguments['message'];
        if (dataArg == null) {
          print('Data received from callback is null');
        await handlerFunction(dataArg);
      } catch (e) {
        print('Unable to handle incoming background message.\n$e');
    return Future.value();
_bgFunction(dynamic message) {
    // Message received in background
    // Remember, this will be a different isolate. So, no widgets
// dart:ui needed
CallbackHandle setup PluginUtilities.getCallbackHandle(_setup);
CallbackHandle handle PluginUtilities.getCallbackHandle(_bgFunction);

  <String, dynamic>{
    'handle': handle.toRawHandle(),
    'setup': setup.toRawHandle()
public void onMethodCall(MethodCall call, MethodChannel.Result result) {
  String methodName = call.method
  if (methodName == "handleFunction") {
     long handle = call.argument("handle");
     long setup = call.argument("setup");
     // save them

FlutterMain.ensureInitializationComplete(context, null)
val appBundlePath = FlutterMain.findAppBundlePath()
val flutterCallback = FlutterCallbackInformation.lookupCallbackInformation(setupHandleYouHadSaved)

FlutterNativeView backgroundFlutterView = FlutterNativeView(context, true)

val args = FlutterRunArguments()
args.bundlePath = appBundlePath
args.entrypoint = flutterCallback.callbackName
args.libraryPath = flutterCallback.callbackLibraryPath


// Initialize your registrant in the app class
val backgroundChannel = MethodChannel(messenger, "pushe_flutter_background")
private fun sendBackgroundMessageToExecute(context: Context, message: String) {
    if (backgroundChannel == null) {

    val args: MutableMap<String, Any?> = HashMap()
    if (backgroundMessageHandle == null) {
        backgroundMessageHandle = getMessageHandle(context)
    args["handle"] = backgroundMessageHandle
    args["message"] = message
    // The created background channel at step 7
    backgroundChannel?.invokeMethod("handleBackgroundMessage", args, null)

Share : facebook icon twitter icon
Call a service class Once in a day when application is Starts in android ,with less Battery Consumption

Call a service class Once in a day when application is Starts in android ,with less Battery Consumption

By : Kumar Prakash
Date : March 29 2020, 07:55 AM
will be helpful for those in need I found the answer for my Question using Shared pref.
When Activity is Starting ,First time in a day Async task will run. then inside on Post execute todays date is saved.
code :
// Shared Preferences
    SharedPreferences settingsShrepref;

    // Editor for Shared preferences
    SharedPreferences.Editor editor;
    // Sharedpref file name
    private static final String PREF_NAME = "MyPrefFileShred";

    // User name (make variable public to access from outside)
    public static final String KEY_TODAY_DATE_ANDTIME = "TimeToday";
    /* Added Servcie count Once in a day Fetch from Server*/

            try {

                DateFormat dateFormat = new SimpleDateFormat("dd-MM-yyyy");
                Date date = new Date();
                 TodayDate_String = dateFormat.format(date);

                settingsShrepref = getSharedPreferences(PREF_NAME, 0);
                editor = settingsShrepref.edit();

                String Val=settingsShrepref.getString(KEY_TODAY_DATE_ANDTIME,"");

                Log.i("Stored Val", Val);
                Log.i("Today date", TodayDate_String);

                    //for  SYNC web to Local
                        Log.d("Comments", "FirstTime Started");

                        // get Internet status
                        isInternetPresent = cd1.isConnectingToInternet();

                        // check for Internet status
                        if (isInternetPresent)
                            new AsyncCallWSCategoryCOUNTFetch().execute();

                        else {

                            Log.i("CATEGORY COUNT ", "Not Internet ......!");
                    catch (Exception e)
                        Log.i(" CATEGORY COUNT ", "EXCEPTION in reading Data from Web Async task ONstart ......!");


                    Log.d("Comments", "Second TIme");

            } catch (Exception e) {
                Log.i("", "Exception here Run Service.");
        protected void onPostExecute(Void result)
            Log.i(TAG_CategoryCOUNT, "onPostExecute");

            try {

                //the app is being launched for first time in a Day, do something
                Log.d("Comments", "First Time");

                // Storing name in pref
                editor.putString(KEY_TODAY_DATE_ANDTIME, TodayDate_String);
                // commit changes

                String Val=settingsShrepref.getString(KEY_TODAY_DATE_ANDTIME, null);
                Log.d("after Insertion data Date", Val);

            } catch (Exception e) {


Best way to distribute Flutter application Android & iOS. Best Practices in Flutter Beta Distribution

Best way to distribute Flutter application Android & iOS. Best Practices in Flutter Beta Distribution

By : dalep
Date : March 29 2020, 07:55 AM
it fixes the issue First, there is no need to submit a different build to either of them. The only thing you need to make sure is if there is a already a build in production mode, the build you are currently submitting must have higher version code than existing.
For Android, you have many options,
Trigger code when alarm from Clock-application starts in Android

Trigger code when alarm from Clock-application starts in Android

By : Жанна Васильева
Date : March 29 2020, 07:55 AM
this will help Warning: You are trying to get a notification about a Clock's state. This app is not part of official Android SDK: the solution below is not supported (or recommended) by Google and subject to change without notice.
Take a look at the source code od DeskClock (a new name for AlarmClock). Specifically take a look at it's AndroidManifest.xml.
How to debug code executed at application's startup if application is hosted in IIS and starts when IIS does?

How to debug code executed at application's startup if application is hosted in IIS and starts when IIS does?

By : user5587463
Date : March 29 2020, 07:55 AM
Any of those help I have a .NET application which is server framework and it is hosted in IIS and it starts when IIS does. , Add
how to use c++ code in flutter (android) application?

how to use c++ code in flutter (android) application?

By : huangsunyang
Date : March 29 2020, 07:55 AM
help you fix your problem Update (2019-09-10)
Today has been released Dart 2.5 (and Flutter 1.9). One of the additions to Dart 2.5 is "the dart:ffi foreign function interface for calling C code directly from Dart." I still haven't checked it, but it should provide a more direct path to interface with C (and C++) code.
Related Posts Related Posts :
  • List<String>- Null
  • How to normalize channel values to the range[0.0,1.0]?
  • How to convert a signed APK to an unsigned APK
  • Android library AAR packing resource incorrectly
  • Why it fail to upload apk to google play console?
  • How do I get more than 500 contact lists on Android?
  • Android layer-list affecting position of floating action button
  • Koin: NoBeanDefFoundException, Check your module definitions
  • Jetpack Navigation: Hide label in toolbar
  • get thumbnail from video URL but it takes more than 5 seconds to load data on recycler view
  • How to fix 'Android SDK not found at this location' error while installing flutter?
  • Android Shared Storage protection issue
  • How can I clone views using java code in Android Studio
  • Hide title and action bar for splash screen and remove White screen in start
  • Why can not hashing key android for facebook
  • Can not create handler inside thread that has not called Looper.prepare()
  • ID of the child views in a custom view are same in Android
  • Android: unable to hide appbar on scrolling
  • Best layout for form-style screen
  • How To create multiple function in Adapter Class Android with Retrofit
  • Can the Android Flow virtual layout handle variable-width Views
  • How to fix "Unable to load class 'dagger.Multibindings'" due to problems with gradle
  • VpnService always-on "not supported by this app"
  • Android Studio - Gradle "Sync now" is not Available
  • How do i get my code to give my current location?
  • Could not initialize class sun.util.calendar.ZoneInfoFile while using Flutter firebase-notifications
  • How to implement circular to check / tick animation in Android?
  • Toolbar shadow not showing
  • Android Sqlite get rows where first character is not an Alphabet
  • why I receive "bad request" in my request by retrofit
  • Intercept NavigationUI.onNavDestinationSelected() to make backstack pop with "inclusive = true"
  • I have a problem with the navigation fragments in my proyect, it sais that I need a defaut nav host atribute but I alrea
  • How can I keep a BottomSheetDialogFragment height to always match_parent?
  • How to reference a timerPicker in android studio using kotlin
  • Firebase Crashlytics - get stacktrace info to display during CrashlyticsListener.crashlyticsDidDetectCrashDuringPrevious
  • Schedule a repeating alarm clock
  • Can't assign values outside onTouchListener
  • Is setContentView() needed to inflate a fragment?
  • Why instead of string method returns Kotlin.Unit?
  • Retrofit slash as Query
  • When does onCreateView() get called in this app?
  • Fragment is reloaded each time after rejecting location permission
  • How to read ViewModel data from sttrings.xml list of items
  • Flutter doctor does not see vs code ,VS code does not detect flutter/bin
  • How to build aar in flutter
  • Gradle Build Fails - Illegal exception table range in class file com/google/wireless/android/sdk/stats/GradleBuildMemory
  • register has type Long (High Half) but expected Long (Low Half)
  • Is it good idea to use Dispatcher.Main with delay( )?
  • WebView and Advanced View is Not loading partiucalr URL
  • How to show three dots at the end of text view
  • Is it possible to run macros within Android Studio project?
  • Adding a button with default appearance but changed background color
  • What is best way to show notification at a certain time in Android?
  • Jetifier not working when library uses android component and app uses androidx component
  • How can I write the contents of an image in a filesystem
  • Retrieve a list of images from the Database and display them using a ListView?
  • java.lang.SecurityException: my location requires permission ACCESS_FINE_LOCATION or ACCESS_COARSE_LOCATION
  • Timer/hourglass wont stop
  • How can I make AndroidX the default library for new Android projects?
  • Is it okay to delete buildToolsVersion android studio because of a warning in the Asyncstorage library?
  • shadow
    Privacy Policy - Terms - Contact Us © festivalmusicasacra.org