firebase cloud messaging (fcm) 을 android 앱에 전송시 앱 튕김 현상 질문!

조회수 61회
2019-11-07 16:01:18.615 22887-22887/com.example.api21test E/AndroidRuntime: FATAL EXCEPTION: main
    Process: com.example.api21test, PID: 22887
    java.lang.RuntimeException: Unable to instantiate service com.example.api21test.MyFirebaseMessagingService: java.lang.ClassNotFoundException: Didn't find class "com.example.api21test.MyFirebaseMessagingService" on path: DexPathList[[zip file "/data/app/com.example.api21test-1/base.apk"],nativeLibraryDirectories=[/data/app/com.example.api21test-1/lib/arm64, /system/lib64, /vendor/lib64]]
        at android.app.ActivityThread.handleCreateService(ActivityThread.java:3248)
        at android.app.ActivityThread.-wrap5(ActivityThread.java)
        at android.app.ActivityThread$H.handleMessage(ActivityThread.java:1633)
        at android.os.Handler.dispatchMessage(Handler.java:102)
        at android.os.Looper.loop(Looper.java:165)
        at android.app.ActivityThread.main(ActivityThread.java:6375)
        at java.lang.reflect.Method.invoke(Native Method)
        at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:912)
        at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:802)
     Caused by: java.lang.ClassNotFoundException: Didn't find class "com.example.api21test.MyFirebaseMessagingService" on path: DexPathList[[zip file "/data/app/com.example.api21test-1/base.apk"],nativeLibraryDirectories=[/data/app/com.example.api21test-1/lib/arm64, /system/lib64, /vendor/lib64]]
        at dalvik.system.BaseDexClassLoader.findClass(BaseDexClassLoader.java:74)
        at java.lang.ClassLoader.loadClass(ClassLoader.java:380)
        at java.lang.ClassLoader.loadClass(ClassLoader.java:312)
        at android.app.ActivityThread.handleCreateService(ActivityThread.java:3245)
        at android.app.ActivityThread.-wrap5(ActivityThread.java) 
        at android.app.ActivityThread$H.handleMessage(ActivityThread.java:1633) 
        at android.os.Handler.dispatchMessage(Handler.java:102) 
        at android.os.Looper.loop(Looper.java:165) 
        at android.app.ActivityThread.main(ActivityThread.java:6375) 
        at java.lang.reflect.Method.invoke(Native Method) 
        at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:912) 
        at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:802) 
package com.example.api21test;

import android.util.Log;

import com.google.firebase.messaging.FirebaseMessagingService;


public class MyFirebaseMessagingService extends FirebaseMessagingService{
    @Override
    public void onNewToken(String token) {
        Log.d("새로 고침", "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 void sendRegistrationToServer(String token) {
        // TODO: Implement this method to send token to your app server.
    }

}
package com.example.api21test;

import android.os.Bundle;
import android.util.Log;
import android.widget.Toast;

import androidx.annotation.NonNull;
import androidx.appcompat.app.AppCompatActivity;

import com.google.firebase.messaging.FirebaseMessaging;
import com.google.android.gms.tasks.OnCompleteListener;
import com.google.android.gms.tasks.Task;
import com.google.firebase.iid.FirebaseInstanceId;
import com.google.firebase.iid.InstanceIdResult;

public class MainActivity extends AppCompatActivity {

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);
        FirebaseInstanceId.getInstance().getInstanceId()
                .addOnCompleteListener(new OnCompleteListener<InstanceIdResult>() {
                    @Override
                    public void onComplete(@NonNull Task<InstanceIdResult> task) {
                        if (!task.isSuccessful()) {
                            Log.w("실패 : ", "getInstanceId failed", task.getException());
                            return;
                        }

                        // Get new Instance ID token
                        String token = task.getResult().getToken();

                        // Log and toast
                        String msg = getString(R.string.msg_token_fmt, token);
                        Log.d("성공 : ", msg);
                        Toast.makeText(MainActivity.this, msg, Toast.LENGTH_SHORT).show();
                    }
                });
        FirebaseMessaging.getInstance().setAutoInitEnabled(true);
    }
}

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

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

    <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">
        <meta-data
            android:name="com.google.firebase.messaging.default_notification_channel_id"
            android:value="@string/default_notification_channel_id" />
        <meta-data
            android:name="firebase_messaging_auto_init_enabled"
            android:value="false" />
        <meta-data
            android:name="firebase_analytics_collection_enabled"
            android:value="false" />
        <activity android:name="com.example.api21test.MainActivity">
            <intent-filter>
                <action android:name="android.intent.action.MAIN" />

                <category android:name="android.intent.category.LAUNCHER" />
            </intent-filter>
        </activity>
        <service
            android:name="com.example.api21test.MyFirebaseMessagingService"
            android:exported="false">
            <intent-filter>
                <action android:name="com.google.firebase.MESSAGING_EVENT" />
            </intent-filter>
        </service>
    </application>

</manifest>
// Top-level build file where you can add configuration options common to all sub-projects/modules.

buildscript {
    repositories {
        jcenter()
        google()
    }
    dependencies {
        classpath 'com.android.tools.build:gradle:3.5.2'
        classpath 'com.google.gms:google-services:4.3.2'
        // NOTE: Do not place your application dependencies here; they belong
        // in the individual module build.gradle files
    }
}

allprojects {
    repositories {
        jcenter()
        google()
    }
}

task clean(type: Delete) {
    delete rootProject.buildDir
}
apply plugin: 'com.android.application'

android {
    compileSdkVersion 28
    buildToolsVersion "29.0.2"
    defaultConfig {
        applicationId "com.example.api21test"
        minSdkVersion 21
        targetSdkVersion 28
        versionCode 1
        versionName "1.0"
        testInstrumentationRunner "androidx.test.runner.AndroidJUnitRunner"
    }
    buildTypes {
        release {
            minifyEnabled false
            proguardFiles getDefaultProguardFile('proguard-android-optimize.txt'), 'proguard-rules.pro'
        }
    }
}

dependencies {
    implementation fileTree(dir: 'libs', include: ['*.jar'])
    implementation 'androidx.appcompat:appcompat:1.1.0'
    implementation 'androidx.constraintlayout:constraintlayout:1.1.3'
    implementation 'com.android.support:support-core-utils:28.0.0'
    implementation 'com.google.firebase:firebase-messaging:20.0.0'
    testImplementation 'junit:junit:4.12'
    androidTestImplementation 'androidx.test.ext:junit:1.1.1'
    androidTestImplementation 'androidx.test.espresso:espresso-core:3.2.0'
}

apply plugin: 'com.google.gms.google-services'

순서대로 오류 MyFirebaseMessagingService, MainActivty, Manifest, build.gradle(project), build.gradle(module) 코드입니다

firebase에 등록한 앱에서 나온 토큰으로 개인메세지, 전체메세지를 보낼때 이와같은 오류가뜨면서 튕겨버립니다 어디부분이 잘못된걸까요?

  • 오류메세지를 잘 읽어보세요. 질문자가 만든 클래스를 찾지 못한다고 합니다. apk 내에 클래스가 존재하는지 혹은 클래스패스내에 존재하는지 확인해보세요. 정영훈 2019.11.7 16:36

1 답변

  • 다 잘 되어있는것같은데 어느 다른부분이 문제일지도 모르겠네요.

    ...
            android:name="com.example.api21test.MyFirebaseMessagingService"
            android:enabled="true"
            android:exported="true">
    ...
    
    

    이렇게 고쳐서 해보시겠어요?

    그리고 onMessageReceived() 도 오버라이드 해보시기 바랍니다.

    • 현재 오류는고쳤지만 메세지는 안오내요 ㅠ 앱가동후 2초정도 지나면 V/FA: Inactivity, disconnecting from the service 이런 메세지가뜨고 메세지를 보내면 Logging event (FE): notification_receive(_nr), Bundle[{g... 이런게 뜨내요..ㅠ 한희태 2019.11.7 17:10
    • 메세지를 보시려면 onMessageReceived 함수를 구현해야할겁니다. firebase 문서에서 기본동작을 카피해서 넣어보세요 김은기 2019.11.7 17:13
    • 아마 FA 는 파이어베이스 아날리스틱일겁니다. 파이어베이스 문제보다는 앱 구현이 잘못되어있을 수 있습니다. 김은기 2019.11.7 17:16
    • implementation 'com.google.firebase:firebase-core:17.2.1' 이거 빼먹으신 것 같아요. 뉴랜드 2019.11.7 17:33
    • com.google.firebase:firebase-core, onMessageReceived 두개 구현후 실행해도 똑같은 오류가뜨내요..ㅠ 안드로이드는 잘모르다보니 아주기초적인걸 실수한것같은 느낌이듭니다ㅠ 한희태 2019.11.7 18:03
    • firebase 문서 그대로 차근차근 다시 따라해보세요. 뉴랜드 2019.11.7 18:38

답변을 하려면 로그인이 필요합니다.

Hashcode는 개발자들을 위한 무료 QnA 사이트입니다. 계정을 생성하셔야만 답변을 작성하실 수 있습니다.

(ಠ_ಠ)
(ಠ‿ಠ)

ᕕ( ᐛ )ᕗ
로그인이 필요합니다

Hashcode는 개발자들을 위한 무료 QnA사이트 입니다. 계정을 생성하셔야만 글을 작성하실 수 있습니다.