Сбой приложения при получении уведомления FCM на переднем плане работает на фоне - PullRequest
0 голосов
/ 08 июня 2019

Я добавил Firebase Cloud Messaging в свое приложение, следуя указаниям в документации.Кажется, работает нормально, но приложение падает при получении на Foreground, но отлично работает, когда оно получает закрытие.

MANIFEST

<?xml version="1.0" encoding="utf-8"?>
<manifest xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:tools="http://schemas.android.com/tools"
package="com. gumangan. uecficenterslist">

<uses-permission android:name="android.permission.INTERNET" />
<uses-permission android:name="android.permission.WRITE_EXTERNAL_STORAGE" />
<uses-permission android:name="android.permission.READ_EXTERNAL_STORAGE" />

<application
    android:allowBackup="true"
    android:icon="@mipmap/ic_launcher"
    android:label="@string/app_name"
    android:roundIcon="@mipmap/ic_launcher_round"
    android:supportsRtl="true"
    android:theme="@style/AppTheme">

    <service
        android:name=".MyFirebaseMessagingService"
        android:enabled="true"
        android:exported="false">
        <intent-filter>
            <action android:name="com.google.firebase.MESSAGING_EVENT" />
        </intent-filter>
    </service>
    <!-- Set custom default icon. This is used when no icon is set for incoming notification messages.
    <meta-data
        android:name="com.google.firebase.messaging.default_notification_icon"
        android:resource="@drawable/ic_menu_camera" />
    <!-- Set color used with incoming notification messages. This is used when no color is set for the incoming
         notification message.
    <meta-data
        android:name="com.google.firebase.messaging.default_notification_color"
        android:resource="@color/colorAccent" />

    <activity
        android:name="com.google.android.gms.ads.AdActivity"
        android:theme="@android:style/Theme.NoTitleBar.Fullscreen"
        tools:replace="android:theme" />
    <activity
        android:name=".MenuActivity"
        android:label="@string/app_name"
        android:theme="@style/AppTheme.NoActionBar">
        <intent-filter>
            <action android:name="android.intent.action.MAIN" />

            <category android:name="android.intent.category.LAUNCHER" />
        </intent-filter>
    </activity>
    <activity
        android:name=".CentersActivity"
        android:label="@string/title_activity_hymns"
        android:launchMode="singleTop"
        android:theme="@style/AppTheme.NoActionBar">
        <intent-filter>
            <action android:name="android.intent.action.SEARCH" />
        </intent-filter>

        <meta-data
            android:name="android.app.searchable"
            android:resource="@xml/searchable" />
    </activity>
    <activity
        android:name=".CentersDetailActivity"
        android:parentActivityName=".CentersActivity">
        <meta-data
            android:name="android.support.PARENT_ACTIVITY"
            android:value="com.gumangan.uecficenterslist.CentersActivity" />
    </activity>
    <activity
        android:name=".YouTubeActivity"
        android:label="@string/title_activity_web"
        android:theme="@style/AppTheme.NoActionBar"></activity>
    <activity
        android:name=".AboutActivity"
        android:theme="@style/AppTheme.NoActionBar" />
    <activity
        android:name=".AffiliateActivity"
        android:theme="@style/AppTheme.NoActionBar" />
    <activity
        android:name=".TermsActivity"
        android:theme="@style/AppTheme.NoActionBar" />
    <activity
        android:name=".WarningActivity"
        android:theme="@style/AppTheme.NoActionBar" />
    <activity
        android:name=".ShareActivity"
        android:label="@string/title_activity_share"
        android:theme="@style/AppTheme.NoActionBar" />
    <activity
        android:name=".SupportActivity"
        android:label="@string/title_activity_support"
        android:theme="@style/AppTheme.NoActionBar" />
    <activity
        android:name=".SubmitActivity"
        android:label="@string/title_activity_submit"
        android:theme="@style/AppTheme.NoActionBar">
    </activity>

</application>
</manifest>

DEPENDENCIES

apply plugin: 'com.android.application'

apply plugin: 'kotlin-android'

apply plugin: 'kotlin-android-extensions'

apply plugin: 'io.fabric'
android {
/* TODO: Don't forget to change versionCode and versionName when updating for final building */
compileSdkVersion 28
defaultConfig {
    applicationId "com. gumangan. uecficenterslist"
    minSdkVersion 16
    targetSdkVersion 28
    versionCode 8
    versionName "1.7"
    testInstrumentationRunner "android.support.test.runner.AndroidJUnitRunner"

    vectorDrawables.useSupportLibrary = true
}
buildTypes {
    release {
        minifyEnabled false
        proguardFiles getDefaultProguardFile('proguard-android.txt'), 'proguard-rules.pro'
    }
}

}

dependencies {
implementation fileTree(dir: 'libs', include: ['*.jar'])
implementation "org.jetbrains.kotlin:kotlin-stdlib-jdk7:$kotlin_version"

implementation 'com.android.support.constraint:constraint-layout:1.1.3'
implementation 'com.android.support:appcompat-v7:28.0.0'
implementation 'com.android.support:support-v4:28.0.0'
implementation 'com.android.support:design:28.0.0'
implementation 'com.android.support:cardview-v7:28.0.0'
implementation 'com.android.support:customtabs:28.0.0'
implementation 'com.android.support:support-core-utils:28.0.0'

implementation 'com.intuit.sdp:sdp-android:1.0.5'
implementation 'com.intuit.ssp:ssp-android:1.0.5'

implementation 'com.google.android.gms:play-services-ads:17.2.1'
implementation 'com.google.firebase:firebase-core:16.0.9'
implementation 'com.google.firebase:firebase-ads:17.2.1'
implementation 'com.crashlytics.sdk.android:crashlytics:2.10.1'

implementation 'com.google.firebase:firebase-messaging:18.0.0'

testImplementation 'junit:junit:4.12'
androidTestImplementation 'com.android.support.test:runner:1.0.2'
androidTestImplementation 'com.android.support.test.espresso:espresso-core:3.0.2'
}
apply plugin: 'com.google.gms.google-services'

MyFirebaseMessagingService.kt

package com.gumangan.uecficenterslist

import android.util.Log
import com.google.firebase.messaging.FirebaseMessagingService
import com.google.firebase.messaging.RemoteMessage
import com.gumangan.uecficenterslist.CentersActivity.Companion.TAG

class MyFirebaseMessagingService : FirebaseMessagingService() {

override fun onMessageReceived(remoteMessage: RemoteMessage?) {
    // ...

    // TODO(developer): Handle FCM messages here.
    // Not getting messages here? See why this may be:
    Log.d(TAG, "From: ${remoteMessage?.from}")

    // Check if message contains a data payload.
    remoteMessage?.data?.isNotEmpty()?.let {
        Log.d(TAG, "Message data payload: " + remoteMessage.data)

        if (/* Check if data needs to be processed by long running job */ true) {
            // For long-running tasks (10 seconds or more) use WorkManager.
            scheduleJob()
        } else {
            // Handle message within 10 seconds
            handleNow()
        }
    }

    // Check if message contains a notification payload.
    remoteMessage?.notification?.let {
        Log.d(TAG, "Message Notification Body: ${it.body}")
    }

    // Also if you intend on generating your own notifications as a result of a received FCM
    // message, here is where that should be initiated. See sendNotification method below.
}

private fun handleNow(): Any {
    TODO("not implemented") //To change body of created functions use File | Settings | File Templates.
}

private fun scheduleJob(): Any {
    TODO("not implemented") //To change body of created functions use File | Settings | File Templates.
}

/**
 * Called if InstanceID token is updated. This may occur if the security of
 * the previous token had been compromised. Note that this is called when the InstanceID token
 * is initially generated so this is where you would retrieve the token.
 */
override fun onNewToken(token: String?) {
    Log.d(TAG, "Refreshed token: $token")

    // If you want to send messages to this application instance or
    // manage this apps subscriptions on the server side, send the
    // Instance ID token to your app server.
    sendRegistrationToServer(token)
}

private fun sendRegistrationToServer(token: String?) {
    TODO("not implemented") //To change body of created functions use File | Settings | File Templates.
}


}

Хорошо, приложение получает уведомления о том, когда оно убивает и фон, но оно падает при получении уведомлений на переднем плане.

V/FA: Connection attempt already in progress
E/AndroidRuntime: FATAL EXCEPTION: Firebase-MyFirebaseMessagingService
Process: com.gumangan.uecficenterslist, PID: 15201
kotlin.NotImplementedError: An operation is not implemented: not implemented
    at com.gumangan.uecficenterslist.MyFirebaseMessagingService.scheduleJob(MyFirebaseMessagingService.kt:44)
    at com.gumangan.uecficenterslist.MyFirebaseMessagingService.onMessageReceived(MyFirebaseMessagingService.kt:23)
    at com.google.firebase.messaging.FirebaseMessagingService.zzd(Unknown Source)
    at com.google.firebase.iid.zzb.run(Unknown Source)
    at java.util.concurrent.ThreadPoolExecutor.runWorker(ThreadPoolExecutor.java:1133)
    at java.util.concurrent.ThreadPoolExecutor$Worker.run(ThreadPoolExecutor.java:607)
    at com.google.android.gms.common.util.concurrent.zza.run(Unknown Source)
    at java.lang.Thread.run(Thread.java:761)

Ответы [ 2 ]

1 голос
/ 08 июня 2019

Просто удалите

TODO("not implemented")

TODO (...) - это функция Kotlin, которая всегда выдает NotImplementedError.Если вы хотите пометить что-то с помощью TODO, но не создавать исключение - просто используйте TODO с комментариями:

Надеюсь, это поможет !!!

0 голосов
/ 08 июня 2019

Согласно ответу Мохита удалить TODO (...), а также удалить тип возврата: Любой из объявления функции.

Например, заменить функцию ниже,

private fun scheduleJob(): Any {
    TODO("not implemented") //To change body of created functions use File | Settings | File Templates.
}

с,

private fun scheduleJob() {
    // TODO : "not implemented"
}
Добро пожаловать на сайт PullRequest, где вы можете задавать вопросы и получать ответы от других членов сообщества.
...