简体   繁体   English

Android-Firebase推送通知不起作用

[英]Android - Firebase push notification not working

I have created and setup Firebase console completely as Google tutorial mentioned. 正如Google教程所述,我已经完全创建并设置了Firebase控制台。 I have implemented Services in my project as well. 我也在我的项目中实现了服务。 While I am sending the message from Firebase console it is not receiving in my app. 从Firebase控制台发送消息时,我的应用程序未收到消息。 When I am trying to send using the single device then it is showing "Unregistered registration token". 当我尝试使用单个设备进行发送时,它显示“未注册的注册令牌”。

Here is my MyFirebaseInstanceIDService: 这是我的MyFirebaseInstanceIDService:

public class MyFirebaseInstanceIDService extends FirebaseInstanceIdService {

    @Override
    public void onTokenRefresh() {

        //Getting registration token
        String refreshedToken = FirebaseInstanceId.getInstance().getToken();
        System.out.println("TOKEN::" + refreshedToken);
        //Displaying token on logcat

        SmartApplication.REF_SMART_APPLICATION.writeSharedPreferences("regId", refreshedToken);
//        SharedPreferences pref = getApplicationContext().getSharedPreferences(Config.SHARED_PREF, 0);
//        SharedPreferences.Editor editor = pref.edit();
//        editor.putString("regId", refreshedToken);
//        editor.commit();
    }
}

Here is my MyFirebaseMessagingService: 这是我的MyFirebaseMessagingService:

public class MyFirebaseMessagingService extends FirebaseMessagingService {

    private static final String TAG = "MyFirebaseMsgService";
    private static int count = 0;
    String TYPE = "type";

    @Override
    public void onMessageReceived(RemoteMessage remoteMessage) {
        //Displaying data in log
        //It is optional
        System.out.println("data getting");
        Log.d(TAG, "Notification Message TITLE: " + remoteMessage.getNotification().getTitle());
        Log.d(TAG, "Notification Message BODY: " + remoteMessage.getNotification().getBody());
        Log.d(TAG, "Notification Message DATA: " + remoteMessage.getData().toString());

        //Calling method to generate notification
        //remoteMessage.getNotification().getBody()
        sendNotification(remoteMessage.getNotification().getTitle(),
                remoteMessage.getNotification().getBody(), remoteMessage.getData());
    }


    //This method is only generating push notification
    //It is same as we did in earlier posts
    private void sendNotification(String messageTitle, String messageBody, Map<String, String> row) {
        PendingIntent contentIntent = null;
        try {
            Intent groupDetailIntent = new Intent(this, UnanimousHomeActivity.class);

            contentIntent = PendingIntent.getActivity(this, (int) (Math.random() * 100),
                    groupDetailIntent, PendingIntent.FLAG_UPDATE_CURRENT);
        } catch (Exception e) {
            e.printStackTrace();
        }
        Uri defaultSoundUri = RingtoneManager.getDefaultUri(RingtoneManager.TYPE_NOTIFICATION);
        NotificationCompat.Builder notificationBuilder = new NotificationCompat.Builder(this)
                .setSmallIcon(R.mipmap.ic_launcher)
                .setContentTitle(messageTitle)
                .setContentText(messageBody)
                .setAutoCancel(true)
                .setSound(defaultSoundUri)
                .setContentIntent(contentIntent);

        NotificationManager notificationManager =
                (NotificationManager) getSystemService(Context.NOTIFICATION_SERVICE);
        notificationManager.notify(count, notificationBuilder.build());
        count++;
    }
}

I have stucked since 4 days, please someone help me out as no logical problem found here, some unusual things are happening while integration push. 自4天以来,我一直处于停滞状态,请有人帮助我,因为这里没有发现逻辑上的问题,在集成推送时发生了一些不寻常的事情。

public class MyFirebaseMessagingService extends FirebaseMessagingService {

    private static final String TAG = MyFirebaseMessagingService.class.getSimpleName();

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


        // Check if message contains a data payload.
        if (remoteMessage.getData().size() > 0) {
            Log.e(TAG, "Message data: " + remoteMessage.getData().toString());



        }

        if (remoteMessage.getNotification() != null) {
            Log.e(TAG, "Message data: " + remoteMessage.getData().toString());
            sendnotification(remoteMessage.getNotification().getBody());



        }
    }

    private void sendnotification(String body) {

        Intent intent = new Intent(this,MainActivity.class);
        intent.setFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP);

        PendingIntent pendingIntent = PendingIntent.getActivity(this,0,intent,PendingIntent.FLAG_ONE_SHOT);

        Uri notificationsound = RingtoneManager.getDefaultUri(RingtoneManager.TYPE_NOTIFICATION);

        NotificationCompat.Builder notificationBuilder = new NotificationCompat.Builder(this)
                .setSmallIcon(R.mipmap.ic_launcher)
                .setContentTitle("Emoji Keyboard")
                .setDefaults(-1)
                .setContentText(body)
                .setVibrate(new long[] { 1000, 1000, 1000, 1000, 1000 })
                .setSound(notificationsound)
                .setAutoCancel(true)
                .setContentIntent(pendingIntent);

        NotificationManager notificationManager = (NotificationManager)getSystemService(Context.NOTIFICATION_SERVICE);
        notificationManager.notify(0,notificationBuilder.build());
    }


}

and after this in manifests add this: 然后在清单中添加以下内容:

 <!-- Firebase Notifications -->
        <service android:name=".services.MyFirebaseMessagingService">
            <intent-filter>
                <action android:name="com.google.firebase.MESSAGING_EVENT" />
            </intent-filter>
        </service>

        <service android:name=".services.MyFirebaseInstanceIDService">
            <intent-filter>
                <action android:name="com.google.firebase.INSTANCE_ID_EVENT" />
            </intent-filter>
        </service>
        <!-- ./Firebase Notifications -->

After you've successfully obtained the token, make sure that you've send it correctly to your server. 成功获取令牌后,请确保已将其正确发送到服务器。

Try the recommended action for Invalid Registration Token: 尝试对无效注册令牌采取建议的操作

Check the format of the registration token you pass to the server. 检查传递给服务器的注册令牌的格式。 Make sure it matches the registration token the client app receives from registering with Firebase Notifications. 确保它与客户端应用程序通过Firebase Notifications注册收到的注册令牌匹配。 Do not truncate or add additional characters. 不要截断或添加其他字符。

For more information, see this documentation . 有关更多信息,请参见本文档

Code is working Fine in my application 代码在我的应用程序中运行正常

Add googleservices-json file in app folder created from firebase and add services in manifest 在从Firebase创建的应用文件夹中添加googleservices-json文件,并在清单中添加服务

<service
            android:name=".MyFirebaseMessagingService">
            <intent-filter>
                <action android:name="com.google.firebase.MESSAGING_EVENT"/>
            </intent-filter>
        </service>
        <service
            android:name=".MyFirebaseInstanceIDService">
            <intent-filter>
                <action android:name="com.google.firebase.INSTANCE_ID_EVENT"/>
            </intent-filter>
        </service>

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM