✍2021,2022/app(android studio)

앱만들기.18(FCM푸시알림)

리촬리 2021. 7. 19. 18:12
728x90

 

Firebase 클라우드 메시징

Firebase 클라우드 메시징(FCM)은 무료로 메시지를 안정적으로 전송할 수 있는 교차 플랫폼 메시징 솔루션입니다.

 

FCM을 사용하면 새 이메일이나 기타 데이터를 동기화할 수 있음을 클라이언트 앱에 알릴 수 있습니다. 이렇게 알림 메시지를 전송하여 사용자를 유지하고 재참여를 유도할 수 있습니다. 채팅 메시지와 같은 사용 사례에서는 메시지로 최대 4,000바이트의 페이로드를 클라이언트 앱에 전송할 수 있습니다

 

자세한 FCM구현법 

https://faith-developer.tistory.com/158

 

Android FCM (Firebase Cloud Messaging) 구현해보자

GCM(Goolge Cloud Messaging) 에서 FCM(Firebase Cloud Messaging)으로 변경 및 권장한지도 벌써 몇년이 지나고 있습니다. 개발적 이슈 및 기타 이유로 아직도 GCM 을 사용하는 개발자들도 있습니다. 만약 신규..

faith-developer.tistory.com


 

https://console.firebase.google.com

 

로그인 - Google 계정

하나의 계정으로 모든 Google 서비스를 Google 계정으로 로그인

accounts.google.com

프로젝트 추가

 

android 눌러줌

 

android studio에서 프로젝트만드록, main.js 에서

package com.example.pushtest;

파이어베이스에 com.example.pushtest입력해주기 

 

입력하면 나옴

다운로드 해주깅!

Project 클릭

다운받은 파일 app 에다가 복붙해주기


android로 돌아가서 bulid gradle (project : )로 들어가줌

dependencies 에 추가해줌

classpath 'com.google.gms:google-services:3.1.0'

 

build.gradle(app 에 들어가서

dependencies 에 추가해줌

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

}
그밑에
apply plugin: 'com.google.gms.google-servieces'


FirebaseInstanceIDService.js만들어줌

FirebaseMessagingService.js만들어줌


 

갑자기 궁금한거

 super는 무엇일까?

super와 super()


super 키워드

super 키워드는 부모 클래스로부터 상속받은 필드나 메소드를 자식 클래스에서 참조하는 데 사용하는 참조 변수입니다.

 

인스턴스 변수의 이름과 지역 변수의 이름이 같을 경우 인스턴스 변수 앞에 this 키워드를 사용하여 구분할 수 있었습니다.

이와 마찬가지로 부모 클래스의 멤버와 자식 클래스의 멤버 이름이 같을 경우 super 키워드를 사용하여 구별할 수 있습니다.

 

이렇게 자바에서는 super 참조 변수를 사용하여 부모 클래스의 멤버에 접근할 수 있습니다.

this와 마찬가지로 super 참조 변수를 사용할 수 있는 대상도 인스턴스 메소드뿐이며, 클래스 메소드에서는 사용할 수 없습니다.

 

super() 메소드

this() 메소드가 같은 클래스의 다른 생성자를 호출할 때 사용된다면, super() 메소드는 부모 클래스의 생성자를 호출할 때 사용됩니다.

 

자식 클래스의 인스턴스를 생성하면, 해당 인스턴스에는 자식 클래스의 고유 멤버뿐만 아니라 부모 클래스의 모든 멤버까지도 포함되어 있습니다.

따라서 부모 클래스의 멤버를 초기화하기 위해서는 자식 클래스의 생성자에서 부모 클래스의 생성자까지 호출해야만 합니다.

이러한 부모 클래스의 생성자 호출은 모든 클래스의 부모 클래스인 Object 클래스의 생성자까지 계속 거슬러 올라가며 수행됩니다.

 

따라서 자바 컴파일러는 부모 클래스의 생성자를 명시적으로 호출하지 않는 모든 자식 클래스의 생성자 첫 줄에 자동으로 다음과 같은 명령문을 추가하여, 부모 클래스의 멤버를 초기화할 수 있도록 해줍니다.

this 와 super 의 공통점

두 메소드 모두 생성자의 가장 윗 부분에 위치해야 합니다.

왜냐하면 생성자는 객체가 생성될 때 가장 먼저 호출되는 함수이며

this 와 super 는 생성자 호출에 사용되는 메소드이기 때문입니다.

 

만약 오버로딩 된 생성자를 선택해야 하는 경우 this 또는 super 에 호출하길 원하는 생성자의 인수를 대입하면 됩니다.

this 와 super 의 차이점

this 와 super 의 차이점은 다음과 같습니다.

함수 기능
this ( ) 그 클래스의 다른 생성자를 호출
super ( ) 슈퍼 클래스의 생성자를 호출

 

출처:http://tcpschool.com/java/java_inheritance_super,https://mozi.tistory.com/510

 

[JAVA] this() 와 super() 의 차이점

this 와 super 의 차이점 this 와 super 의 차이점은 다음과 같습니다. 함수 기능 this ( ) 그 클래스의 다른 생성자를 호출 super ( ) 슈퍼 클래스의 생성자를 호출 this 와 super 의 공통점 두 메소드 모두 생.

mozi.tistory.com

 

코딩교육 티씨피스쿨

4차산업혁명, 코딩교육, 소프트웨어교육, 코딩기초, SW코딩, 기초코딩부터 자바 파이썬 등

tcpschool.com


안드로이드의 PendingIntent란?

 

PendingIntent

 

PendingIntent는 Intent를 가지고 있는 클래스로, 기본 목적은 다른 애플리케이션(다른 프로세스)의 권한을 허가하여 가지고 있는 Intent를 마치 본인 앱의 프로세스에서 실행하는 것처럼 사용하게 하는 것입니다.

PendingIntent 용도

  • Notification으로 작업을 수행할 때 인텐트가 실행되도록 합니다. Notification은 안드로이드 시스템의 NotificationManager가 Intent를 실행합니다. 즉 다른 프로세스에서 수행하기 때문에 Notification으로 Intent수행시 PendingIntent의 사용이 필수 입니다.
  • 런처 바탕화면의 위젯으로 Intent 작업을 수행할 때 PendingIntent를 사용합니다.
  • AlarmManager를 통해 지정된 시간에 인텐트가 시작되도록 할때 PendingIntent를 사용합니다.

PendingIntent 생성하는방법

PendingIntent는 컴포넌트의 유형에 따라 생성자 메서드를 호출하는 방법이 다릅니다.

  • Activity를 시작하는 Intent의 경우 PendingIntent.getActivity()
  • Service를 시작하는 Intent의 경우 PendingIntent.getService()
  • BroadcastReceiver를 시작하는 Intent의 경우 PendingIntent.getBroadcast()

호출하려는 컴포넌트에 맞게 PendingIntent객체를 생성해주면 됩니다.

 

출처: https://www.charlezz.com/?p=861 

 

안드로이드의 PendingIntent란? | 찰스의 안드로이드

PendingIntent PendingIntent는 Intent를 가지고 있는 클래스로, 기본 목적은 다른 애플리케이션(다른 프로세스)의 권한을 허가하여 가지고 있는 Intent를 마치 본인 앱의 프로세스에서 실행하는 것처럼 사

www.charlezz.com


메시지를 보내보자

 

 

 

엥 메시지가 오지않는다. 

옛날강의 보다보니까 버전이 맞지않아서 버전을 바꿔줘야한다.

https://firebase.google.com/docs/android/setup?authuser=0 

 

Android 프로젝트에 Firebase 추가

기본 요건 Android 프로젝트가 준비되지 않았다면 빠른 시작 샘플 중 하나를 다운로드하여 Firebase 제품을 사용해 볼 수 있습니다. 다음 옵션 중 하나를 사용하여 Android 앱을 Firebase에 연결할 수 있

firebase.google.com

버전 변경 참고했따.


결과

 

도저히 모르겠다 . FirebaseInstanceIDService를 더이상 쓰지 않아서 함수를 바꿔야할것같은데 좀 더 고민해야할것같다.

배우는입장에서는 아직 애플리케이션 구조도 제대로 모르는데 선뜻 뭘 바꿔야할지 엄두가 나지않는다

개빡친다 갑자기 왜이래;;아까까지만 해도 어플은 돌아갔지 알림만안오는거였는데..

 

이건 참고

https://g-y-e-o-m.tistory.com/112

 

[Android] FCM을 이용한 푸시 보내기

[푸시] FCM 관련 글을 쓴 것 같았는데, 옛날 블로그에만 기록이 되어있었다. 이번에 새로 앱을 하나 만들어야할 게 있어서, 기본 하이브리드앱 + 푸시만 들어간.. 거의 껍데기 앱을 만들었기에 이

g-y-e-o-m.tistory.com


build.gradle(project)

// Top-level build file where you can add configuration options common to all sub-projects/modules.
buildscript {
    repositories {
        google()
        mavenCentral()
    }
    dependencies {
        classpath "com.android.tools.build:gradle:4.2.2"
        classpath 'com.google.gms:google-services:4.3.8'
        // NOTE: Do not place your application dependencies here; they belong
        // in the individual module build.gradle files
    }
}

allprojects {
    repositories {
        google()
        mavenCentral()
        jcenter() // Warning: this repository is going to shut down soon
    }
}

task clean(type: Delete) {
    delete rootProject.buildDir
}

build.gradle(app)

plugins {
    id 'com.android.application'
}

android {
    compileSdkVersion 30
    buildToolsVersion "30.0.3"

    defaultConfig {
        applicationId "com.example.pushtest"
        minSdkVersion 16
        targetSdkVersion 30
        versionCode 1
        versionName "1.0"

        testInstrumentationRunner "androidx.test.runner.AndroidJUnitRunner"
    }

    buildTypes {
        release {
            minifyEnabled false
            proguardFiles getDefaultProguardFile('proguard-android-optimize.txt'), 'proguard-rules.pro'
        }
    }
    compileOptions {
        sourceCompatibility JavaVersion.VERSION_1_8
        targetCompatibility JavaVersion.VERSION_1_8
    }
}

dependencies {

    implementation 'androidx.appcompat:appcompat:1.3.0'
    implementation 'com.google.android.material:material:1.4.0'
    implementation 'androidx.constraintlayout:constraintlayout:2.0.4'
    testImplementation 'junit:junit:4.+'
    androidTestImplementation 'androidx.test.ext:junit:1.1.3'
    androidTestImplementation 'androidx.test.espresso:espresso-core:3.4.0'
    implementation 'com.google.firebase:firebase-messaging:22.0.0'
    implementation 'com.google.firebase:firebase-inappmessaging:20.0.0'
    implementation 'com.google.firebase:firebase-inappmessaging-display:20.0.0'
    implementation 'com.google.firebase:firebase-config:21.0.0'
}

apply plugin: 'com.android.application'
// Add the following line:
apply plugin: 'com.google.gms.google-services'  // Google Services plugin

FirebaseInstanceIDService.js오류발생

package com.example.pushtest;

import android.util.Log;

import com.google.firebase.iid.FirebaseInstanceId;
import com.google.firebase.iid.FirebaseInstanceIdService;

//extends : 상속지정해주는것같음.
public class FirebaseInstanceIDService extends FirebaseInstanceIdService {

    private static final String TAG = "MyFirebaseIIDService";

    //토큰은 핸드폰 기계에서 받아볼수있는 난수의 값, 토큰을 가지고있는 디바이스는 푸쉬알림받을 수 있음.
    @Override
    public void onTokenRefresh() {

        String token = FirebaseInstanceId.getInstance().getToken();
        ///Tag선언해놓으면 로그를 어디서찍더라도 태그를 불러오면 되니까 편리하대
        Log.e(TAG, token);

        sendRegistrationToServer(token);



    }
    //앱서버로 토큰을 보낼때 활용해라
    private void sendRegistrationToServer (String token){

    }

}

FirebaseMessagingService.js

package com.example.pushtest;

import android.app.Notification;
import android.app.NotificationManager;
import android.app.PendingIntent;
import android.content.Context;
import android.content.Intent;
import android.media.RingtoneManager;
import android.util.Log;

import androidx.core.app.NotificationCompat;

import com.google.firebase.messaging.RemoteMessage;

public class FirebaseMessagingService extends com.google.firebase.messaging.FirebaseMessagingService{


    private static final String TAG = "FirebaseMsgService";

    private String msg, title;


    @Override
    public void onMessageReceived(RemoteMessage remoteMessage) {
       Log.e(TAG,"onMessageReceived");

       title = remoteMessage.getNotification().getTitle();
       msg= remoteMessage.getNotification().getBody();


        Intent intent = new Intent(this, MainActivity.class);
        intent.addFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP);
        //실직적인 notification에서 쓰이게될텐데 , intent를 가지고있는 클래스이지만 다른 애플리케이션의 권한허가해서 가지고있는 intent를 본인앱의프로세스처럼사용
        PendingIntent contentIntent = PendingIntent.getActivity(this,0,new Intent(this,MainActivity.class),0);

        //푸시알림이 떴을때 ic_launcher라는 기본아이콘을 띄워주는
        NotificationCompat.Builder mBuilder = new NotificationCompat.Builder(this).setSmallIcon(R.mipmap.ic_launcher)
                .setContentTitle(title)
                .setContentText(msg)
                .setAutoCancel(true)
                //알림소리
                .setSound(RingtoneManager.getDefaultUri(RingtoneManager.TYPE_NOTIFICATION))
                //진동,1초동안 진동이울려라
                .setVibrate(new long[]{1, 1000});

        NotificationManager notificationManager = (NotificationManager) getSystemService(Context.NOTIFICATION_SERVICE);

        notificationManager.notify(0,mBuilder.build());
        //여기까지 해야만 노티피케이션매니져완성

        //pendingintent넣어줌, 서비스형태라서 메니페스트에 선언하러감
       mBuilder.setContentIntent(contentIntent);

    }
}

 

 

 

포기하고 껐는데

수정전에 완료한 앱에다가 알림보냈더니

알림이뜬다...뭐지..짜증

728x90