I'm wanting to automatically run my flutter application's background services as soon as the mobile is rebooted.
I implemented the following Solution, but it's throwing some errors
AndroidStudioProjects\db_app\android\app\src\main\kotlin\com\example\laravel_login\MainActivity.kt: (14, 22): Unresolved reference: Uri
AndroidStudioProjects\db_app\android\app\src\main\kotlin\com\example\laravel_login\MainActivity.kt: (14, 28): Unresolved reference: Uri
FAILURE: Build failed with an exception.
* What went wrong:
Execution failed for task ':app:compileDebugKotlin'.
> Compilation error. See log for more details
* Try:
> Run with --stacktrace option to get the stack trace.
> Run with --info or --debug option to get more log output.
> Run with --scan to get full insights.
If you know any alternative, please help.
Thank you.
MainActivity.kt
package com.example.laravel_login
import android.os.Bundle
import android.provider.Settings
import io.flutter.embedding.android.FlutterActivity
import android.content.BroadcastReceiver
import android.content.Context;
import android.content.Intent;
class MainActivity: FlutterActivity() {
override fun onCreate(savedInstanceState: Bundle?) {
super.onCreate(savedInstanceState)
var REQUEST_OVERLAY_PERMISSIONS = 100
if (!Settings.canDrawOverlays(getApplicationContext())) {
val myIntent = Intent(Settings.ACTION_MANAGE_OVERLAY_PERMISSION)
val uri: Uri = Uri.fromParts("com.example.laravel_login.BootReceiver", getPackageName(), null)
myIntent.setData(uri)
startActivityForResult(myIntent, REQUEST_OVERLAY_PERMISSIONS)
return
}
}
}
class BootReceiver: BroadcastReceiver() {
override fun onReceive(context: Context, intent: Intent) {
if (intent.action == Intent.ACTION_BOOT_COMPLETED) {
val i = Intent(context, MainActivity::class.java)
i.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK)
context.startActivity(i)
}
}
}
AndroidManifest.xml
<!-- app auto restart on phone restart -->
<receiver
android:enabled="true"
android:exported="true"
android:name="com.example.laravel_login.BootReceiver"
android:permission="android.permission.RECEIVE_BOOT_COMPLETED">
<intent-filter>
<action android:name="android.intent.action.BOOT_COMPLETED" />
<action android:name="android.intent.action.QUICKBOOT_POWERON" />
<category android:name="android.intent.category.DEFAULT" />
</intent-filter>
</receiver>
<!-- app auto restart on phone restart -->
Add this to the imports of MainActivity.kt and you're good to go.
import android.net.Uri
Related
I'm trying to work out how to wire up a Share intent in Android using MAUI.
Am I running into preview bugs, or am I not doing it correctly?
I'm running MAUI Preview 10, with Visual Studio 17.1.0 Preview 1.0.
Version 1
I've added the share intent to the AndroidManifest.xml file:
<?xml version="1.0" encoding="utf-8"?>
<manifest xmlns:android="http://schemas.android.com/apk/res/android">
<uses-sdk android:minSdkVersion="21" android:targetSdkVersion="31" />
<application android:allowBackup="true" android:icon="#mipmap/appicon" android:roundIcon="#mipmap/appicon_round" android:supportsRtl="true">
<activity android:name="SomeLongName.MainActivity" >
<intent-filter>
<action android:name="android.intent.action.SEND" />
<category android:name="android.intent.category.DEFAULT" />
<data android:mimeType="text/plain" />
</intent-filter>
</activity>
</application>
<uses-permission android:name="android.permission.ACCESS_NETWORK_STATE" />
</manifest>
And then by adding a Name property to the MainActivity class:
[Activity(Name = "SomeLongName.MainActivity", Theme = "#style/Maui.SplashTheme", MainLauncher = true, ConfigurationChanges = ConfigChanges.ScreenSize | ConfigChanges.Orientation | ConfigChanges.UiMode | ConfigChanges.ScreenLayout | ConfigChanges.SmallestScreenSize)]
public class MainActivity : MauiAppCompatActivity
{
protected override void OnCreate(Bundle savedInstanceState)
{
base.OnCreate(savedInstanceState);
if (Intent.Type == "text/plain")
{
}
}
}
When I debug the application in MAUI, the app builds correctly and the Output says that the app has deployed. However, in Visual Studio, the debugger fails to run, and there is no evidence of the app on the emulator.
Version 2
In version 2, I've tried to create a separate activity for the Share intent:
<?xml version="1.0" encoding="utf-8"?>
<manifest xmlns:android="http://schemas.android.com/apk/res/android">
<uses-sdk android:minSdkVersion="21" android:targetSdkVersion="31" />
<application android:allowBackup="true" android:icon="#mipmap/appicon" android:roundIcon="#mipmap/appicon_round" android:supportsRtl="true">
<activity android:name="SomeLongName.ShareActivity" >
<intent-filter>
<action android:name="android.intent.action.SEND" />
<category android:name="android.intent.category.DEFAULT" />
<data android:mimeType="text/plain" />
</intent-filter>
</activity>
</application>
<uses-permission android:name="android.permission.ACCESS_NETWORK_STATE" />
</manifest>
[Activity(Name = "SomeLongName.ShareActivity")]
public class ShareActivity : MauiAppCompatActivity
{
protected override void OnCreate(Bundle savedInstanceState)
{
if (Intent.Type == "text/plain" && Intent.Action == "android.intent.action.SEND")
{
//handleSendUrl();
}
base.OnCreate(savedInstanceState);
}
I can now successfully debug the application, but when I try to share to the application, I get an exception on the base.OnCreate call:
Java.Lang.IllegalStateException: 'The specified child already has a parent. You must call removeView() on the child's parent first.'
Seems the issue centres around themes. The solution is in the original question, apply Version 2. With some minor updates. In the MainApplication class add an attribute defining the theme (same as in MainActivity class but could be different).
[Application(Theme = "#style/Maui.SplashTheme")]
public class MainApplication : MauiApplication
{
public MainApplication(IntPtr handle, JniHandleOwnership ownership)
: base(handle, ownership)
{
}
protected override MauiApp CreateMauiApp() => MauiProgram.CreateMauiApp();
}
This both works without error and enables debugging.
Without the MainApplication theme setting, when sharing to the android app (incoming), an error thrown:
Java.Lang.IllegalArgumentException: 'The style on this component requires your app theme to be Theme.MaterialComponents (or a descendant).'
In my secondary activity, the Activity attribute sets the Theme, but is ignored and error still shown, hence the Application level needed. Not sure why.
[Activity(Theme = "#android:style/Theme.MaterialComponents.Light", Name = "com.somename.receiveurlactivity", MainLauncher = false, ConfigurationChanges = ConfigChanges.ScreenSize | ConfigChanges.Orientation | ConfigChanges.UiMode | ConfigChanges.ScreenLayout | ConfigChanges.SmallestScreenSize)]
public class ReceiveUrlActivity : MauiAppCompatActivity
{
//.... etc
I have tried adding Firebase Messaging to my Flutter app, and according to this tutorial I should add a custom application name to the manifest file.
Problem
App won't launch because Flutter can't find my custom application file
Cause
I have tried integrating FlutterFire / Firebase Cloud Messaging with flutter
Request
All I care about is receiving push notifications (foreground + background) on the Flutter app, if this is not the correct method to go about it, please let tell me how I can enable this for Android devices
Logs & Outputs
My manifest is
package="com.blabla.blabla">
<!-- Default is android:name="io.flutter.app.FlutterApplication" -->
<!-- FOR PUSH NOIFICATION IN BACKGROUND android:name=".Application" -->
<application
android:name=".Application"
android:label="BlaBla"
android:icon="#mipmap/launcher_icon">
<activity
android:name=".MainActivity"
android:launchMode="singleTop"
android:theme="#style/LaunchTheme"
android:configChanges="orientation|keyboardHidden|keyboard|screenSize|smallestScreenSize|locale|layoutDirection|fontScale|screenLayout|density|uiMode"
android:hardwareAccelerated="true"
android:windowSoftInputMode="adjustResize">
<!-- this is the push notification intent -->
<intent-filter>
<action android:name="FLUTTER_NOTIFICATION_CLICK" />
<category android:name="android.intent.category.DEFAULT" />
</intent-filter>
<meta-data
android:name="io.flutter.embedding.android.NormalTheme"
android:resource="#style/NormalTheme"
/>
The application file is located in the same folder as Manifest (app->src->main)
import io.flutter.app.FlutterApplication
import io.flutter.plugin.common.PluginRegistry
import io.flutter.plugin.common.PluginRegistry.PluginRegistrantCallback
import io.flutter.plugins.firebasemessaging.FlutterFirebaseMessagingService
class Application : FlutterApplication(), PluginRegistrantCallback {
override fun onCreate() {
super.onCreate()
FlutterFirebaseMessagingService.setPluginRegistrant(this)
}
override fun registerWith(registry: PluginRegistry?) {
io.flutter.plugins.firebasemessaging.FirebaseMessagingPlugin.registerWith(
registry?.registrarFor(
"io.flutter.plugins.firebasemessaging.FirebaseMessagingPlugin"));
}
}
And my specific (app->build.gradle) is as follows
def localPropertiesFile = rootProject.file('local.properties')
if (localPropertiesFile.exists()) {
localPropertiesFile.withReader('UTF-8') { reader ->
localProperties.load(reader)
}
}
def flutterRoot = localProperties.getProperty('flutter.sdk')
if (flutterRoot == null) {
throw new GradleException("Flutter SDK not found. Define location with flutter.sdk in the local.properties file.")
}
def flutterVersionCode = localProperties.getProperty('flutter.versionCode')
if (flutterVersionCode == null) {
flutterVersionCode = '1'
}
def flutterVersionName = localProperties.getProperty('flutter.versionName')
if (flutterVersionName == null) {
flutterVersionName = '1.0'
}
apply plugin: 'com.android.application'
apply plugin: 'com.google.gms.google-services' // Google Services plugin
apply plugin: 'kotlin-android'
apply from: "$flutterRoot/packages/flutter_tools/gradle/flutter.gradle"
android {
compileSdkVersion 30
sourceSets {
main.java.srcDirs += 'src/main/kotlin'
}
lintOptions {
disable 'InvalidPackage'
}
defaultConfig {
applicationId "com.bla.bla"
minSdkVersion 21
targetSdkVersion 30
// multiDexEnabled true
versionCode flutterVersionCode.toInteger()
versionName flutterVersionName
}
buildTypes {
release {
// TODO: Add your own signing config for the release build.
// Signing with the debug keys for now, so `flutter run --release` works.
signingConfig signingConfigs.debug
}
}
splits {
// Configures multiple APKs based on ABI.
abi {
// Enables building multiple APKs per ABI.
enable true
// By default all ABIs are included, so use reset() and include to specify that we only
// want APKs for x86 and x86_64.
// Resets the list of ABIs that Gradle should create APKs for to none.
reset()
// Specifies a list of ABIs that Gradle should create APKs for.
include "x86", "x86_64", "armeabi", "armeabi-v7a", "arm64-v8a"
// Specifies that we do not want to also generate a universal APK that includes all ABIs.
universalApk true
}
}
}
flutter {
source '../..'
}
dependencies {
// implementation "androidx.multidex:multidex:2.0.1"
implementation "org.jetbrains.kotlin:kotlin-stdlib-jdk7:$kotlin_version"
// Import the BoM for the Firebase platform
implementation platform('com.google.firebase:firebase-bom:26.6.0')
// Declare the dependencies for the Firebase Cloud Messaging and Analytics libraries
// When using the BoM, you don't specify versions in Firebase library dependencies
implementation 'com.google.firebase:firebase-messaging-ktx:21.0.1'
// implementation 'com.google.firebase:firebase-analytics-ktx'
}
This is the general build.gradle
ext.kotlin_version = '1.3.50'
repositories {
google()
jcenter()
}
dependencies {
classpath 'com.android.tools.build:gradle:3.5.4'
classpath "org.jetbrains.kotlin:kotlin-gradle-plugin:$kotlin_version"
classpath 'com.google.gms:google-services:4.3.5' // Google Services plugin
}
}
allprojects {
repositories {
google()
jcenter()
}
}
rootProject.buildDir = '../build'
subprojects {
project.buildDir = "${rootProject.buildDir}/${project.name}"
}
subprojects {
project.evaluationDependsOn(':app')
}
task clean(type: Delete) {
delete rootProject.buildDir
}
This is the console output of every launch
E/AndroidRuntime(31070): java.lang.RuntimeException: Unable to instantiate application com.bla.bla.Application: java.lang.ClassNotFoundException: Didn't find class "com.bla.bla.Application" on path: DexPathList[[zip file "/data/app/com.bla.bla-bPPOfcyKzIbhjyMWE3Q9NQ==/base.apk"],nativeLibraryDirectories=[/data/app/com.bla.bla-bPPOfcyKzIbhjyMWE3Q9NQ==/lib/arm64, /data/app/com.bla.bla-bPPOfcyKzIbhjyMWE3Q9NQ==/base.apk!/lib/arm64-v8a, /system/lib64, /system/product/lib64]]
E/AndroidRuntime(31070): at android.app.LoadedApk.makeApplication(LoadedApk.java:1231)
E/AndroidRuntime(31070): at android.app.ActivityThread.handleBindApplication(ActivityThread.java:6431)
E/AndroidRuntime(31070): at android.app.ActivityThread.access$1300(ActivityThread.java:219)
E/AndroidRuntime(31070): at android.app.ActivityThread$H.handleMessage(ActivityThread.java:1859)
E/AndroidRuntime(31070): at android.os.Handler.dispatchMessage(Handler.java:107)
E/AndroidRuntime(31070): at android.os.Looper.loop(Looper.java:214)
E/AndroidRuntime(31070): at android.app.ActivityThread.main(ActivityThread.java:7356)
E/AndroidRuntime(31070): at java.lang.reflect.Method.invoke(Native Method)
E/AndroidRuntime(31070): at com.android.internal.os.RuntimeInit$MethodAndArgsCaller.run(RuntimeInit.java:491)
E/AndroidRuntime(31070): at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:930)
I DON'T KNOW WHAT ELSE TO DO!! I have spent countless hours trying to solve it, would appreciate it if anybody knows how to fix this issue!!
Currently running on a Google Pixel 2 Android 10 device.
My bad,
I had accidentally put the Application.kt file in the android > app folder instead of android > app > src > your-package-name.
Once I moved the custom Application.kt next to the MainActivity.kt, all seems to work well!
Try modifying your AndroidManifest.xml file to look like below. This is working.
This is only for the <activity </activity> tags. And set your minSdkVersion to 21 in android/app/build.gradle to overcome possible multidex errors.
<activity
android:name=".MainActivity"
android:launchMode="singleTop"
android:theme="#style/LaunchTheme"
android:configChanges="orientation|keyboardHidden|keyboard|screenSize|smallestScreenSize|locale|layoutDirection|fontScale|screenLayout|density|uiMode"
android:hardwareAccelerated="true"
android:windowSoftInputMode="adjustResize">
<!-- Specifies an Android theme to apply to this Activity as soon as
the Android process has started. This theme is visible to the user
while the Flutter UI initializes. After that, this theme continues
to determine the Window background behind the Flutter UI. -->
<meta-data
android:name="io.flutter.embedding.android.NormalTheme"
android:resource="#style/NormalTheme"
/>
<!-- Displays an Android View that continues showing the launch screen
Drawable until Flutter paints its first frame, then this splash
screen fades out. A splash screen is useful to avoid any visual
gap between the end of Android's launch screen and the painting of
Flutter's first frame. -->
<meta-data
android:name="io.flutter.embedding.android.SplashScreenDrawable"
android:resource="#drawable/launch_background"
/>
<intent-filter>
<action android:name="android.intent.action.MAIN"/>
<category android:name="android.intent.category.LAUNCHER"/>
</intent-filter>
<intent-filter>
<action android:name="FLUTTER_NOTIFICATION_CLICK" />
<category android:name="android.intent.category.DEFAULT" />
</intent-filter>
</activity>
I want to work with Flutter Workmanager, I did the cited configuration in my .kt like this:
package com.example.mybackprocess
import be.tramckrijte.workmanager.WorkmanagerPlugin
import io.flutter.app.FlutterApplication
import io.flutter.plugin.common.PluginRegistry
import io.flutter.plugins.GeneratedPluginRegistrant
class App : FlutterApplication(), PluginRegistry.PluginRegistrantCallback {
override fun onCreate() {
super.onCreate()
WorkmanagerPlugin.setPluginRegistrantCallback(this)
}
override fun registerWith(reg: PluginRegistry?) {
GeneratedPluginRegistrant.registerWith(reg)
}
}
and I have changed android:name to
android:name=".App"
but it gives me this error:
Launching lib\main.dart on G3212 in debug mode...
e:E:\mybackprocess\android\app\src\main\kotlin\com\example\mybackprocess\MainActivity.kt:
(15, 48): Type mismatch: inferred type is PluginRegistry? but
FlutterEngine was expected
FAILURE: Build failed with an exception. * What went wrong:
Execution failed for task ':app:compileDebugKotlin'. Compilation
error. See log for more details
Try: Run with --stacktrace option to get the stack trace. Run with
--info or --debug option to get more log output. Run with --scan to get full insights. * Get more help at https://help.gradle.org
BUILD FAILED in 55s Gradle task assembleDebug failed with exit code
1 Exited (sigterm)
Can someone please help me?
you can fix the issue by replacing the following method in your application.kt
override fun registerWith(registry: PluginRegistry?) {
registry?.registrarFor("com.iotecksolutions.background_location_fetch.BackgroundLocationFetchPlugin");
}
Note: Replace com.iotecksolutions.background_location_fetch.BackgroundLocationFetchPlugin with your plugin name.
Replace the MainActivity.kt with:
import android.os.Bundle
import io.flutter.app.FlutterActivity
import io.flutter.plugins.GeneratedPluginRegistrant
class MainActivity : FlutterActivity() {
override fun onCreate(savedInstanceState: Bundle?) {
super.onCreate(savedInstanceState)
GeneratedPluginRegistrant.registerWith(this)
}
}
I used the following code to fix the error
GeneratedPluginRegistrant.registerWith(FlutterEngine(applicationContext))
app this tag before closing tag in AndroidManifest like below and you are good to go
...
<meta-data
android:name="flutterEmbedding"
android:value="2" />
</application>
go to (JitsiMeetPlugin.kt) file in:
android\src\main\kotlin\com\gunschu\jitsi_meet
JitsiMeetPlugin.kt
Search for these lines and add (?) to Activity
constructor(activity: Activity) : this() {
this.activity = activity
}
And edit it to this:
constructor(activity: Activity?) : this() {
this.activity = activity
}
This Work for me, I hope this helps you
I wanted to try out cloud messaging in my Flutter application, but I always run into errors, and I have not found a solution yet. I followed the steps stated here: firebase_messaging
If I follow the steps except the optional part with creating an Application.java file for background messages, and I send a test message from Firebase to the launched application, I get this error:
java.lang.RuntimeException: Unable to create service io.flutter.plugins.firebasemessaging.FlutterFirebaseMessagingService: java.lang.RuntimeException: PluginRegistrantCallback is not set.
at android.app.ActivityThread.handleCreateService(ActivityThread.java:3577)
at android.app.ActivityThread.access$1400(ActivityThread.java:200)
at android.app.ActivityThread$H.handleMessage(ActivityThread.java:1689)
at android.os.Handler.dispatchMessage(Handler.java:106)
at android.os.Looper.loop(Looper.java:201)
at android.app.ActivityThread.main(ActivityThread.java:6806)
at java.lang.reflect.Method.invoke(Native Method)
at com.android.internal.os.RuntimeInit$MethodAndArgsCaller.run(RuntimeInit.java:547)
at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:873)
E/AndroidRuntime(29468): Caused by: java.lang.RuntimeException: PluginRegistrantCallback is not set.
at io.flutter.plugins.firebasemessaging.FlutterFirebaseMessagingService.startBackgroundIsolate(FlutterFirebaseMessagingService.java:157)
at io.flutter.plugins.firebasemessaging.FlutterFirebaseMessagingService.onCreate(FlutterFirebaseMessagingService.java:77)
at android.app.ActivityThread.handleCreateService(ActivityThread.java:3565)
For me it seems like that the optional part is needed too, but when I do that I get errors when the app opens. After the errors the app still runs, and if I send a test message from Firebase the app receives it succesfully. Later it doesn't even receives the message, but thows the same errors.
java.lang.NullPointerException: Attempt to invoke virtual method 'android.app.Application android.app.Activity.getApplication()' on a null object reference
at com.github.adee42.keyboardvisibility.KeyboardVisibilityPlugin.registerWith(KeyboardVisibilityPlugin.java:107)
at io.flutter.plugins.GeneratedPluginRegistrant.registerWith(GeneratedPluginRegistrant.java:22)
at io.flutter.plugins.Application.registerWith(Application.java:18)
at io.flutter.plugins.firebasemessaging.FlutterFirebaseMessagingService.startBackgroundIsolate(FlutterFirebaseMessagingService.java:164)
at io.flutter.plugins.firebasemessaging.FirebaseMessagingPlugin.onMethodCall(FirebaseMessagingPlugin.java:133)
at io.flutter.plugin.common.MethodChannel$IncomingMethodCallHandler.onMessage(MethodChannel.java:222)
at io.flutter.embedding.engine.dart.DartMessenger.handleMessageFromDart(DartMessenger.java:96)
at io.flutter.embedding.engine.FlutterJNI.handlePlatformMessage(FlutterJNI.java:656)
at android.os.MessageQueue.nativePollOnce(Native Method)
at android.os.MessageQueue.next(MessageQueue.java:326)
at android.os.Looper.loop(Looper.java:165)
at android.app.ActivityThread.main(ActivityThread.java:6806)
at java.lang.reflect.Method.invoke(Native Method)
at com.android.internal.os.RuntimeInit$MethodAndArgsCaller.run(RuntimeInit.java:547)
at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:873)
[ERROR:flutter/lib/ui/ui_dart_state.cc(148)] Unhandled Exception: PlatformException(error, Attempt to invoke virtual method 'android.app.Application android.app.Activity.getApplication()' on a null object reference, null)
StandardMethodCodec.decodeEnvelope (package:flutter/src/services/message_codecs.dart:569:7)
MethodChannel.invokeMethod (package:flutter/src/services/platform_channel.dart:316:33)
<asynchronous suspension>
FirebaseMessaging.configure (package:firebase_messaging/firebase_messaging.dart:118:16)
main (package:vonatles/main.dart:18:22)
_AsyncAwaitCompleter.start (dart:async-patch/async_patch.dart:43:6)
main (package:vonatles/main.dart:12:10)
_runMainZoned.<anonymous closure>.<anonymous closure> (dart:ui/hooks.dart:229:25)
_rootRun (dart:async/zone.dart:1124:13)
_CustomZone.run (dart:async/zone.dart:1021:19)
_runZoned (dart:async/zone.dart:1516:10)
runZoned (dart:async/zone.dart:1500:12)
_runMainZoned.<anonymous closure> (dart:ui/hooks.dart:221:5)
_startIsolate.<anonymous closure> (dart:isolate-patch/isolate_patch.dart:305:19)
_RawReceivePortImpl._handleMessage (dart:isolate-patch/isolate_patch.dart:172:12)
Versions:
firebase_core: ^0.4.0+1
firebase_database: 3.0.7
firebase_messaging: 5.1.5
classpath 'com.android.tools.build:gradle:3.3.0'
classpath "org.jetbrains.kotlin:kotlin-gradle-plugin:1.3.0"
classpath 'com.google.gms:google-services:4.3.0'
In the Flutter main function I have this:
final FirebaseMessaging _firebaseMessaging = FirebaseMessaging();
_firebaseMessaging.configure(
onMessage: (Map<String, dynamic> message) async {
print("onMessage: $message");
},
onLaunch: (Map<String, dynamic> message) async {
print("onLaunch: $message");
},
onResume: (Map<String, dynamic> message) async {
print("onResume: $message");
},
);
The Application.java code:
package io.flutter.plugins;
import io.flutter.app.FlutterApplication;
import io.flutter.plugin.common.PluginRegistry;
import io.flutter.plugin.common.PluginRegistry.PluginRegistrantCallback;
import io.flutter.plugins.GeneratedPluginRegistrant;
import io.flutter.plugins.firebasemessaging.FlutterFirebaseMessagingService;
public class Application extends FlutterApplication implements PluginRegistrantCallback {
#Override
public void onCreate() {
super.onCreate();
FlutterFirebaseMessagingService.setPluginRegistrant(this);
}
#Override
public void registerWith(PluginRegistry registry) {
GeneratedPluginRegistrant.registerWith(registry);
}
}
My android main directory:
-main
-java
-io.flutter.plugins
Apllication.java
GeneratedPluginRegistrant.java
-kotlin
-my.package.name
MainActivity.kt
AndroidManifest:
<manifest xmlns:android="http://schemas.android.com/apk/res/android"
package="my.package.name">
<application
android:name="io.flutter.plugins.Application"
android:label="mylabel"
android:icon="#mipmap/ic_launcher">
<activity
android:name=".MainActivity"
...
<intent-filter>
<action android:name="FLUTTER_NOTIFICATION_CLICK" />
<category android:name="android.intent.category.DEFAULT" />
</intent-filter>
</activity>
</application>
</manifest>
Since my MainActivity in android was a Kotlin class, I got the solution to this problem when I tried the Application class as a Kotlin class instead of trying it as a Java class.
I tried many solutions, still, I was not able to run the app.
Application.kt
package YOUR_PACKAGE_NAME
import io.flutter.app.FlutterApplication
import io.flutter.plugin.common.PluginRegistry
import io.flutter.plugin.common.PluginRegistry.PluginRegistrantCallback
import io.flutter.plugins.firebasemessaging.FlutterFirebaseMessagingService
public class Application: FlutterApplication(), PluginRegistrantCallback {
override fun onCreate() {
super.onCreate()
FlutterFirebaseMessagingService.setPluginRegistrant(this)
}
override fun registerWith(registry: PluginRegistry) {
FirebaseCloudMessagingPluginRegistrant.registerWith(registry)
}
}
Also, FirebaseCloudMessagingPluginRegistrant.kt
package YOUR_PACKAGE_NAME
import io.flutter.plugin.common.PluginRegistry
import io.flutter.plugins.firebasemessaging.FirebaseMessagingPlugin
class FirebaseCloudMessagingPluginRegistrant {
companion object {
fun registerWith(registry: PluginRegistry) {
if (alreadyRegisteredWith(registry)) {
return;
}
FirebaseMessagingPlugin.registerWith(registry.registrarFor("io.flutter.plugins.firebasemessaging.FirebaseMessagingPlugin"))
}
fun alreadyRegisteredWith(registry: PluginRegistry): Boolean {
val key = FirebaseCloudMessagingPluginRegistrant::class.java.name
if (registry.hasPlugin(key)) {
return true
}
registry.registrarFor(key)
return false
}
}
}
This can be added in the sample directory where your MainActivity is.
Try this Along with the steps mentioned here: Firebase messaging
by the way you can create a notification_handler.dart like this Unhandled Exception: NoSuchMethodError: The method 'toRawHandle' was called on null.
i have posted my notification_handler.dart their.
try to configure with that and just call is as below from your statefullWidget and the let me know.
#override
void initState() {
super.initState();
new NotificationHandler().initializeFcmNotification();
}
Background notification setup is not optional anymore. Make sure to follow intructions properly. And i was confused in making change in AndroidManifest.xml, So i wanted to share clear instruction.
PluginRegistrantCallback is not set" means Application.java file is not called properly at AndroidManifest.xml. Make change as follows:
First it looks like this
Change it to yourpackagename.Application like this
If you get "Default activity not found" error, run "flutter clean" command in your project folder and run it again.
In your AndroidManifest:
<manifest xmlns:android="http://schemas.android.com/apk/res/android"
package="my.package.name">
<application
android:name=".Application" //edit this line
android:label="mylabel"
android:icon="#mipmap/ic_launcher">
<activity
android:name=".MainActivity"
...
<intent-filter>
<action android:name="FLUTTER_NOTIFICATION_CLICK" />
<category android:name="android.intent.category.DEFAULT" />
</intent-filter>
</activity>
</application>
I'm trying to implement Scringo Login status change on Android. But my Broadcast receiver is never called.
I've followed the instructions described on http://www.scringo.com/docs/android-guides/popular/handling-login-status-changes/
So I registered my broadcast receiver:
<receiver android:name="com.jino.footster.MyReceiver">
<intent-filter>
<action android:name="com.scringo.LoginBroadcast" />
</intent-filter>
</receiver>
And I then defined my Broacast receiver:
package com.jino.footster;
import com.scringo.utils.ScringoLogger;
import android.content.BroadcastReceiver;
import android.content.Context;
import android.content.Intent;
public class MyReceiver extends BroadcastReceiver {
#Override
public void onReceive(Context context, Intent intent) {
if (intent.getAction().equals("com.scringo.LoginBroadcast")) {
boolean isLogin = intent.getExtras().getBoolean("isLogin");
String accountId = intent.getExtras().getString("accountId");
ScringoLogger.e("Got Login receiver: " + isLogin + ", " + accountId);
}
}
}
When I start the application the login seems to be successful: I see the below message in logcat:
04-24 01:12:35.000: I/Scringo(4717): Your Scringo user token is: a03fgalc5E
However, the onReceive method of my broadcast receiver is never called.
Would someone be able to help?
thank you
You forgot the category:
<receiver android:name="com.jino.footster.MyReceiver">
<intent-filter>
<action android:name="com.scringo.LoginBroadcast" />
<category android:name="com.jino.footster"/>
</intent-filter>
</receiver>