FCM令牌问题在一些Android设备 [英] FCM Token Issue in some android device

查看:417
本文介绍了FCM令牌问题在一些Android设备的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

FCM专家请帮助我,我必须使用FCM整合android的通知,我试着给出了由Firebase给出的演示,我尝试了很多逻辑,但它给了一些设备的第一个令牌:
我用三个装置,Moto E(第二代)(安卓版本5.1.1),三星GT-S7562(AV 4.1.2)和Karbon Titanium(AV 4.2.2),我只收到Karbon Titanium的令牌,知道为什么我没有收到Moto E(2 Gen)和三星GT-S7562的令牌,但从karbon Titanium设备收到令牌:

这是我试过的代码:

Logcat Moto E2:

  07-07 15:58 :08.776 24152-24152 /? I / art:延迟启用-Xcheck:jni 
07-07 15:58:08.802 24152-24162 /? E / art:发送回复调试器失败:损坏的管道
07-07 15:58:08.802 24152-24162 /? I / art:调试器不再有效
07-07 15:58:08.848 24152-24152 /? D / FirebaseApp:com.google.firebase.auth.FirebaseAuth未链接。跳过初始化。
07-07 15:58:08.859 24152-24152 /? D / FirebaseApp:com.google.firebase.crash.FirebaseCrash未链接。跳过初始化。
07-07 15:58:08.872 24152-24152 /? I / FA:应用程序测量正在启动,版本:9256
07-07 15:58:08.872 24152-24152 /? I / FA:启用调试日志记录运行:adb shell setprop log.tag.FA VERBOSE
07-07 15:58:09.027 24152-24152 /? I / FirebaseInitProvider:FirebaseApp初始化成功
07-07 15:58:09.196 24152-24152 /? W /艺术:在Android 4.1之前,方法android.graphics.PorterDuffColorFilter android.support.graphics.drawable.VectorDrawableCompat.updateTintFilter(android.graphics.PorterDuffColorFilter,android.content.res.ColorStateList,android.graphics.PorterDuff $模式)将有不正确地重写了android.graphics.drawable.Drawable中的package-private方法
07-07 15:58:09.361 24152-24192 /? D / OpenGLRenderer:使用EGL_SWAP_BEHAVIOR_PRESERVED:true
07-07 15:58:09.378 24152-24152 /? D /地图集:验证地图...
07-07 15:58:09.564 24152-24192 /? I / Adreno-EGL:< qeglDrvAPI_eglInitialize:379>:EGL 1.4 QUALCOMM构建:(Ibddc658e36)
OpenGL ES Shader编译器版本:E031.25.03.04
构建日期:08/10/15 Mon
本地分支:工作区
远程分支:
本地修补程序:
重建分支:
07-07 15:58:09.567 24152-24192 /? I / OpenGLRenderer:初始化的EGL,版本1.4
07-07 15:58:09.609 24152-24192 /? D / OpenGLRenderer:启用调试模式0
07-07 15:58:12.860 24152-24242 / com.shubhank.fcm_tutorial W / InstanceID / Rpc:Found 10016
07-07 15:58:13.049 24152 -24242 / com.shubhank.fcm_tutorial D / FirebaseInstanceId:后台同步失败:PHONE_REGISTRATION_ERROR,重试时间为10s
07-07 15:58:19.256 24152-24178 / com.shubhank.fcm_tutorial I / FA:标记管理器不是发现,因此不会被使用
07-07 15:58:23.194 24152-24448 / com.shubhank.fcm_tutorial D / FirebaseInstanceId:后台同步失败:PHONE_REGISTRATION_ERROR,20秒后重试




Karbon Mobile的Logcat:

-07 16:38:03.964 3939-3939 / com.shubhank.fcm_tutorial I / FA:启用调试日志记录运行:adb shell setprop log.tag.FA VERBOSE
07-07 16:38:04.004 3939-3939 /com.shubhank.fcm_tutorial I / FirebaseInitProvider:FirebaseApp初始化成功
07-07 16:38:04.017 3939-3939 / com.shubhank.fcm_tutorial W / dalvikvm:VFY:找不到引用签名的类e(Landroid / view / SearchEvent;)
07-07 16:38:04.017 3939-3939 / com.shubhank.fcm_tutorial I / dalvikvm:找不到方法android.view.Window $ Callback.onSearchRequested,引用自方法android.support.v7.view.WindowCallbackWrapper.onSearchRequested
07-07 16:38:04.017 3939-3939 / com.shubhank.fcm_tutorial W / dalvikvm:VFY:无法解析接口方法19193:Landroid / view / Window $ Callback; .onSearchRequested(Landroid / view / SearchEvent;)Z
07-07 16:38:04.017 3939-3939 / com.shubhank.fcm_tutorial I / dalvikvm:找不到方法android.view.Window $ Callback.onWindowStartingActionMode,从方法android.support.v7.view.WindowCallbackWrapper.onWindowStartingActionMode引用
07-07 16:38:04.017 3939-3939 / com.shubhank.fcm_tutorial W / dalvikvm:VFY:无法解析接口方法19197:Landroid / view / Window $回调; .onWindowStartingActionMode(Landroid / view / ActionMode $回调; I)Landroid / view / ActionMode;
07-07 16:38:04.049 3939-3939 / com.shubhank.fcm_tutorial I / dalvikvm:无法找到方法android.content.res.TypedArray.getChangingConfigurations,从方法android.support.v7.widget引用。 TintTypedArray.getChangingConfigurations
07-07 16:38:04.049 3939-3939 / com.shubhank.fcm_tutorial W / dalvikvm:VFY:无法解析虚拟方法577:Landroid / content / res / TypedArray; .getChangingConfigurations()I
07-07 16:38:04.050 3939-3939 / com.shubhank.fcm_tutorial I / dalvikvm:无法找到方法android.content.res.TypedArray.getType,从方法android.support.v7.widget引用。 TintTypedArray.getType
07-07 16:38:04.050 3939-3939 / com.shubhank.fcm_tutorial W / dalvikvm:VFY:无法解析虚拟方法599:Landroid / content / res / TypedArray; .getType(I) I
07-07 16:38:04.092 3939-3939 / com.shubhank.fcm_tutorial I / dalvikvm:无法找到方法android.content.res.Resources.getDrawable,从方法android.support.v7.widget引用.ResourcesWrapper.getDrawabl e-b $ b 07-07 16:38:04.092 3939-3939 / com.shubhank.fcm_tutorial W / dalvikvm:VFY:无法解析虚拟方法540:Landroid / content / res / Resources; .getDrawable(ILandroid / content / RES /资源$主题;)Landroid /图形/绘制/可绘制;
07-07 16:38:04.092 3939-3939 / com.shubhank.fcm_tutorial I / dalvikvm:无法找到方法android.content.res.Resources.getDrawableForDensity,从方法android.support.v7.widget引用。 ResourcesWrapper.getDrawableForDensity
07-07 16:38:04.092 3939-3939 / com.shubhank.fcm_tutorial W / dalvikvm:VFY:无法解析虚拟方法542:Landroid / content / res / Resources; .getDrawableForDensity(IILandroid /内容/ RES /资源$主题;)Landroid /图形/绘制/可绘制;
07-07 16:38:04.096 3939-3939 / com.shubhank.fcm_tutorial W /通知:faQNkJ65F5c:APA91bFHH5rVOhIlX5k7Pxo-sbZPwZplWqBGLVOjlG8G4NwoMqaKZQRYWMMjliYXb0gokiuJPBYpWY0G7L-FEbgAv7LfKcuR0j7Sr6ATxb1j2UR7A
07-07 16:38:04.148 3939-3939 / COM。 I / MaliEGL:[Mali] window_type = 1,is_framebuffer = 0,errnum = 0
07-07 16:38:04.148 3939-3939 / com.shubhank.fcm_tutorial I / MaliEGL: - > num_buffers = 4,surface_> num_frames = 3,win_min_undequeued = 1
07-07 16:38:04.148 3939-3939 / com.shubhank.fcm_tutorial I / MaliEGL:[Mali] max_allowed_dequeued_buffers = 3
07-07 16:38:04.159 3939-3939 / com.shubhank.fcm_tutorial I / [MALI] [Gralloc]:dlopen libsec_mem.so失败


MainActivity:

  public class MainActivity extends AppCompatActivity {
Tracker mTracker;

@Override
protected void onCreate(Bundle savedInstanceState){
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);

字符串标记= FirebaseInstanceId.getInstance()。getToken();
if(token!= null){
Log.w(notification,token);
Toast.makeText(MainActivity.this,+ token,Toast.LENGTH_SHORT).show();
}

}


}

app gradle:

  apply plugin:'com.android.application'
android {
compileSdkVersion 23
buildToolsVersion23.0.3

defaultConfig {
applicationIdcom.shubhank.fcm_tutorial
minSdkVersion 15
targetSdkVersion 23
versionCode 1
versionName1.0
}
buildTypes {
release {
minifyEnabled true
proguardFiles getDefaultProguardFile('proguard-android.txt' ),'proguard-rules.pro'
}
}
}

依赖项{
编译fileTree(dir:'libs',include:[ '* .jar'])
testCompile'junit:junit:4.12'
compile'c​​om.google.android.gms:play-services-analytics:9.2.0'

编译'com.android.support:appcompat-v7:23.3.0'
编译'com.google.firebase:firebase-core:9.0.1'
编译'com.google.firebase:firebase- messaging:9.0.1'
compile'c​​om.android.support:design:23.3.0'
}


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

顶级gradle:











$ {
classpath {
classpath 'com.android.tools.build:gradle:2.1.2'
classpath'com.google.gms:google-services:3.0.0'

//注意:不要放置你的应用程序依赖关系它们属于单个模块build.gradle文件中的
//
}
}

allprojects {
repositories {
jcenter()
$ mavenLocal



$ b令牌服务:

  public class TokenService extends FirebaseInstanceIdService {

@Override $ b $ public void onTokenRefresh(){
//获取更新的InstanceID令牌。
String refreshedToken = FirebaseInstanceId.getInstance()。getToken();
Log.w(notification,refreshedToken);
sendRegistrationToServer(refreshedToken);
}

private void sendRegistrationToServer(String token){
}
}

FCMMessageReceiverService:

  public class FCMMessageReceiverService extends FirebaseMessagingService {

@Override
public void onMessageReceived(RemoteMessage remoteMessage){
Log.w(fcm,received notification);
sendNotification(remoteMessage.getNotification()。getTitle());


private void sendNotification(String messageBody){
Intent intent = new Intent(this,MainActivity.class);
intent.addFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP);
PendingIntent pendingIntent = PendingIntent.getActivity(this,0 / * Request code * /,intent,
PendingIntent.FLAG_ONE_SHOT);

Uri defaultSoundUri = RingtoneManager.getDefaultUri(RingtoneManager.TYPE_NOTIFICATION);
NotificationCompat.Builder notificationBuilder = new NotificationCompat.Builder(this)
.setSmallIcon(R.mipmap.ic_launcher)
.setContentTitle(messageBody)
.setAutoCancel(false)
.setSound(defaultSoundUri);

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

notificationManager.notify(1,notificationBuilder.build());




清单文件

 <?xml version =1.0encoding =utf-8?> 
< manifest xmlns:android =http://schemas.android.com/apk/res/android
package =com.shubhank.fcm_tutorial>
< uses-permission android:name =android.permission.INTERNET/>
<使用权限android:name =android.permission.ACCESS_NETWORK_STATE/>
< uses-permission android:name =android.permission.GET_ACCOUNTS/>

应用程序$ b $ android:allowBackup =true
android:icon =@ mipmap / ic_launcher
android:label =@ string / app_name
android:supportsRtl =true
android:launchMode =standard
android:theme =@ style / AppTheme>
< activity android:name =。MainActivity>
< intent-filter>

< category android:name =android.intent.category.LAUNCHER/>
< / intent-filter>
< / activity>

< service android:name =。TokenService
android:exported =true>
< intent-filter>
< action android:name =com.google.firebase.INSTANCE_ID_EVENT/>
< / intent-filter>
< / service>
< service android:name =。FCMMessageReceiverService
android:exported =true>
< intent-filter>
< action android:name =com.google.firebase.MESSAGING_EVENT/>
< / intent-filter>
< / service>
< / activity>
< meta-data
android:name =com.google.android.gms.version
android:value =@ integer / google_play_services_version/>
< / application>

< / manifest>


解决方案

b

在gradle文件中

  compile'c​​om.google.firebase:firebase-messaging:9.0.0 '

  public class FirebaseMessagingServices extends FirebaseMessagingService {

private static final String TAG =FirebaseMessaging;
private NotificationManager mNotificationManager;
public static final int NOTIFICATION_ID = 1;

$ b @Override
public void onMessageReceived(RemoteMessage remoteMessage){
// TODO(developer):在这里处理FCM消息。
//在这里没有得到消息
Log.v(TAG,From:+ remoteMessage.getFrom());

//检查消息是否包含数据有效载荷。如果(remoteMessage.getData()。size()> 0){
Log.v(TAG,Message data payload:1+ remoteMessage.getData());
// sendNotification(remoteMessage.getData()+); (TAG,Message data payload:2+ remoteMessage.getData()。get(Config.MESSAGE_KEY).toString());
Log.v
sendNotification(remoteMessage.getData()。get(Config.MESSAGE_KEY)+);
}

//检查消息是否包含通知负载。
if(remoteMessage.getNotification()!= null){
Log.v(TAG,Message Notification Body:+ remoteMessage.getNotification()。getBody());

SharedPreferences首选项= getSharedPreferences(Utils.SIGNUP_PREF,MODE_PRIVATE);
布尔值notification = preferences.getBoolean(Utils.notification,true);

sendNotification(remoteMessage.getNotification()。getBody());

$ b $ private void sendNotification(String msg){
MediaPlayer mp = MediaPlayer.create(getApplicationContext(),R.raw.notification1);
mp.start();

mNotificationManager =(NotificationManager)this
.getSystemService(Context.NOTIFICATION_SERVICE);
$ b $ PendingIntent contentIntent = PendingIntent.getActivity(this,0,
new Intent(this,MainActivity.class),0);

NotificationCompat.Builder mBuilder =(NotificationCompat.Builder)new NotificationCompat.Builder(
this).setSmallIcon(R.drawable.penless_small)
.setContentTitle(Penless)
.setStyle(new NotificationCompat.BigTextStyle()。bigText(msg))
.setContentText(msg);
mBuilder.setContentIntent(contentIntent);
mNotificationManager.notify(NOTIFICATION_ID,mBuilder.build());}}


FCM Expert Please Help me out,I have to integrate notification for the android using FCM, I am trying the demo given by Firebase, I tried many logic but it's giving first token for the some devices: I used three device, Moto E (2nd Gen)(android version 5.1.1), Samsung GT-S7562(A.V 4.1.2) and Karbon Titanium (A.V 4.2.2), I am receiving the token only for Karbon Titanium ,don't know why I am not receiving the token for Moto E(2 Gen)and Samsung GT-S7562 but receiving the token from karbon Titanium device :

Here is the code I tried :

Logcat Moto E2 :

07-07 15:58:08.776 24152-24152/? I/art: Late-enabling -Xcheck:jni
07-07 15:58:08.802 24152-24162/? E/art: Failed sending reply to debugger: Broken pipe
07-07 15:58:08.802 24152-24162/? I/art: Debugger is no longer active
07-07 15:58:08.848 24152-24152/? D/FirebaseApp: com.google.firebase.auth.FirebaseAuth is not linked. Skipping initialization.
07-07 15:58:08.859 24152-24152/? D/FirebaseApp: com.google.firebase.crash.FirebaseCrash is not linked. Skipping initialization.
07-07 15:58:08.872 24152-24152/? I/FA: App measurement is starting up, version: 9256
07-07 15:58:08.872 24152-24152/? I/FA: To enable debug logging run: adb shell setprop log.tag.FA VERBOSE
07-07 15:58:09.027 24152-24152/? I/FirebaseInitProvider: FirebaseApp initialization successful
07-07 15:58:09.196 24152-24152/? W/art: Before Android 4.1, method android.graphics.PorterDuffColorFilter android.support.graphics.drawable.VectorDrawableCompat.updateTintFilter(android.graphics.PorterDuffColorFilter, android.content.res.ColorStateList, android.graphics.PorterDuff$Mode) would have incorrectly overridden the package-private method in android.graphics.drawable.Drawable
07-07 15:58:09.361 24152-24192/? D/OpenGLRenderer: Use EGL_SWAP_BEHAVIOR_PRESERVED: true
07-07 15:58:09.378 24152-24152/? D/Atlas: Validating map...
07-07 15:58:09.564 24152-24192/? I/Adreno-EGL: <qeglDrvAPI_eglInitialize:379>: EGL 1.4 QUALCOMM build:  (Ibddc658e36)
                                               OpenGL ES Shader Compiler Version: E031.25.03.04
                                               Build Date: 08/10/15 Mon
                                               Local Branch: workspace
                                               Remote Branch: 
                                               Local Patches: 
                                               Reconstruct Branch: 
07-07 15:58:09.567 24152-24192/? I/OpenGLRenderer: Initialized EGL, version 1.4
07-07 15:58:09.609 24152-24192/? D/OpenGLRenderer: Enabling debug mode 0
07-07 15:58:12.860 24152-24242/com.shubhank.fcm_tutorial W/InstanceID/Rpc: Found 10016
07-07 15:58:13.049 24152-24242/com.shubhank.fcm_tutorial D/FirebaseInstanceId: background sync failed: PHONE_REGISTRATION_ERROR, retry in 10s
07-07 15:58:19.256 24152-24178/com.shubhank.fcm_tutorial I/FA: Tag Manager is not found and thus will not be used
07-07 15:58:23.194 24152-24448/com.shubhank.fcm_tutorial D/FirebaseInstanceId: background sync failed: PHONE_REGISTRATION_ERROR, retry in 20s

Logcat of Karbon Mobile:

07-07 16:38:03.964 3939-3939/com.shubhank.fcm_tutorial I/FA: To enable debug logging run: adb shell setprop log.tag.FA VERBOSE
07-07 16:38:04.004 3939-3939/com.shubhank.fcm_tutorial I/FirebaseInitProvider: FirebaseApp initialization successful
07-07 16:38:04.017 3939-3939/com.shubhank.fcm_tutorial W/dalvikvm: VFY: unable to find class referenced in signature (Landroid/view/SearchEvent;)
07-07 16:38:04.017 3939-3939/com.shubhank.fcm_tutorial I/dalvikvm: Could not find method android.view.Window$Callback.onSearchRequested, referenced from method android.support.v7.view.WindowCallbackWrapper.onSearchRequested
07-07 16:38:04.017 3939-3939/com.shubhank.fcm_tutorial W/dalvikvm: VFY: unable to resolve interface method 19193: Landroid/view/Window$Callback;.onSearchRequested (Landroid/view/SearchEvent;)Z
07-07 16:38:04.017 3939-3939/com.shubhank.fcm_tutorial I/dalvikvm: Could not find method android.view.Window$Callback.onWindowStartingActionMode, referenced from method android.support.v7.view.WindowCallbackWrapper.onWindowStartingActionMode
07-07 16:38:04.017 3939-3939/com.shubhank.fcm_tutorial W/dalvikvm: VFY: unable to resolve interface method 19197: Landroid/view/Window$Callback;.onWindowStartingActionMode (Landroid/view/ActionMode$Callback;I)Landroid/view/ActionMode;
07-07 16:38:04.049 3939-3939/com.shubhank.fcm_tutorial I/dalvikvm: Could not find method android.content.res.TypedArray.getChangingConfigurations, referenced from method android.support.v7.widget.TintTypedArray.getChangingConfigurations
07-07 16:38:04.049 3939-3939/com.shubhank.fcm_tutorial W/dalvikvm: VFY: unable to resolve virtual method 577: Landroid/content/res/TypedArray;.getChangingConfigurations ()I
07-07 16:38:04.050 3939-3939/com.shubhank.fcm_tutorial I/dalvikvm: Could not find method android.content.res.TypedArray.getType, referenced from method android.support.v7.widget.TintTypedArray.getType
07-07 16:38:04.050 3939-3939/com.shubhank.fcm_tutorial W/dalvikvm: VFY: unable to resolve virtual method 599: Landroid/content/res/TypedArray;.getType (I)I
07-07 16:38:04.092 3939-3939/com.shubhank.fcm_tutorial I/dalvikvm: Could not find method android.content.res.Resources.getDrawable, referenced from method android.support.v7.widget.ResourcesWrapper.getDrawable
07-07 16:38:04.092 3939-3939/com.shubhank.fcm_tutorial W/dalvikvm: VFY: unable to resolve virtual method 540: Landroid/content/res/Resources;.getDrawable (ILandroid/content/res/Resources$Theme;)Landroid/graphics/drawable/Drawable;
07-07 16:38:04.092 3939-3939/com.shubhank.fcm_tutorial I/dalvikvm: Could not find method android.content.res.Resources.getDrawableForDensity, referenced from method android.support.v7.widget.ResourcesWrapper.getDrawableForDensity
07-07 16:38:04.092 3939-3939/com.shubhank.fcm_tutorial W/dalvikvm: VFY: unable to resolve virtual method 542: Landroid/content/res/Resources;.getDrawableForDensity (IILandroid/content/res/Resources$Theme;)Landroid/graphics/drawable/Drawable;
07-07 16:38:04.096 3939-3939/com.shubhank.fcm_tutorial W/notification: faQNkJ65F5c:APA91bFHH5rVOhIlX5k7Pxo-sbZPwZplWqBGLVOjlG8G4NwoMqaKZQRYWMMjliYXb0gokiuJPBYpWY0G7L-FEbgAv7LfKcuR0j7Sr6ATxb1j2UR7A
07-07 16:38:04.148 3939-3939/com.shubhank.fcm_tutorial I/MaliEGL: [Mali]window_type=1, is_framebuffer=0, errnum = 0
07-07 16:38:04.148 3939-3939/com.shubhank.fcm_tutorial I/MaliEGL: [Mali]surface->num_buffers=4, surface->num_frames=3, win_min_undequeued=1
07-07 16:38:04.148 3939-3939/com.shubhank.fcm_tutorial I/MaliEGL: [Mali]max_allowed_dequeued_buffers=3
07-07 16:38:04.159 3939-3939/com.shubhank.fcm_tutorial I/[MALI][Gralloc]: dlopen libsec_mem.so fail

MainActivity:

    public class MainActivity extends AppCompatActivity {
    Tracker mTracker;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);

        String token = FirebaseInstanceId.getInstance().getToken();
        if (token != null) {
            Log.w("notification", token);
            Toast.makeText(MainActivity.this,""+token,Toast.LENGTH_SHORT).show();
        }

    }


}

app gradle :

apply plugin: 'com.android.application'
   android {
        compileSdkVersion 23
        buildToolsVersion "23.0.3"

        defaultConfig {
            applicationId "com.shubhank.fcm_tutorial"
            minSdkVersion 15
            targetSdkVersion 23
            versionCode 1
            versionName "1.0"
        }
        buildTypes {
            release {
                minifyEnabled true
                proguardFiles getDefaultProguardFile('proguard-android.txt'), 'proguard-rules.pro'
            }
        }
    }

    dependencies {
        compile fileTree(dir: 'libs', include: ['*.jar'])
        testCompile 'junit:junit:4.12'
        compile 'com.google.android.gms:play-services-analytics:9.2.0'

        compile 'com.android.support:appcompat-v7:23.3.0'
        compile 'com.google.firebase:firebase-core:9.0.1'
        compile 'com.google.firebase:firebase-messaging:9.0.1'
        compile 'com.android.support:design:23.3.0'
    }


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

top level gradle :

buildscript {
    repositories {
        jcenter()
        mavenLocal()
    }
    dependencies {
        classpath 'com.android.tools.build:gradle:2.1.2'
        classpath 'com.google.gms:google-services:3.0.0'

        // NOTE: Do not place your application dependencies here; they belong
        // in the individual module build.gradle files
    }
}

allprojects {
    repositories {
        jcenter()
        mavenLocal()
    }
}

TokenService:

public class TokenService extends FirebaseInstanceIdService {

@Override
public void onTokenRefresh() {
    // Get updated InstanceID token.
    String refreshedToken = FirebaseInstanceId.getInstance().getToken();
    Log.w("notification", refreshedToken);
    sendRegistrationToServer(refreshedToken);
}

private void sendRegistrationToServer(String token) {
}
}

FCMMessageReceiverService:

public class FCMMessageReceiverService extends FirebaseMessagingService {

@Override
public void onMessageReceived(RemoteMessage remoteMessage) {
    Log.w("fcm", "received notification");
    sendNotification(remoteMessage.getNotification().getTitle());
}

private void sendNotification(String messageBody) {
    Intent intent = new Intent(this, MainActivity.class);
    intent.addFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP);
    PendingIntent pendingIntent = PendingIntent.getActivity(this, 0 /* Request code */, intent,
            PendingIntent.FLAG_ONE_SHOT);

    Uri defaultSoundUri= RingtoneManager.getDefaultUri(RingtoneManager.TYPE_NOTIFICATION);
    NotificationCompat.Builder notificationBuilder = new NotificationCompat.Builder(this)
            .setSmallIcon(R.mipmap.ic_launcher)
            .setContentTitle(messageBody)
            .setAutoCancel(false)
            .setSound(defaultSoundUri);

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

    notificationManager.notify(1, notificationBuilder.build());
}
}

Manifest File:

<?xml version="1.0" encoding="utf-8"?>
<manifest xmlns:android="http://schemas.android.com/apk/res/android"
    package="com.shubhank.fcm_tutorial">
    <uses-permission android:name="android.permission.INTERNET"/>
    <uses-permission android:name="android.permission.ACCESS_NETWORK_STATE"/>
    <uses-permission android:name="android.permission.GET_ACCOUNTS" />

    <application
        android:allowBackup="true"
        android:icon="@mipmap/ic_launcher"
        android:label="@string/app_name"
        android:supportsRtl="true"
        android:launchMode="standard"
        android:theme="@style/AppTheme">
        <activity android:name=".MainActivity">
            <intent-filter>
                <action android:name="android.intent.action.MAIN" />

                <category android:name="android.intent.category.LAUNCHER" />
            </intent-filter>
        </activity>

        <service android:name=".TokenService"
            android:exported="true">
            <intent-filter>
                <action android:name="com.google.firebase.INSTANCE_ID_EVENT" />
            </intent-filter>
        </service>
        <service android:name=".FCMMessageReceiverService"
            android:exported="true">
            <intent-filter>
                <action android:name="com.google.firebase.MESSAGING_EVENT" />
            </intent-filter>
        </service>
        </activity>
        <meta-data
            android:name="com.google.android.gms.version"
            android:value="@integer/google_play_services_version"/>
    </application>

</manifest>

解决方案

Make changes like this

in gradle file

   compile 'com.google.firebase:firebase-messaging:9.0.0'

and

public class FirebaseMessagingServices extends FirebaseMessagingService {

private static final String TAG = "FirebaseMessaging";
private NotificationManager mNotificationManager;
public static final int NOTIFICATION_ID = 1;


@Override
public void onMessageReceived(RemoteMessage remoteMessage) {
    // TODO(developer): Handle FCM messages here.
    // Not getting messages here
    Log.v(TAG, "From: " + remoteMessage.getFrom());

    // Check if message contains a data payload.
    if (remoteMessage.getData().size() > 0) {
        Log.v(TAG, "Message data payload: 1" + remoteMessage.getData());
      //  sendNotification(remoteMessage.getData()+"");
        Log.v(TAG, "Message data payload: 2" + remoteMessage.getData().get(Config.MESSAGE_KEY).toString());    
                    sendNotification(remoteMessage.getData().get(Config.MESSAGE_KEY) + "");
         }

    // Check if message contains a notification payload.
    if (remoteMessage.getNotification() != null) {
        Log.v(TAG, "Message Notification Body: " + remoteMessage.getNotification().getBody());

        SharedPreferences preferences =getSharedPreferences(Utils.SIGNUP_PREF, MODE_PRIVATE);
        boolean notification = preferences.getBoolean(Utils.notification,true);

            sendNotification(remoteMessage.getNotification().getBody()); 
    }
}
    private void sendNotification(String msg) {
    MediaPlayer mp = MediaPlayer.create(getApplicationContext(), R.raw.notification1);
    mp.start();

    mNotificationManager = (NotificationManager) this
            .getSystemService(Context.NOTIFICATION_SERVICE);

    PendingIntent contentIntent = PendingIntent.getActivity(this, 0,
            new Intent(this, MainActivity.class), 0);

    NotificationCompat.Builder mBuilder = (NotificationCompat.Builder) new NotificationCompat.Builder(
            this).setSmallIcon(R.drawable.penless_small)
            .setContentTitle("Penless")
            .setStyle(new NotificationCompat.BigTextStyle().bigText(msg))
            .setContentText(msg);
    mBuilder.setContentIntent(contentIntent);
    mNotificationManager.notify(NOTIFICATION_ID, mBuilder.build());}}

这篇关于FCM令牌问题在一些Android设备的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆