파이어베이스InstanceIdService가 더 이상 사용되지 않습니다.
파이어베이스 알림 토큰이 새로 고쳐질 때마다 알림 토큰을 가져오는 데 사용되는 이 클래스를 모두 알고 있기를 바랍니다. 이 클래스에서 새로 고쳐진 토큰을 받는 방법은 다음과 같습니다.
@Override
public void onTokenRefresh() {
// Get updated InstanceID token.
String refreshedToken = FirebaseInstanceId.getInstance().getToken();
Log.d(TAG, "Refreshed token: " + refreshedToken);
}
FCM에서 했습니다.FirebaseInstanceIdService
하지만, 그 파이어베이스를 보여주는 것.InstanceIdService가 더 이상 사용되지 않습니다.
이거 아는 사람?토큰이 더 이상 사용되지 않으므로 새로 고침하려면 이 대신 어떤 메서드 또는 클래스를 사용해야 합니까?
중: 사용중:implementation 'com.google.firebase:firebase-messaging:17.1.0'
저는 문서에 동일한 내용이 있는지 확인했습니다. 이것에 대해서는 언급된 것이 없습니다.FCM 설정 문서
갱신하다
이 문제는 수정되었습니다.
구글이 더 이상 사용하지 않는 것처럼FirebaseInstanceService
,
저는 길을 찾기 위해 질문을 했고, Firebase Messaging Service에서 토큰을 얻을 수 있다는 것을 알게 되었습니다.
이전과 마찬가지로 질문 문서가 업데이트되지 않았지만 이제 Google 문서가 업데이트되었으므로 자세한 내용은 이 Google 문서: Firebase Messaging Service를 참조하십시오.
OLD 시작 : Firebase인스턴스 서비스(사용되지 않음)
@Override
public void onTokenRefresh() {
// Get updated InstanceID token.
String refreshedToken = FirebaseInstanceId.getInstance().getToken();
Log.d(TAG, "Refreshed token: " + refreshedToken);
}
새로운 시작: Firebase 메시징 서비스
@Override
public void onNewToken(String s) {
super.onNewToken(s);
Log.d("NEW_TOKEN",s);
}
업데이트 11-12-2020
이제는 또한 더 이상 사용되지 않습니다.
이제 우리는 사용해야 합니다.FirebaseMessaging.getInstance().token
샘플 코드
FirebaseMessaging.getInstance().token.addOnCompleteListener {
if(it.isComplete){
firebaseToken = it.result.toString()
Util.printLog(firebaseToken)
}
}
FROM DOCS :- 이 클래스는 더 이상 사용되지 않습니다.을 지지하는
overriding onNewToken
FirebaseMessagingService
이 서비스가 구현되면 이 서비스를 안전하게 제거할 수 있습니다.
사할필없을 사용할 .FirebaseInstanceIdService
FCM을 할 수 .FirebaseInstanceIdService
이제 우리는 가야 합니다.Token
FirebaseMessagingService
샘플 코드
public class MyFirebaseMessagingService extends FirebaseMessagingService {
@Override
public void onNewToken(String s) {
Log.e("NEW_TOKEN", s);
}
@Override
public void onMessageReceived(RemoteMessage remoteMessage) {
Map<String, String> params = remoteMessage.getData();
JSONObject object = new JSONObject(params);
Log.e("JSON_OBJECT", object.toString());
String NOTIFICATION_CHANNEL_ID = "Nilesh_channel";
long pattern[] = {0, 1000, 500, 1000};
NotificationManager mNotificationManager =
(NotificationManager) getSystemService(Context.NOTIFICATION_SERVICE);
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.O) {
NotificationChannel notificationChannel = new NotificationChannel(NOTIFICATION_CHANNEL_ID, "Your Notifications",
NotificationManager.IMPORTANCE_HIGH);
notificationChannel.setDescription("");
notificationChannel.enableLights(true);
notificationChannel.setLightColor(Color.RED);
notificationChannel.setVibrationPattern(pattern);
notificationChannel.enableVibration(true);
mNotificationManager.createNotificationChannel(notificationChannel);
}
// to diaplay notification in DND Mode
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.O) {
NotificationChannel channel = mNotificationManager.getNotificationChannel(NOTIFICATION_CHANNEL_ID);
channel.canBypassDnd();
}
NotificationCompat.Builder notificationBuilder = new NotificationCompat.Builder(this, NOTIFICATION_CHANNEL_ID);
notificationBuilder.setAutoCancel(true)
.setColor(ContextCompat.getColor(this, R.color.colorAccent))
.setContentTitle(getString(R.string.app_name))
.setContentText(remoteMessage.getNotification().getBody())
.setDefaults(Notification.DEFAULT_ALL)
.setWhen(System.currentTimeMillis())
.setSmallIcon(R.drawable.ic_launcher_background)
.setAutoCancel(true);
mNotificationManager.notify(1000, notificationBuilder.build());
}
}
#편집
매니페스트 파일을 이렇게 등록해야 합니다.
<service
android:name=".MyFirebaseMessagingService"
android:stopWithTask="false">
<intent-filter>
<action android:name="com.google.firebase.MESSAGING_EVENT" />
</intent-filter>
</service>
#활동에서 토큰을 얻는 방법
.getToken();
사용보다 활동에서 토큰을 얻어야 하는 경우에도 사용되지 않습니다.
이제 토큰을 생성하는 데 사용해야 합니다.
getInstanceId ()
다음을 반환합니다.ID
입니다.Firebase
프로젝트.
인스턴스 ID가 아직 존재하지 않으면 인스턴스 ID가 생성되어 정기적으로 Firebase 백엔드로 정보를 보내기 시작합니다.
돌아온다
- 를통 결를확데는사수태있크를 통해 하는 데 할 수 .
InstanceIdResult
그것을 보유하는.ID
그리고.token
.
샘플 코드
FirebaseInstanceId.getInstance().getInstanceId().addOnSuccessListener( MyActivity.this, new OnSuccessListener<InstanceIdResult>() {
@Override
public void onSuccess(InstanceIdResult instanceIdResult) {
String newToken = instanceIdResult.getToken();
Log.e("newToken",newToken);
}
});
##편집 2
코틀린의 작업 코드는 다음과 같습니다.
class MyFirebaseMessagingService : FirebaseMessagingService() {
override fun onNewToken(p0: String?) {
}
override fun onMessageReceived(remoteMessage: RemoteMessage?) {
val notificationManager = getSystemService(Context.NOTIFICATION_SERVICE) as NotificationManager
val NOTIFICATION_CHANNEL_ID = "Nilesh_channel"
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.O) {
val notificationChannel = NotificationChannel(NOTIFICATION_CHANNEL_ID, "Your Notifications", NotificationManager.IMPORTANCE_HIGH)
notificationChannel.description = "Description"
notificationChannel.enableLights(true)
notificationChannel.lightColor = Color.RED
notificationChannel.vibrationPattern = longArrayOf(0, 1000, 500, 1000)
notificationChannel.enableVibration(true)
notificationManager.createNotificationChannel(notificationChannel)
}
// to diaplay notification in DND Mode
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.O) {
val channel = notificationManager.getNotificationChannel(NOTIFICATION_CHANNEL_ID)
channel.canBypassDnd()
}
val notificationBuilder = NotificationCompat.Builder(this, NOTIFICATION_CHANNEL_ID)
notificationBuilder.setAutoCancel(true)
.setColor(ContextCompat.getColor(this, R.color.colorAccent))
.setContentTitle(getString(R.string.app_name))
.setContentText(remoteMessage!!.getNotification()!!.getBody())
.setDefaults(Notification.DEFAULT_ALL)
.setWhen(System.currentTimeMillis())
.setSmallIcon(R.drawable.ic_launcher_background)
.setAutoCancel(true)
notificationManager.notify(1000, notificationBuilder.build())
}
}
여기서 불을 뿜습니다.
다음에 대한 참조 설명서를 확인하십시오.
이 클래스는 더 이상 사용되지 않습니다.
우선하는 것에 찬성합니다.
onNewToken
에FirebaseMessagingService
이 서비스가 구현되면 이 서비스를 안전하게 제거할 수 있습니다.
이상하게도 JavaDoc은 다음과 같습니다.FirebaseMessagingService
에 대해 언급하지 않음onNewToken
아직 방법이 없습니다.업데이트된 문서 중 일부가 아직 게시되지 않은 것 같습니다.참조 문서의 업데이트를 게시하고 가이드의 샘플도 업데이트하기 위해 내부 문제를 제출했습니다.
그 동안 이전/사용되지 않는 통화와 새 통화가 모두 작동해야 합니다.둘 중 하나에 문제가 있으면 코드를 올리면 제가 확인해 보겠습니다.
이 메서드를 호출하여 Firebase 메시징 토큰을 가져옵니다.
public void getFirebaseMessagingToken ( ) {
FirebaseMessaging.getInstance ().getToken ()
.addOnCompleteListener ( task -> {
if (!task.isSuccessful ()) {
//Could not get FirebaseMessagingToken
return;
}
if (null != task.getResult ()) {
//Got FirebaseMessagingToken
String firebaseMessagingToken = Objects.requireNonNull ( task.getResult () );
//Use firebaseMessagingToken further
}
} );
}
build.gradle 파일에 이 종속성을 추가한 후 위 코드가 잘 작동합니다.
implementation 'com.google.firebase:firebase-messaging:21.1.0'
참고: 상기 종속성에 대한 절사 해결을 위해 수행한 코드 수정입니다. (2021년 5월 9일 기준 작업 코드)
그리고 이것은:
FirebaseInstanceId.getInstance().getInstanceId().getResult().getToken()
사용되지 않는 솔루션으로 가정합니다.
FirebaseInstanceId.getInstance().getToken()
편집
FirebaseInstanceId.getInstance().getInstanceId().getResult().getToken()
작업이 아직 완료되지 않은 경우 예외를 생성할 수 있으므로, 방법 스위치 Nilesh Rathod가 설명했습니다(포함)..addOnSuccessListener
)이 올바른 방법입니다.
코틀린:
FirebaseInstanceId.getInstance().instanceId.addOnSuccessListener(this) { instanceIdResult ->
val newToken = instanceIdResult.token
Log.e("newToken", newToken)
}
FirebaseinstanceIdService
사용되지 않습니다.그래서 "Firebase Messaging Service"를 사용해야 합니다.
이미지를 검색하십시오.
public class MyFirebaseMessagingService extends FirebaseMessagingService {
@Override
public void onNewToken(String s) {
super.onNewToken(s);
Log.e("NEW_TOKEN",s);
}
@Override
public void onMessageReceived(RemoteMessage remoteMessage) {
super.onMessageReceived(remoteMessage);
}
}
Kotlin은 다른 답변에 표시된 것보다 훨씬 더 간단한 코드를 허용합니다.
새로 고쳐질 때마다 새 토큰을 가져오는 방법:
class MyFirebaseMessagingService: FirebaseMessagingService() {
override fun onNewToken(token: String?) {
Log.d("FMS_TOKEN", token)
}
...
}
런타임에 아무 곳에서나 토큰을 가져오려면:
FirebaseInstanceId.getInstance().instanceId.addOnSuccessListener {
Log.d("FMS_TOKEN", it.token)
}
In KOTLIN:- 토큰을 DB 또는 공유 기본 설정에 저장하려면 Firebase Messaging Service의 NewToken에서 재정의합니다.
override fun onNewToken(token: String) {
super.onNewToken(token)
}
런타임에 토큰 가져오기, 사용
FirebaseInstanceId.getInstance().instanceId
.addOnSuccessListener(this@SplashActivity) { instanceIdResult ->
val mToken = instanceIdResult.token
println("printing fcm token: $mToken")
}
FCM 구현 클래스:
public class MyFirebaseMessagingService extends FirebaseMessagingService {
@Override
public void onMessageReceived(RemoteMessage remoteMessage) {
Map<String, String> data = remoteMessage.getData();
if(data != null) {
// Do something with Token
}
}
}
// FirebaseInstanceId.getInstance().getToken();
@Override
public void onNewToken(String token) {
super.onNewToken(token);
if (!token.isEmpty()) {
Log.e("NEW_TOKEN",token);
}
}
}
활동 또는 APP에서 초기화를 호출합니다.
FirebaseInstanceId.getInstance().getInstanceId().addOnSuccessListener(
instanceIdResult -> {
String newToken = instanceIdResult.getToken();
}).addOnFailureListener(new OnFailureListener() {
@Override
public void onFailure(@NonNull Exception e) {
Log.i("FireBaseToken", "onFailure : " + e.toString());
}
});
AndroidManifest.xml:
<service android:name="ir.hamplus.MyFirebaseMessagingService"
android:stopWithTask="false">
<intent-filter>
<action android:name="com.google.firebase.MESSAGING_EVENT" />
</intent-filter>
</service>
**"INSTANCE_"를 추가한 경우ID_EVENT"를 사용하지 않도록 설정하는 것을 잊지 마십시오.
사용해야 합니다.FirebaseMessagingService()
대신에FirebaseInstanceIdService
그리고 여기 C#/Xamarin에 대한 솔루션이 있습니다.Android:
var token = await FirebaseInstallations.Instance.GetToken(forceRefresh: false).AsAsync<InstallationTokenResult>();
getInstance().getInstanceId()
또한 현재는 더 이상 사용되지 않습니다.FirebaseMessaging
지금 사용 중입니다.
FirebaseMessaging.getInstance().token.addOnCompleteListener { task ->
if (task.isSuccessful) {
val token = task.result
} else {
Timber.e(task.exception)
}
}
첫번째 가져오기import com.google.firebase.messaging.FirebaseMessaging;
그렇다면 간단하게 사용하세요.FirebaseMessaging.getInstance().getToken().getResult();
대신에FirebaseInstanceId.getInstance().getToken().getresult()
바로 그겁니다.
서비스를 이용하실 수 있습니다.
<service android:name=".utils.fcm.MyFirebaseMessagingService">
<intent-filter>
<action android:name="com.google.firebase.MESSAGING_EVENT" />
</intent-filter>
</service>
public class MyFirebaseMessagingService extends FirebaseMessagingService{
@Override
public void onNewToken(String s) {
super.onNewToken(s);
Log.e("NEW_TOKEN = = == = = =",s);
}
}
활동에서 사용하려는 경우
FirebaseMessaging.getInstance ().getToken ().addOnCompleteListener ( task -> {
Log.e("spalsh",task.getResult());
});
빌드에 이 파일을 추가합니다.구현 'com.google.파이어베이스:파이어베이스-디젤:20.2.
대신 Firebase Messaging 사용
FirebaseMessaging.getInstance().getToken()
.addOnCompleteListener(new OnCompleteListener<String>() {
@Override
public void onComplete(@NonNull Task<String> task) {
if (!task.isSuccessful()) {
Log.w(TAG, "Fetching FCM registration token failed", task.getException());
return;
}
// Get new FCM registration token
String token = task.getResult();
// Log and toast
String msg = getString(R.string.msg_token_fmt, token);
Log.d(TAG, msg);
Toast.makeText(MainActivity.this, msg, Toast.LENGTH_SHORT).show();
}
});
코틀린의 경우 다음을 사용합니다.
val fcmtoken = FirebaseMessaging.getInstance().token.await()
확장 기능의 경우
public suspend fun <T> Task<T>.await(): T {
// fast path
if (isComplete) {
val e = exception
return if (e == null) {
if (isCanceled) {
throw CancellationException("Task $this was cancelled normally.")
} else {
@Suppress("UNCHECKED_CAST")
result as T
}
} else {
throw e
}
}
return suspendCancellableCoroutine { cont ->
addOnCompleteListener {
val e = exception
if (e == null) {
@Suppress("UNCHECKED_CAST")
if (isCanceled) cont.cancel() else cont.resume(result as T)
} else {
cont.resumeWithException(e)
}
}
}
}
당신은 이 방법을 당신의 활동에 사용할 수 있습니다, 이것은 저에게 효과가 있었습니다.
private void registerInBackground() {
FirebaseApp.initializeApp(SplashActivity.this);
FirebaseMessaging.getInstance().getToken().addOnCompleteListener(new OnCompleteListener<String>() {
@Override
public void onComplete(@NonNull Task<String> task) {
String token = task.getResult();
}
});
}
부터com.google.firebase:firebase-bom:28.4.2
방법은 다음과 같습니다.
FirebaseMessaging.getInstance().token.result
그러나 이 작업은 작업이므로 이러한 방식으로 값을 반환하지 않습니다.당신은 콜백을 사용하여 그것을 기다려야 합니다.
이 문제를 해결하는 좋은 방법은 다음과 같습니다.
@WorkerThread
fun <TResult> Task<TResult>.awaitForResult(): Task<TResult> {
val countDownLatch = CountDownLatch(1)
this.addOnCompleteListener {
countDownLatch.countDown()
}
countDownLatch.await()
return this
}
@WorkerThread
fun <TResult> Task<TResult>.awaitForResultOrNull(): Task<TResult>? {
val task = awaitForResult()
return if (task.isSuccessful)
return task else null
}
사용 예:
val regId : String? = FirebaseMessaging.getInstance().token.awaitForResultOrNull()?.result
새로운 방법
FirebaseMessaging.getInstance().getToken().addOnCompleteListener(task -> Log.e(TAG, "Token: "+task.getResult()));
언급URL : https://stackoverflow.com/questions/51123197/firebaseinstanceidservice-is-deprecated
'programing' 카테고리의 다른 글
Windows에서 Cmake (0) | 2023.07.23 |
---|---|
여러 레코드 INSERT 문에 사용되는 MySQL LAST_INSERT_ID() (0) | 2023.07.23 |
실행 시간 제한에 절전 시간이 포함됩니까? (0) | 2023.07.23 |
phpexcel을 사용하여 셀에서 새 줄을 만드는 방법 (0) | 2023.07.23 |
트리거에서 DELMITER //의 역할은 무엇입니까? (0) | 2023.07.23 |