未生成FCM令牌ID

时间:2017-07-11 07:53:46

标签: android firebase firebase-cloud-messaging

我没有获得FCM令牌。

在我的登录屏幕上,我称之为

 startService(new Intent(this, FetchNewRefreshToken.class));
        startService(new Intent(this, ContCreateTokenService.class));

我的清单

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



public class ContCreateTokenService extends Service {
    @Nullable
    @Override
    public IBinder onBind(Intent intent) {
        return null;
    }

    @Override
    public int onStartCommand(Intent intent, int flags, int startId) {
        Intent serviceIntent = new Intent(this, MyFirebaseMessagingService.class);
        startService(serviceIntent);
        return START_REDELIVER_INTENT;
    }
}



public class FetchNewRefreshToken extends IntentService {
    /**
     * Creates an IntentService.  Invoked by your subclass's constructor.
     *
     * @param name Used to name the worker thread, important only for debugging.
     */

    public static final String TAG = FetchNewRefreshToken.class.getSimpleName();


    public FetchNewRefreshToken() {
        super(TAG);
    }

    @Override
    protected void onHandleIntent(Intent intent) {
        try {

            // Resets Instance ID and revokes all tokens.
            FirebaseInstanceId.getInstance().deleteInstanceId();


            // Now manually call onTokenRefresh()
            Log.d(TAG, "Getting new token");
           String token= FirebaseInstanceId.getInstance().getToken();
            final Intent intents = new Intent("tokenReceiver");
            // You can also include some extra data.
            final LocalBroadcastManager broadcastManager = LocalBroadcastManager.getInstance(this);
            intents.putExtra("token", token);
            broadcastManager.sendBroadcast(intents);

        } catch (Exception e) {
            e.printStackTrace();
        }
    }
}


public class MyFirebaseMessagingService extends FirebaseMessagingService {
    private static final String TAG = "FCM Service";
    @Override
    public void onMessageReceived(RemoteMessage remoteMessage) {
        // TODO: Handle FCM messages here.
        // If the application is in the foreground handle both data and notification messages here.
        // Also if you intend on generating your own notifications as a result of a received FCM
        // message, here is where that should be initiated.
        Log.d(TAG, "From: " + remoteMessage.getFrom());
        Log.d(TAG, "Notification Message Body: " + remoteMessage.getNotification().getBody());
        // Check if message contains a data payload.
        if (remoteMessage.getData().size() > 0) {



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

    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 , intent,
                PendingIntent.FLAG_ONE_SHOT);
        Uri defaultSoundUri= RingtoneManager.getDefaultUri(RingtoneManager.TYPE_NOTIFICATION);
        NotificationCompat.Builder notificationBuilder = new NotificationCompat.Builder(this)
                .setSmallIcon(R.drawable.ic_notifications_black_24dp)
                .setContentTitle("FCM Message")
                .setContentText(messageBody)
                .setAutoCancel(true)
                .setSound(defaultSoundUri)
                .setContentIntent(pendingIntent);
        NotificationManager notificationManager =
                (NotificationManager) getSystemService(Context.NOTIFICATION_SERVICE);
        notificationManager.notify(0, notificationBuilder.build());

    }

}

我的mainActivity类

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

           LocalBroadcastManager.getInstance(this).registerReceiver(tokenReceiver,
                    new IntentFilter("tokenReceiver"));
    }
BroadcastReceiver tokenReceiver = new BroadcastReceiver() {
        @Override
        public void onReceive(Context context, Intent intent) {
            String token = intent.getStringExtra("token");
            //Log.d("token",token);
          // String token=FirebaseInstanceId.getInstance().getToken();
            if(token != null)
            {
                //send token to your server or what you want to do
                FirebaseUser user = FirebaseAuth.getInstance().getCurrentUser();
                Log.d("token",token);
                Firebase reference1 = new Firebase("https://fuudful-1a15c.firebaseio.com/users/" +user.getUid());
                Map<String, String> map = new HashMap<String, String>();
                map.put("registrationtoken", token);
                reference1.push().setValue(map);
            }

        }
    };

我没有收到令牌,也没有生成通知,因为数据库中没有插入。

请有人帮我这个吗?

2 个答案:

答案 0 :(得分:2)

您可以尝试使用自己的生成令牌的服务,而不是制作Intent服务。将其存储在您的偏好中,然后随时使用。

public class TokenService extends FirebaseInstanceIdService {

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

将这些行放入AndroidManifest.xml文件中:

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

答案 1 :(得分:2)

如果安装了旧版本,请检查GooglePlayserviceVersion,否则会产生firebase问题

检查Google Play服务版的方法

private boolean checkPlayServices() {
        GoogleApiAvailability apiAvailability = GoogleApiAvailability.getInstance();
        int resultCode = apiAvailability.isGooglePlayServicesAvailable(this);
        if (resultCode != ConnectionResult.SUCCESS) {
            goahead = false;
            if (apiAvailability.isUserResolvableError(resultCode)) {
                dialog = apiAvailability.getErrorDialog(this, resultCode, PLAY_SERVICES_RESOLUTION_REQUEST);
                dialog.setCancelable(false);
                dialog.setCanceledOnTouchOutside(false);
                dialog.show();
            } else {
                Log.i("Demo App", "This device is not supported.");

                AlertDialog.Builder dialog_app = new AlertDialog.Builder(SplashActivity.this);
                dialog_app.setTitle("Error");
                dialog_app.setMessage("This device is not supported..");
                dialog_app.setCancelable(false);
                dialog_app.setPositiveButton("OK", new DialogInterface.OnClickListener() {
                    @Override
                    public void onClick(DialogInterface dialogInterface, int i) {
                        finish();
                    }
                });
                dialog_app.show();
            }
            return false;
        }
        return true;
    }

如果google play服务旧了,那么此方法将显示更新对话框,否则返回true,您可以调用service。

检查播放服务版本

if(checkPlayServices())
{
        Intent intent = new Intent(this, RegistrationIntentService.class);
        startService(intent);
}

CustomFirebaseInstanceIDService.class :Refesh令牌的服务类

public class CustomFirebaseInstanceIDService extends FirebaseInstanceIdService {
    private static final String TAG = CustomFirebaseInstanceIDService.class.getSimpleName();

    @Override
    public void onCreate() {
        super.onCreate();
    }

    @Override
    public void onTokenRefresh() {
        Intent intent = new Intent(this, RegistrationIntentService.class);
        startService(intent);
    }
}

获取FCM令牌的服务类:RegistrationIntentService.class

public class RegistrationIntentService extends IntentService {

    // abbreviated tag name
    private static final String TAG = RegistrationIntentService.class.getSimpleName();
    public RegistrationIntentService() {
        super(TAG);
    }
    String token;
    @Override
    protected void onHandleIntent(Intent intent) {

        // Make a call to Instance API

        FirebaseInstanceId instanceID = FirebaseInstanceId.getInstance();

        
        //String senderId = getResources().getString(R.string.gcm_defaultSenderId);

        // request token that will be used by the server to send push notifications
        token = instanceID.getToken();
        Log.d(TAG, "FCM Registration Token: " + token);

    }
}

在清单文件中定义服务

<service android:name=".notification.CustomFirebaseInstanceIDService">
            <intent-filter>
                <action android:name="com.google.firebase.INSTANCE_ID_EVENT" />
            </intent-filter>
        </service>

<service
            android:name=".notification.RegistrationIntentService"
            android:exported="false" />