How to connect postman gRPC mock server by Android app? - android

I'm struggling to access postman gRPC mock server by Android/kotlin app for several days.
I created the mock server after reading official document. I got the URL for mock server and I could get a response by grpcurl and a Node.js gRPC client. However, I got a error when I used the URL by Android gRPC client.
Stacktrace is below.
java.lang.RuntimeException: Unable to start activity ComponentInfo{io.github.aniokrait.grpcsample/io.github.aniokrait.grpcsample.MainActivity}: io.grpc.StatusRuntimeException: UNAVAILABLE
at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:3449)
at android.app.ActivityThread.handleLaunchActivity(ActivityThread.java:3601)
at android.app.servertransaction.LaunchActivityItem.execute(LaunchActivityItem.java:85)
at android.app.servertransaction.TransactionExecutor.executeCallbacks(TransactionExecutor.java:135)
at android.app.servertransaction.TransactionExecutor.execute(TransactionExecutor.java:95)
at android.app.ActivityThread$H.handleMessage(ActivityThread.java:2066)
at android.os.Handler.dispatchMessage(Handler.java:106)
at android.os.Looper.loop(Looper.java:223)
at android.app.ActivityThread.main(ActivityThread.java:7656)
at java.lang.reflect.Method.invoke(Native Method)
at com.android.internal.os.RuntimeInit$MethodAndArgsCaller.run(RuntimeInit.java:592)
at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:947)
Caused by: io.grpc.StatusRuntimeException: UNAVAILABLE
at io.grpc.stub.ClientCalls.toStatusRuntimeException(ClientCalls.java:271)
at io.grpc.stub.ClientCalls.getUnchecked(ClientCalls.java:252)
at io.grpc.stub.ClientCalls.blockingUnaryCall(ClientCalls.java:165)
at com.book.BookServiceGrpc$BookServiceBlockingStub.getBook(BookServiceGrpc.java:312)
at io.github.aniokrait.grpcsample.MainActivity$Companion.startGrpc(MainActivity.kt:71)
at io.github.aniokrait.grpcsample.MainActivity$Companion.access$startGrpc(MainActivity.kt:34)
at io.github.aniokrait.grpcsample.MainActivity.onCreate(MainActivity.kt:30)
at android.app.Activity.performCreate(Activity.java:8000)
at android.app.Activity.performCreate(Activity.java:7984)
at android.app.Instrumentation.callActivityOnCreate(Instrumentation.java:1309)
at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:3422)
at android.app.ActivityThread.handleLaunchActivity(ActivityThread.java:3601) 
at android.app.servertransaction.LaunchActivityItem.execute(LaunchActivityItem.java:85) 
at android.app.servertransaction.TransactionExecutor.executeCallbacks(TransactionExecutor.java:135) 
at android.app.servertransaction.TransactionExecutor.execute(TransactionExecutor.java:95) 
at android.app.ActivityThread$H.handleMessage(ActivityThread.java:2066) 
at android.os.Handler.dispatchMessage(Handler.java:106) 
at android.os.Looper.loop(Looper.java:223) 
at android.app.ActivityThread.main(ActivityThread.java:7656) 
at java.lang.reflect.Method.invoke(Native Method) 
at com.android.internal.os.RuntimeInit$MethodAndArgsCaller.run(RuntimeInit.java:592) 
at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:947) 
Caused by: java.lang.RuntimeException: TLS ALPN negotiation failed with protocols: [h2]
at io.grpc.okhttp.OkHttpProtocolNegotiator.negotiate(OkHttpProtocolNegotiator.java:104)
at io.grpc.okhttp.OkHttpProtocolNegotiator$AndroidNegotiator.negotiate(OkHttpProtocolNegotiator.java:218)
at io.grpc.okhttp.OkHttpTlsUpgrader.upgrade(OkHttpTlsUpgrader.java:63)
at io.grpc.okhttp.OkHttpClientTransport$3.run(OkHttpClientTransport.java:551)
at io.grpc.internal.SerializingExecutor.run(SerializingExecutor.java:133)
at java.util.concurrent.ThreadPoolExecutor.runWorker(ThreadPoolExecutor.java:1167)
at java.util.concurrent.ThreadPoolExecutor$Worker.run(ThreadPoolExecutor.java:641)
at java.lang.Thread.run(Thread.java:923)
The messages says "TLS ALPN negotiation failed with protocols: [h2]", so I have an idea that the problem is around SSL/TLS, but I don't know how to solve it.
I do not think it is likely to be a certificate issue, as I am able to access the URL from Node.js and grpcurl but the issue of my Android app.
I've read tls-on-android and Update your security provider to protect against SSL exploits.
I added dependecies of play-services and installing code as below but still it doesn't work.
Here's my code.
MainActivity.kt
import android.content.Context
import androidx.appcompat.app.AppCompatActivity
import android.os.Bundle
import android.util.Log
import com.book.BookServiceGrpc
import com.book.Index.GetBookRequest
import com.google.android.gms.security.ProviderInstaller
import io.grpc.okhttp.OkHttpChannelBuilder
class MainActivity : AppCompatActivity() {
override fun onCreate(savedInstanceState: Bundle?) {
super.onCreate(savedInstanceState)
setContentView(R.layout.activity_main)
ProviderInstaller.installIfNeeded(this#MainActivity)
startGrpc()
}
companion object {
private fun startGrpc() {
try {
val channel = OkHttpChannelBuilder
.forAddress("g-95d43o92ollxvwmm7nx895731r4g9y.srv.pstmn.io",443) //URL is slightly altered to prevent tampering
.useTransportSecurity()
.build()
val stub = BookServiceGrpc.newBlockingStub(channel)
val request = GetBookRequest.newBuilder().setIsbn(123).build()
val result = stub.getBook(request)
} catch (e: Exception) {
e.printStackTrace()
throw e
}
}
}
}
my proto file.
syntax = "proto3";
package com.book;
message Book {
int64 isbn = 1;
string title = 2;
string author = 3;
}
message GetBookRequest {
int64 isbn = 1;
}
service BookService {
rpc GetBook (GetBookRequest) returns (Book) {}
}
and dependecies relevant to gRPC
dependencies {
implementation 'io.grpc:grpc-okhttp:1.51.1'
implementation 'io.grpc:grpc-protobuf-lite:1.51.1'
implementation 'io.grpc:grpc-stub:1.51.1'
implementation 'org.apache.tomcat:annotations-api:6.0.53'
implementation 'com.google.android.gms:play-services-basement:18.1.0'
}
Update:
I found these messages in Debug logs.
W/DynamiteModule: Local module descriptor class for com.google.android.gms.providerinstaller.dynamite not found.
I/DynamiteModule: Considering local module com.google.android.gms.providerinstaller.dynamite:0 and remote module com.google.android.gms.providerinstaller.dynamite:0
W/ProviderInstaller: Failed to load providerinstaller module: No acceptable module com.google.android.gms.providerinstaller.dynamite found. Local version is 0 and remote version is 0.
I/ProviderInstaller: Installed default security provider GmsCore_OpenSSL
Perhaps The Dynamic Security Provider isn't installed properly, but still I don't know why.

Related

Cannot get app name correctly in android API 30 or higher

I want to get a list of app names installed on android phone.
However, when I run my code, I can't get some of the app names correctly as shown below.
D/applicationName: com.android.gallery3d.app.GalleryActivity
D/applicationName: Messaging
D/applicationName: Settings
D/applicationName: Maps
D/applicationName: com.android.documentsui.LauncherActivity
D/applicationName: res/menu/example_menu.xml
D/applicationName: res/color/abc_primary_text_material_light.xml
Also, when the correct app name cannot be obtained, the following error occurs
E/mple.getapplis: Resource 7f100082 is a complex map type.
W/PackageManager: Failure retrieving text 0x7f100082 in package com.android.documentsui
android.content.res.Resources$NotFoundException: String resource ID #0x7f100082
at android.content.res.Resources.getText(Resources.java:444)
at android.app.ApplicationPackageManager.getText(ApplicationPackageManager.java:2004)
at android.content.pm.ComponentInfo.loadUnsafeLabel(ComponentInfo.java:103)
at android.content.pm.PackageItemInfo.loadLabel(PackageItemInfo.java:210)
at android.content.pm.ResolveInfo.loadLabel(ResolveInfo.java:225)
at com.example.getapplist.MainActivity.onCreate(MainActivity.kt:22)
at android.app.Activity.performCreate(Activity.java:7994)
at android.app.Activity.performCreate(Activity.java:7978)
at android.app.Instrumentation.callActivityOnCreate(Instrumentation.java:1309)
at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:3422)
at android.app.ActivityThread.handleLaunchActivity(ActivityThread.java:3601)
at android.app.servertransaction.LaunchActivityItem.execute(LaunchActivityItem.java:85)
at android.app.servertransaction.TransactionExecutor.executeCallbacks(TransactionExecutor.java:135)
at android.app.servertransaction.TransactionExecutor.execute(TransactionExecutor.java:95)
at android.app.ActivityThread$H.handleMessage(ActivityThread.java:2066)
at android.os.Handler.dispatchMessage(Handler.java:106)
at android.os.Looper.loop(Looper.java:223)
at android.app.ActivityThread.main(ActivityThread.java:7656)
at java.lang.reflect.Method.invoke(Native Method)
at com.android.internal.os.RuntimeInit$MethodAndArgsCaller.run(RuntimeInit.java:592)
at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:947)
Sometimes I get a list of each app name is correct, but after a few builds, the above situation occurs.
And this situation occurs only if my code runs in api 30 and above.
My code is below.
class MainActivity : AppCompatActivity() {
override fun onCreate(savedInstanceState: Bundle?) {
super.onCreate(savedInstanceState)
setContentView(R.layout.activity_main)
val pm = this.packageManager
val intent = Intent()
intent.action = Intent.ACTION_MAIN
intent.addCategory(Intent.CATEGORY_LAUNCHER)
val applications = pm.queryIntentActivities(intent, 0)
for (resolverInfo in applications) {
val applicationName = resolverInfo.loadLabel(pm).toString()
Log.d("applicationName", applicationName)
}
}
}
I already added following setting in AndroidManifest.xml
<uses-permission android:name="android.permission.QUERY_ALL_PACKAGES"
tools:ignore="QueryAllPackagesPermission" />
Does anyone know how to fix it?
I removed my app and rebuilt, this problem was solved! I think this is a bug of IDE.
try this
public String getAppLable(Context context) {
PackageManager packageManager = context.getPackageManager();
ApplicationInfo applicationInfo = null;
try {
applicationInfo = packageManager.getApplicationInfo(context.getApplicationInfo().packageName, 0);
} catch (final NameNotFoundException e) {
}
return (String) (applicationInfo != null ? packageManager.getApplicationLabel(applicationInfo) : "Unknown");
}

FirebaseRemoteConfigServerException when connect for remote config

I have created a Firebase project and add google-services.json to app module.
I have setup Firebase remote config as follow :
private fun initFirebaseRemoteConfig() {
val remoteConfig = Firebase.remoteConfig
val configSettings = remoteConfigSettings {
minimumFetchIntervalInSeconds = if (BuildConfig.DEBUG) 0 else 3600
}
//remoteConfig.setDefaultsAsync(R.xml.remote_config_defaults)
remoteConfig.setConfigSettingsAsync(configSettings)
remoteConfig.fetchAndActivate().addOnCompleteListener { task ->
val updated = task.result
if (task.isSuccessful) {
Timber.d("Config params updated: $updated")
} else {
Timber.d("Unsuccessful")
}
}
}
I receive following exception on this line task.result as follow :
com.google.android.gms.tasks.RuntimeExecutionException: com.google.firebase.remoteconfig.FirebaseRemoteConfigServerException: Fetch failed: The user is not authorized to access the project. Please make sure you are using the API key that corresponds to your Firebase project.
at com.google.android.gms.tasks.zzu.getResult(com.google.android.gms:play-services-tasks##17.0.2:15)
at com.sample.android.tmdb.TmdbApp.initFirebaseRemoteConfig$lambda-0(TmdbApp.kt:34)
at com.sample.android.tmdb.TmdbApp.lambda$P4-jkzwf9-IJZ17_EtnpghkBXis(Unknown Source:0)
at com.sample.android.tmdb.-$$Lambda$TmdbApp$P4-jkzwf9-IJZ17_EtnpghkBXis.onComplete(Unknown Source:0)
at com.google.android.gms.tasks.zzi.run(com.google.android.gms:play-services-tasks##17.0.2:4)
at android.os.Handler.handleCallback(Handler.java:938)
at android.os.Handler.dispatchMessage(Handler.java:99)
at com.google.android.gms.internal.tasks.zzb.dispatchMessage(com.google.android.gms:play-services-tasks##17.0.2:6)
at android.os.Looper.loop(Looper.java:223)
at android.app.ActivityThread.main(ActivityThread.java:7656)
at java.lang.reflect.Method.invoke(Native Method)
at com.android.internal.os.RuntimeInit$MethodAndArgsCaller.run(RuntimeInit.java:592)
at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:947)
Caused by: com.google.firebase.remoteconfig.FirebaseRemoteConfigServerException: Fetch failed: The user is not authorized to access the project. Please make sure you are using the API key that corresponds to your Firebase project.
at com.google.firebase.remoteconfig.internal.ConfigFetchHandler.createExceptionWithGenericMessage(ConfigFetchHandler.java:380)
at com.google.firebase.remoteconfig.internal.ConfigFetchHandler.fetchFromBackend(ConfigFetchHandler.java:333)
at com.google.firebase.remoteconfig.internal.ConfigFetchHandler.fetchFromBackendAndCacheResponse(ConfigFetchHandler.java:278)
at com.google.firebase.remoteconfig.internal.ConfigFetchHandler.lambda$fetchIfCacheExpiredAndNotThrottled$1$ConfigFetchHandler(ConfigFetchHandler.java:215)
at com.google.firebase.remoteconfig.internal.-$$Lambda$ConfigFetchHandler$PAoFtfQiOtbXSTeK4H2aFJ-JNJI.then(Unknown Source:8)
at com.google.android.gms.tasks.zzg.run(com.google.android.gms:play-services-tasks##17.0.2:2)
at java.util.concurrent.ThreadPoolExecutor.runWorker(ThreadPoolExecutor.java:1167)
at java.util.concurrent.ThreadPoolExecutor$Worker.run(ThreadPoolExecutor.java:641)
at java.lang.Thread.run(Thread.java:923)
Caused by: com.google.firebase.remoteconfig.FirebaseRemoteConfigServerException: Forbidden
at com.google.firebase.remoteconfig.internal.ConfigFetchHttpClient.fetch(ConfigFetchHttpClient.java:195)
at com.google.firebase.remoteconfig.internal.ConfigFetchHandler.fetchFromBackend(ConfigFetchHandler.java:307)
at com.google.firebase.remoteconfig.internal.ConfigFetchHandler.fetchFromBackendAndCacheResponse(ConfigFetchHandler.java:278) 
at com.google.firebase.remoteconfig.internal.ConfigFetchHandler.lambda$fetchIfCacheExpiredAndNotThrottled$1$ConfigFetchHandler(ConfigFetchHandler.java:215) 
at com.google.firebase.remoteconfig.internal.-$$Lambda$ConfigFetchHandler$PAoFtfQiOtbXSTeK4H2aFJ-JNJI.then(Unknown Source:8) 
at com.google.android.gms.tasks.zzg.run(com.google.android.gms:play-services-tasks##17.0.2:2) 
at java.util.concurrent.ThreadPoolExecutor.runWorker(ThreadPoolExecutor.java:1167) 
at java.util.concurrent.ThreadPoolExecutor$Worker.run(ThreadPoolExecutor.java:641) 
at java.lang.Thread.run(Thread.java:923) 

Is it possible to use RSocket in android with kotlin?

I'm trying to use Rsocket in android to communicate with the spring-boot server with kotlin. unfortunately, rsocket doesn't have good documentation. I try this code from the rsocket kotlin Github pages but I got an error.
This is my dependency:
implementation("io.rsocket.kotlin:rsocket-core:0.12.0")
implementation("io.rsocket.kotlin:rsocket-transport-ktor:0.12.0")
implementation("io.rsocket.kotlin:rsocket-transport-ktor-client:0.12.0")
implementation("io.ktor:ktor-client-cio:1.4.3")
This is my code:
CoroutineScope(Dispatchers.Main).launch {
val client = HttpClient(CIO) {
install(WebSockets)
install(RSocketSupport)
}
val rSocket: RSocket = client.rSocket("http://demo.rsocket.io/")
val stream: Flow<Payload> = rSocket.requestStream(Payload.Empty)
stream.take(5).map { payload: Payload ->
println(payload.data.readText())
}
}
The error that I have got:
2021-06-04 17:38:49.682 31873-31873/com.example.rsockettest E/AndroidRuntime: FATAL EXCEPTION: main
Process: com.example.rsockettest, PID: 31873
java.lang.NoSuchMethodError: No static method getSeconds(I)D in class Lkotlin/time/DurationKt; or its super classes (declaration of 'kotlin.time.DurationKt' appears in /data/app/~~TL05n0pUBJZXhnzTYygaSg==/com.example.rsockettest-iWVKDxzJU4GvHrKyFG8j5A==/base.apk)
at io.rsocket.kotlin.keepalive.KeepAlive.<init>(KeepAlive.kt:22)
at io.rsocket.kotlin.core.RSocketConnectorBuilder$ConnectionConfigBuilder.<init>(RSocketConnectorBuilder.kt:70)
at io.rsocket.kotlin.core.RSocketConnectorBuilder.<init>(RSocketConnectorBuilder.kt:28)
at io.rsocket.kotlin.core.RSocketConnectorBuilderKt.RSocketConnector(RSocketConnectorBuilder.kt:112)
at io.rsocket.kotlin.core.RSocketConnectorBuilderKt.RSocketConnector$default(RSocketConnectorBuilder.kt:111)
at io.rsocket.kotlin.transport.ktor.client.RSocketSupport$Config.<init>(RSocketSupport.kt:30)
at io.rsocket.kotlin.transport.ktor.client.RSocketSupport$Feature.prepare(RSocketSupport.kt:36)
at io.rsocket.kotlin.transport.ktor.client.RSocketSupport$Feature.prepare(RSocketSupport.kt:33)
at io.ktor.client.HttpClientConfig$install$3.invoke(HttpClientConfig.kt:77)
at io.ktor.client.HttpClientConfig$install$3.invoke(HttpClientConfig.kt:74)
at io.ktor.client.HttpClientConfig.install(HttpClientConfig.kt:97)
at io.ktor.client.HttpClient.<init>(HttpClient.kt:172)
at io.ktor.client.HttpClient.<init>(HttpClient.kt:81)
at io.ktor.client.HttpClientKt.HttpClient(HttpClient.kt:43)
at com.example.rsockettest.MainActivity$onCreate$1.invokeSuspend(MainActivity.kt:41)
at kotlin.coroutines.jvm.internal.BaseContinuationImpl.resumeWith(ContinuationImpl.kt:33)
at kotlinx.coroutines.DispatchedTask.run(DispatchedTask.kt:106)
at android.os.Handler.handleCallback(Handler.java:938)
at android.os.Handler.dispatchMessage(Handler.java:99)
at android.os.Looper.loop(Looper.java:223)
at android.app.ActivityThread.main(ActivityThread.java:7656)
at java.lang.reflect.Method.invoke(Native Method)
at com.android.internal.os.RuntimeInit$MethodAndArgsCaller.run(RuntimeInit.java:592)
at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:947)
2021-06-04 17:38:49.722 31873-31873/com.example.rsockettest I/Process: Sending signal. PID: 31873 SIG: 9
if it's not possible to use rsocket in android, can you offer for instead for that? I want to build an application that streams data reactively.

Exception 'android.system.ErrnoException' occurred in thread 'SharedPreferencesImpl-load' at libcore.io.Linux.access(Linux.java:-1)

I am trying to work through building the google sunflower app and I am getting stuck loading my json file I think. I am unable to hit any break points which to me means that I am breaking on an error loading permissions maybe. I am debugging on an actual pizel 3 and I think perhaps I have my phone locked down too much. I have also tried adding reading permissions to the manifest file. Here is the code
private fun buildDatabase(context: Context): AppDatabase {
// create the room
return Room.databaseBuilder(context, AppDatabase::class.java, DATABASE_NAME)
.addCallback(object : RoomDatabase.Callback() {
// when created, seed it
override fun onCreate(db: SupportSQLiteDatabase) {
super.onCreate(db)
// create the work manager request
val request = OneTimeWorkRequestBuilder<SeedDatabaseWorker>().build()
// fire it
WorkManager.getInstance(context).enqueue(request)
}
})
.build()
}
and here is my error stack from debugging:
Connected to the target VM, address: 'localhost:8608', transport: 'socket'
Exception 'android.system.ErrnoException' occurred in thread 'SharedPreferencesImpl-load' at libcore.io.Linux.access(Linux.java:-1)
Breakpoint reached
at libcore.io.Linux.access(Linux.java:-1)
at libcore.io.ForwardingOs.access(ForwardingOs.java:73)
at libcore.io.BlockGuardOs.access(BlockGuardOs.java:71)
at libcore.io.ForwardingOs.access(ForwardingOs.java:73)
at android.app.ActivityThread$AndroidOs.access(ActivityThread.java:7246)
at java.io.UnixFileSystem.checkAccess(UnixFileSystem.java:281)
at java.io.File.exists(File.java:815)
at android.app.SharedPreferencesImpl.loadFromDisk(SharedPreferencesImpl.java:136)
at android.app.SharedPreferencesImpl.access$000(SharedPreferencesImpl.java:55)
at android.app.SharedPreferencesImpl$1.run(SharedPreferencesImpl.java:126)
Exception 'java.lang.ClassNotFoundException' occurred in thread 'main' at java.lang.Class.classForName(Class.java:-1)
Breakpoint reached
at java.lang.Class.classForName(Class.java:-1)
at java.lang.BootClassLoader.findClass(ClassLoader.java:1358)
at java.lang.BootClassLoader.loadClass(ClassLoader.java:1418)
at java.lang.ClassLoader.loadClass(ClassLoader.java:367)
at java.lang.ClassLoader.loadClass(ClassLoader.java:312)
at java.lang.Class.classForName(Class.java:-1)
at java.lang.Class.forName(Class.java:454)
at android.view.LayoutInflater.createView(LayoutInflater.java:815)
at android.view.LayoutInflater.createView(LayoutInflater.java:776)
at com.android.internal.policy.PhoneLayoutInflater.onCreateView(PhoneLayoutInflater.java:58)
at android.view.LayoutInflater.onCreateView(LayoutInflater.java:930)
at android.view.LayoutInflater.onCreateView(LayoutInflater.java:950)
at android.view.LayoutInflater.createViewFromTag(LayoutInflater.java:1004)
at android.view.LayoutInflater.createViewFromTag(LayoutInflater.java:961)
at android.view.LayoutInflater.rInflate(LayoutInflater.java:1123)
at android.view.LayoutInflater.rInflateChildren(LayoutInflater.java:1084)
at android.view.LayoutInflater.inflate(LayoutInflater.java:682)
at android.view.LayoutInflater.inflate(LayoutInflater.java:534)
at android.view.LayoutInflater.inflate(LayoutInflater.java:481)
at com.android.internal.policy.DecorView.onResourcesLoaded(DecorView.java:2084)
at com.android.internal.policy.PhoneWindow.generateLayout(PhoneWindow.java:2627)
at com.android.internal.policy.PhoneWindow.installDecor(PhoneWindow.java:2694)
at com.android.internal.policy.PhoneWindow.getDecorView(PhoneWindow.java:2094)
at androidx.appcompat.app.AppCompatDelegateImpl.createSubDecor(AppCompatDelegateImpl.java:575)
at androidx.appcompat.app.AppCompatDelegateImpl.ensureSubDecor(AppCompatDelegateImpl.java:518)
at androidx.appcompat.app.AppCompatDelegateImpl.setContentView(AppCompatDelegateImpl.java:466)
at androidx.appcompat.app.AppCompatActivity.setContentView(AppCompatActivity.java:140)
at androidx.databinding.DataBindingUtil.setContentView(DataBindingUtil.java:303)
at androidx.databinding.DataBindingUtil.setContentView(DataBindingUtil.java:284)
at com.stegner.androiddex.PokedexActivity.onCreate(PokedexActivity.kt:22)
at android.app.Activity.performCreate(Activity.java:7802)
at android.app.Activity.performCreate(Activity.java:7791)
at android.app.Instrumentation.callActivityOnCreate(Instrumentation.java:1306)
at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:3245)
at android.app.ActivityThread.handleLaunchActivity(ActivityThread.java:3409)
at android.app.servertransaction.LaunchActivityItem.execute(LaunchActivityItem.java:83)
at android.app.servertransaction.TransactionExecutor.executeCallbacks(TransactionExecutor.java:135)
at android.app.servertransaction.TransactionExecutor.execute(TransactionExecutor.java:95)
at android.app.ActivityThread$H.handleMessage(ActivityThread.java:2016)
at android.os.Handler.dispatchMessage(Handler.java:107)
at android.os.Looper.loop(Looper.java:214)
at android.app.ActivityThread.main(ActivityThread.java:7356)
at java.lang.reflect.Method.invoke(Method.java:-1)
at com.android.internal.os.RuntimeInit$MethodAndArgsCaller.run(RuntimeInit.java:492)
at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:930)
Disconnected from the target VM, address: 'localhost:8608', transport: 'socket'
I am only able to hit this when I toggle Java exception and exception breakpoints. Any help is greatly appreciated!

How to initialize Firebase Cloud Messaging in a lower library?

I moved Firebase Cloud Messaging to a library, so that I can import this into any of my apps and provide push messages. So therefore I created a library and moved everything from this example to my library.
Then I compile this library in my build.gradle and use it as desired.
This works so far when I instantiate Firebase from app level:
FirebaseMessaging.getInstance().subscribeToTopic(topic)
Now, I thought of moving this down into my library:
fun initFirebaseMessaging(topic : String) : String
{
FirebaseMessaging.getInstance().subscribeToTopic(topic)
Timber.d("Push subscribeToTopic $topic")
val token = FirebaseInstanceId.getInstance().token!!
Timber.d("Push FirebaseinstanceId token $token")
sendRegistrationToServer(token)
return token
}
Since I do not hand over the app level context, I get:
E/AndroidRuntime: FATAL EXCEPTION: main
Process: com.example.demo, PID: 8047
java.lang.RuntimeException: Unable to start activity ComponentInfo{com.example.demo/com.example.MainActivity}: java.lang.IllegalStateException: Default FirebaseApp is not initialized in this process com.example.demo. Make sure to call FirebaseApp.initializeApp(Context) first.
at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:2817)
at android.app.ActivityThread.handleLaunchActivity(ActivityThread.java:2892)
at android.app.ActivityThread.-wrap11(Unknown Source:0)
at android.app.ActivityThread$H.handleMessage(ActivityThread.java:1593)
at android.os.Handler.dispatchMessage(Handler.java:105)
at android.os.Looper.loop(Looper.java:164)
at android.app.ActivityThread.main(ActivityThread.java:6541)
at java.lang.reflect.Method.invoke(Native Method)
at com.android.internal.os.Zygote$MethodAndArgsCaller.run(Zygote.java:240)
at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:767)
Caused by: java.lang.IllegalStateException: Default FirebaseApp is not initialized in this process com.example.demo. Make sure to call FirebaseApp.initializeApp(Context) first.
at com.google.firebase.FirebaseApp.getInstance(Unknown Source:58)
at com.google.firebase.iid.FirebaseInstanceId.getInstance(Unknown Source:0)
at com.google.firebase.messaging.FirebaseMessaging.getInstance(Unknown Source:9)
at com.example.network.fcm.exampleFirebaseInstanceIdService$Companion.initFirebaseMessaging(exampleFirebaseInstanceIdService.kt:14)
at com.example.MainActivity.onCreate(MainActivity.kt:168)
at android.app.Activity.performCreate(Activity.java:6975)
at android.app.Instrumentation.callActivityOnCreate(Instrumentation.java:1213)
at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:2770)
at android.app.ActivityThread.handleLaunchActivity(ActivityThread.java:2892) 
at android.app.ActivityThread.-wrap11(Unknown Source:0) 
at android.app.ActivityThread$H.handleMessage(ActivityThread.java:1593) 
at android.os.Handler.dispatchMessage(Handler.java:105) 
at android.os.Looper.loop(Looper.java:164) 
at android.app.ActivityThread.main(ActivityThread.java:6541) 
at java.lang.reflect.Method.invoke(Native Method) 
at com.android.internal.os.Zygote$MethodAndArgsCaller.run(Zygote.java:240) 
at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:767) 
ADDENDUM: I added that line to my init
fun initFirebaseMessaging(topic : String, context : context) : String
{
FirebaseApp.initializeApp(context)
FirebaseMessaging.getInstance().subscribeToTopic(topic)
Timber.d("Push subscribeToTopic $topic")
val token = FirebaseInstanceId.getInstance().token!!
Timber.d("Push FirebaseinstanceId token $token")
sendRegistrationToServer(token)
return token
}
leads to very same error message.
Your error
Make sure to call FirebaseApp.initializeApp(Context) first.
In your library u need create function like
public static void Init(Context context) {
FirebaseApp.initializeApp(context);
}
and call it before using firebase. Best way its add to your application
example :
... extends Application /*** code **/
onCreate () {
YourLibrary.Init(this);
}

Categories

Resources