Error java.exe exited with code 1 Xamarin Firbase Messaging - firebase

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)]

Related

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

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

NServicebus not unable to resolve service for interface in handler

I'm trying to build my first NserviceBus application, but I cannot get it to work. The message arrives on the "backend" but the handler uses DI and NServicebus claims it cannot find the service for the interface. But the code was lifted directly from the examples. I'm missing something and I cannot figure it out.
The Error:
dbug: NServiceBus.LoadHandlersConnector[0]
Processing message type: Messages.JobStartCommand
Message headers:
NServiceBus.MessageId : 0044f261-e3b3-4287-b6f0-ad7400ef43cb
NServiceBus.MessageIntent : Send
NServiceBus.ConversationId : bb4f276f-63fe-450b-b234-ad7400ef43cd
NServiceBus.CorrelationId : 0044f261-e3b3-4287-b6f0-ad7400ef43cb
NServiceBus.ReplyToAddress : ClientUI
NServiceBus.OriginatingMachine : L19002992
NServiceBus.OriginatingEndpoint : ClientUI
$.diagnostics.originating.hostid : e1fecb2b72b8185e47341bb4dfb37dd7
NServiceBus.ContentType : text/xml
NServiceBus.EnclosedMessageTypes : Messages.JobStartCommand, Messages, Version=1.0.0.0, Culture=neutral, PublicKeyToken=null
NServiceBus.Version : 7.5.0
NServiceBus.TimeSent : 2021-07-29 14:31:08:228497 Z
NServiceBus.Retries : 3
NServiceBus.Retries.Timestamp : 2021-07-29 14:31:40:397277 Z
Handlers to invoke:
Extractor.JobStartHandler
Extractor.JobStartHandler
info: NServiceBus.RecoverabilityExecutor[0]
Immediate Retry is going to retry message '0044f261-e3b3-4287-b6f0-ad7400ef43cb' because of an exception:
System.InvalidOperationException: Unable to resolve service for type 'IExtract' while attempting to activate 'Extractor.JobStartHandler'.
at Microsoft.Extensi
My backend program.cs
using Microsoft.Extensions.Hosting;
using System;
using System.Diagnostics;
using System.Linq;
using Microsoft.Extensions.DependencyInjection;
using Microsoft.Extensions.Logging;
using NServiceBus;
using System.Threading.Tasks;
using Messages;
using Extractor;
namespace ExtractorOsiris
{
class Program
{
static void Main(string[] args)
{
CreateHostBuilder(args).Build().Run();
}
public static IHostBuilder CreateHostBuilder(string[] args)
{
var builder = Host.CreateDefaultBuilder(args);
builder.UseWindowsService();
//builder.UseMicrosoftLogFactoryLogging();
builder.ConfigureLogging((ctx, logging) =>
{
logging.AddConfiguration(ctx.Configuration.GetSection("Logging"));
//logging.AddEventLog();
logging.AddConsole();
logging.SetMinimumLevel(LogLevel.Debug);
});
#region back-end-use-nservicebus
builder.UseNServiceBus(ctx =>
{
var endpointConfiguration = new EndpointConfiguration("Sample.Extractor");
endpointConfiguration.UseTransport<LearningTransport>();
var transport = endpointConfiguration.UseTransport<LearningTransport>();
transport.Routing().RouteToEndpoint(typeof(ProcessObjectCommand), "Sample.Processor");
endpointConfiguration.DefineCriticalErrorAction(OnCriticalError);
return endpointConfiguration;
});
#endregion
#region back-end-register-service
builder.ConfigureServices(services =>
{
services.AddSingleton<IExtract, ExtractOsiris>();
});
#endregion
return builder;
}
private static Task OnCriticalError(ICriticalErrorContext arg)
{
throw new NotImplementedException();
}
}
}
The Interface
using Newtonsoft.Json.Linq;
using NServiceBus;
using System;
using System.Threading.Tasks;
namespace Extractor
{
public interface IExtract
{
Task<JArray> Extract(string #object, DateTime deltaTime);
}
}
The handler
using System.Threading.Tasks;
using Messages;
using Newtonsoft.Json.Linq;
using NServiceBus;
namespace Extractor
{
#region back-end-handler
public class JobStartHandler : IHandleMessages<JobStartCommand>
{
private readonly IExtract extractor;
public JobStartHandler(IExtract extractor)
{
this.extractor = extractor;
}
public async Task Handle(JobStartCommand message, IMessageHandlerContext context)
{
Task<JArray> result = extractor.Extract("Medewerkers", message.DeltaTime);
await result;
JArray test = result.Result;
foreach (JObject x in test)
{
// send the object to be processed.
//await context.Send(new ProcessObjectCommand(x.ToString()));
}
}
}
#endregion
}
The implementation of the interface
using System;
using System.IO;
using System.Net;
using System.Threading.Tasks;
using Extractor;
using Microsoft.Extensions.Logging;
using Newtonsoft.Json;
using Newtonsoft.Json.Linq;
using NServiceBus;
namespace ExtractorOsiris
{
public class ExtractOsiris : IExtract
{
private readonly ILogger logger;
public ExtractOsiris(ILogger<ExtractOsiris> logger)
{
this.logger = logger;
}
public Task<JArray> Extract(string #object, DateTime deltaTime)
{
logger.LogInformation($"getting {#object} for delta time {deltaTime}");
HttpWebRequest request = (HttpWebRequest)HttpWebRequest.Create("https://xx.yy");
WebResponse response = request.GetResponse();
JObject temp = JObject.Load(new JsonTextReader(new StreamReader(response.GetResponseStream())));
return Task<JArray>.FromResult(temp["items"] as JArray);
}
}
}
I know the code ain't pretty, but it's pure quick and dirty testing code.
I cleaned out the offending interface from the code and still got the error on an interface that was not even there anymore. I removed the bin folder and build everything back up step by step. Stupid thing is, source control says I am back where I started, without changes. And it just works....
So must have bin something stupid with VS2019. Sorry to anyone who's time I wasted

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.

Unit Testing code built with MVVMCross SQLite Plugin

I'm currently building a Xamarin.Forms project using MVVMCross. In order to test my platform specific code I am using Nunit.Xamarin which features an app that run tests on device.
This test app is a forms app but doesn't use MVVMCross and I haven't had any luck setting it up to use MVVMCross due to the fact the Application class loads an App of type NUnit.Runner.App whereas MVVMCross requires MvxFormsApp.
I want to test this class the saves and loads user data from an SQLite Database:
public class DataStorageService : IDataStorageService
{
private readonly SQLiteConnection _connection;
public User UserData
{
get { return _connection.Table<User>().FirstOrDefault(); }
set { _connection.InsertOrReplace(value); }
}
public DataStorageService(IMvxSqliteConnectionFactory factory)
{
_connection = factory.GetConnection(DataStorageConstants.LocalDatabaseName);
_connection.CreateTable<User>();
}
}
I want to actually test that it saves and loads from a local SQLite database so I don't want to mock the IMvxSqliteConnectionFactory. I tried installing MVVMCross and the SQLite plugin into the project and then passing in the Android implementation of the connection factory but that repeatedly threw a typeloadexception.
Any ideas as to how I can set up this test with MVVMCross (or are there alternatives?) and dependency injection?
It is possible :) The important stuff happens in the MvxSplashScreenActivity. The MvxFormsApp is basically empty. So we don't have to care. Example Code: https://github.com/smstuebe/stackoverflow-answers/tree/master/mvx-android-test-app
Create a nunit Test app project
Install-Package MvvmCross.StarterPack -Version 4.1.4
Get rid of Views folder
Install the SQLite plugin
Reference your Core project
Install-Package MvvmCross.Forms.Presenter -Version 4.1.4
Remove MainLauncher = true from MainActivity
Adust Setup to return your core project's App
protected override IMvxApplication CreateApp()
{
return new MyApp.Core.App();
}
Change SplashScreen to (source)
[Activity(MainLauncher = true
, Theme = "#style/Theme.Splash"
, NoHistory = true
, ScreenOrientation = ScreenOrientation.Portrait)]
public class SplashScreen
: MvxSplashScreenActivity
{
public SplashScreen()
: base(Resource.Layout.SplashScreen)
{
}
private bool _isInitializationComplete;
public override void InitializationComplete()
{
if (!_isInitializationComplete)
{
_isInitializationComplete = true;
StartActivity(typeof(MainActivity));
}
}
protected override void OnCreate(Android.OS.Bundle bundle)
{
Forms.Init(this, bundle);
Forms.ViewInitialized += (object sender, ViewInitializedEventArgs e) =>
{
if (!string.IsNullOrWhiteSpace(e.View.StyleId))
{
e.NativeView.ContentDescription = e.View.StyleId;
}
};
base.OnCreate(bundle);
}
}
Write a test like
[TestFixture]
public class TestClass
{
[Test]
public void TestMethod()
{
var service = Mvx.Resolve<IDataStorageService>();
Assert.IsNull(service.UserData);
}
}
Enjoy the awesomeness of MvvmCross

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