Java.Lang.IllegalStateException: Make sure to call FirebaseApp.initializeApp(Context) first.' xamarin.android - push-notification

i am trying to implement fcm in my xamarin.android app using xamarin.forms. i am using the Plugin.FirebasePushNotification version 3.3.10 depending on this youtube tutorial: https://www.youtube.com/watch?v=7w2q2D6mR7g
i added Application.cs to my xamarin.android app:
using Android.App;
using Android.Content;
using Android.OS;
using Android.Runtime;
using Android.Views;
using Android.Widget;
using Plugin.FirebasePushNotification;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
namespace LearningWithCassidy.Droid
{
[Application]
public class MainApplication : Application
{
public MainApplication(IntPtr handle, JniHandleOwnership transer) : base(handle, transer)
{
}
public override void OnCreate()
{
base.OnCreate();
//Set the default notification channel for your app when running Android Oreo
if (Build.VERSION.SdkInt >= Android.OS.BuildVersionCodes.O)
{
//Change for your default notification channel id here
FirebasePushNotificationManager.DefaultNotificationChannelId = "FirebasePushNotificationChannel";
//Change for your default notification channel name here
FirebasePushNotificationManager.DefaultNotificationChannelName = "General";
FirebasePushNotificationManager.DefaultNotificationChannelImportance = NotificationImportance.Max;
}
//If debug you should reset the token each time.
#if DEBUG
FirebasePushNotificationManager.Initialize(this, true);
#else
FirebasePushNotificationManager.Initialize(this, false);
#endif
//Handle notification when app is closed here
CrossFirebasePushNotification.Current.OnNotificationReceived += (s, p) =>
{
};
}
}
}
and added this line to my MainActivity as mentioned:
protected override void OnCreate(Bundle savedInstanceState)
{
base.OnCreate(savedInstanceState);
Xamarin.Essentials.Platform.Init(this, savedInstanceState);
global::Xamarin.Forms.Forms.Init(this, savedInstanceState);
LoadApplication(new App());
FirebasePushNotificationManager.ProcessIntent(this, Intent);
}
i also added the internet permission to my manifest file. but when i launch my app i get this exception:
**Java.Lang.IllegalStateException:** 'Default FirebaseApp is not initialized in this process com.companyname.learningwithcassidy. Make sure to call FirebaseApp.initializeApp(Context) first.'
i searched a lot and tried many things. i tried adding FirebaseApp.InitializeApp(this); to my mainactivity but nothing happened. what am i doing wrong? many answers correspond to android studio i really trie understanding the probelm but couldn't. thanks in advance

Related

Error java.exe exited with code 1 Xamarin Firbase Messaging

I am using nuget package Xamarin.Firebase.Messaging and Xamarin.GooglePlayServices.Baseto receive push notifications in my app, previously it was working fine, but when I update visual studio 2022 to 17.2.3 it stopped working
I Tried all of these:
Update all nuget packages
delete obj bin folder from all shared projects
enable multidex
install and include
<PackageReference Include="Xamarin.Google.Guava" ExcludeAssets="all"> <Version>27.1.0</Version> </PackageReference>
https://techhelpnotes.com/c-working-through-package-reference-errors-with-firebase-and-a-java-exe-exited-with-code-1-error-xamarin/
https://github.com/xamarin/GooglePlayServicesComponents/issues/379
and nothing i did before has worked
my code to receive push notifications:
using System;
using System.Threading.Tasks;
using Android.App;
using Firebase.Messaging;
using Plugin.DeviceInfo;
using Xamarin.Essentials;
using Xamarin.Forms;
namespace MyApp.Droid
{
[Service]
[IntentFilter(new[] { "com.google.firebase.MESSAGING_EVENT" })]
public class MyFirebaseMessagingService : FirebaseMessagingService
{
readonly AndroidNotificationManager _androidNotification = new AndroidNotificationManager();
public override void OnMessageReceived(RemoteMessage message)
{
var mensajeData = message.Data;
string title= mensajeData["notiTitle"];
string bodymessage= mensajeData["notiBody"];
_androidNotification.CreateLocalNotification(title, bodymessage);
}
public override void OnNewToken(string token)
{
base.OnNewToken(token);
Preferences.Set("TokenFirebase", token);
}
}
}
if I remove [Service] or
[IntentFilter(new[] { "com.google.firebase.MESSAGING_EVENT" })] the code compiles correctly
Apparently it was due to the update I made of visual studio because the android SDK was also updated, the solution was to edit [Services] to [Services(Exported = true)] for android +31, leaving the final code like this.
[Service(Exported = true)]
[IntentFilter(new[] { "com.google.firebase.MESSAGING_EVENT" })]
public class MyFirebaseMessagingService : FirebaseMessagingService
{
readonly AndroidNotificationManager _androidNotification = new AndroidNotificationManager();
public override void OnMessageReceived(RemoteMessage message)
{
var mensajeData = message.Data;
string title= mensajeData["notiTitle"];
string bodymessage= mensajeData["notiBody"];
_androidNotification.CreateLocalNotification(title, bodymessage);
}
public override void OnNewToken(string token)
{
base.OnNewToken(token);
Preferences.Set("TokenFirebase", token);
}
}
After adding that, everything compiled correctly
font answer
In addition to the answers here, I also had to export the broadcast reviver
[BroadcastReceiver(Enabled = true, Exported = true)]

implement android beam in xamarin forms

I'm develop cross-platform mobile application that use NFC. I already check the xamarin android beam here. Now i'm trying implement the same sample using xamarin forms so i'm using dependency service to call the function from android project. I try to make simple message that pass from device to another but it didn't work. The problem is the implementation of NfcAdapter.IOnNdefPushCompleteCallback
PhoneBeam.cs
using System;
using System.Text;
using Android.App;
using MyApp.Droid;
using Android.Nfc;
using Xamarin.Forms;
[assembly: Dependency(typeof(PhoneBeam))]
namespace MyApp.Droid
{
public class PhoneBeam : Activity, NfcAdapter.ICreateNdefMessageCallback, NfcAdapter.IOnNdefPushCompleteCallback, iBeam
{
private NfcAdapter nfcAdapter;
public void Beam()
{
nfcAdapter = NfcAdapter.GetDefaultAdapter(MainActivity.Instance);
nfcAdapter.SetNdefPushMessageCallback(this, MainActivity.Instance);
nfcAdapter.SetOnNdefPushCompleteCallback(this, MainActivity.Instance);
}
public NdefMessage CreateNdefMessage(NfcEvent evt)
{
DateTime time = DateTime.Now;
var text = ("Beam me up!\n\n" + "Beam : " +
time.ToString("HH:mm:ss"));
NdefMessage msg = new NdefMessage(
new NdefRecord[]{ CreateMimeRecord (
"application/com.example.android.beam",
Encoding.UTF8.GetBytes (text)) });
return msg;
}
public NdefRecord CreateMimeRecord(String mimeType, byte[] payload)
{
byte[] mimeBytes = Encoding.UTF8.GetBytes(mimeType);
NdefRecord mimeRecord = new NdefRecord(
NdefRecord.TnfMimeMedia, mimeBytes, new byte[0], payload);
return mimeRecord;
}
}
}
It says 'PhoneBeam does not implement interface member NfcAdapter.IOnNdefPushCompleteCallback.OnNdefPushComplete(NfcEvent)'. Am i missing something?
Your class implements IOnNdefPushCompleteCallback, which has a public method OnNdefPushComplete that must be implemented in order to satisfy the Interface.

Xamarin.Forms - OnStop(), OnExit(), OnClose()

I'm developing an app and I need to know when the app gets Stopped, Closed, Exited, whatever interrupts it, in order to stop some services such as WebSocket. How can I get 'access' to those events?
Thanks!
I have tested the following in a small example. (Tested it on UWP and works, the OnSleep() is called, when i close the App). The OnSleep() Method which can be overridden in the App.xaml.cs is the Method you are looking for.
The Xamarin Application LifeCycle offers some methods for your needs.
OnStart - Called when the application starts.
OnSleep - Called each time the application goes to the background.
OnResume - Called when the application is resumed, after being sent to the background.
Note that there is no method for application termination. Under normal
circumstances (ie. not a crash) application termination will happen
from the OnSleep state, without any additional notifications to your
code.
Example:
using System;
using System.Diagnostics;
using Xamarin.Forms;
namespace App1
{
public partial class App : Application
{
public App()
{
InitializeComponent();
if (Device.RuntimePlatform == Device.iOS)
MainPage = new MainPage();
else
MainPage = new NavigationPage(new MainPage());
}
protected override void OnStart() {
Debug.WriteLine("OnStart");
}
protected override void OnSleep() {
Debug.WriteLine("OnSleep");
}
protected override void OnResume() {
Debug.WriteLine("OnResume");
}
}
}
Update
According to this you have to catch unhandled exceptions in the native code. That makes it a lil complicated to shutdown your services.
Example:
public class MainActivity : global::Xamarin.Forms.Platform.Android.FormsAppCompatActivity {
protected override void OnCreate(Bundle bundle) {
TabLayoutResource = Resource.Layout.Tabbar;
ToolbarResource = Resource.Layout.Toolbar;
AppDomain.CurrentDomain.UnhandledException += CurrentDomainOnUnhandledException;
base.OnCreate(bundle);
global::Xamarin.Forms.Forms.Init(this, bundle);
LoadApplication(new App());
}
private void CurrentDomainOnUnhandledException(object sender, UnhandledExceptionEventArgs unhandledExceptionEventArgs) {
//crashed by exception
}
}
Further Reading on Unhandled Exceptions: here

Xamarin-UItest: System.InvalidOperationException : Sequence contains no elements

I am trying to Xamarin.uiTest to automate an application and I got this error in very initial stage.
System.InvalidOperationException : Sequence contains no elements
Code: AppInitializer.cs
using System;
using System.IO;
using System.Linq;
using Xamarin.UITest;
using Xamarin.UITest.Queries;
namespace MyXamarinApp1_Test1
{
public class AppInitializer
{
public static IApp StartApp(Platform platform)
{
if (platform == Platform.Android)
{
return ConfigureApp
.Android
//.InstalledApp("com.companyname.MyXamarinApp1")
.ApkFile("C:\\Users\\...\\Desktop\\com.companyname.MyXamarinApp1.apk")
.StartApp();
}
return ConfigureApp
.iOS.StartApp();
}
}
}
Code: Test.cs
using System;
using System.IO;
using System.Linq;
using NUnit.Framework;
using Xamarin.UITest;
using Xamarin.UITest.Queries;
namespace UITest1
{
[TestFixture(Platform.Android)]
[TestFixture(Platform.iOS)]
public class Tests
{
IApp app;
Platform platform;
public Tests(Platform platform)
{
this.platform = platform;
}
[SetUp]
public void BeforeEachTest()
{
app = AppInitializer.StartApp(platform);
}
[Test]
public void AppLaunches()
{
app.Screenshot("First screen.");
}
}
Any idea to resolve the issue is appreciated.
I am using the signed app, could it be an issue.
Xamarin version : 2.0.3
Nunit : 2.6.4
try downgrading or upgrading it to Xamarin 2.2.1 or less and try cleaning solution or delete debug folder and build and run the command in fresh command line window, it may fix.. not 100% sure

signalr example not working

i just installed the signalr sample (downloaded with nuget)
everything from nuget installed fine and it's a clean project (just to test the sample), yet i get the following error:
throw "SignalR: Connection must be started before data can be sent. Call .start() before .send()";
use package manager
install-package Microsoft.Owin.Host.SystemWeb
and do changes in startup.cs
using Microsoft.Owin;
using Owin;
[assembly: OwinStartup(typeof(Microsoft.AspNet.SignalR.StockTicker.Startup), "Configuration")]
namespace Microsoft.AspNet.SignalR.StockTicker
{
public static class Startup
{
public static void Configuration(IAppBuilder app)
{
Microsoft.AspNet.SignalR.StockTicker.Startup.ConfigureSignalR(app);
}
public static void ConfigureSignalR(IAppBuilder app)
{
app.MapSignalR();
}
}
}
Replace code in Startup.cs file with the following code block, that will fix the js error hopefully
using Microsoft.Owin;
using Owin;
[assembly: OwinStartup(typeof(Microsoft.AspNet.SignalR.StockTicker.Startup))]
namespace Microsoft.AspNet.SignalR.StockTicker
{
public static class Startup
{
public static void Configuration(IAppBuilder app)
{
app.MapSignalR();
}
}
}
you have first to call,
$.connection.hub.start
for example :
var myConnection = $.connection.myConnection;
$.connection.hub.start({ transport: 'auto' }, function () {
alert('connected');
});
/// now you can do what ever you want.
myConnection.SendHello('Just Testing');
now when you load open the page, you should see the browser message (connected), to make sure that the signalR has established a connection.
You can find a full working demo with source code at :
Example including VS2010 solution
This worked for me first time.

Resources