2017-02-21 15 views
1

Я создал проект на консоли Firebase. Я зарегистрировал пакет на консоли Firebase, но я не могу получить какой-либо токен из журнала, даже нажав кнопку LOG TOKEN в приложении.Демонстрация FCM не может получить токен

Затем я пытаюсь отправить сообщение с консолью Firebase и установить для целевого объекта имя моего приложения. Я не получил входящего сообщения из журнала.

enter image description here

Код:

MainActivity.java

public class MainActivity extends AppCompatActivity { 

private final String TAG = "HelloJni"; 

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

    Intent intent = new Intent(this, RegistrationIntentService.class); 
    startService(intent); 

    // Example of a call to a native method 
    TextView tv = (TextView) findViewById(R.id.sample_text); 
    tv.setText(stringFromJNI()); 
    if (getIntent().getExtras() != null) { 
     for (String key : getIntent().getExtras().keySet()) { 
      Object value = getIntent().getExtras().get(key); 
      Log.d(TAG, "Key: " + key + " Value: " + value); 
     } 
    } 
    // [END handle_data_extras] 

    Button subscribeButton = (Button) findViewById(R.id.subscribeButton); 
    subscribeButton.setOnClickListener(new View.OnClickListener() { 
     @Override 
     public void onClick(View v) { 
      // [START subscribe_topics] 
      FirebaseMessaging.getInstance().subscribeToTopic("news"); 
      // [END subscribe_topics] 

      // Log and toast 
      String msg = getString(R.string.msg_subscribed); 
      Log.d(TAG, msg + ", " + FirebaseInstanceId.getInstance().getToken()); 
      Toast.makeText(MainActivity.this, msg, Toast.LENGTH_SHORT).show(); 
     } 
    }); 
} 

RegistrationIntentService.java

public class RegistrationIntentService extends IntentService { 
private static final String TAG = "RegIntentService"; 

public RegistrationIntentService() { 
    super(TAG); 
} 

@Override 
protected void onHandleIntent(Intent intent) { 
    String token = FirebaseInstanceId.getInstance().getToken(); 
    Log.i(TAG, "FCM Registration Token: " + token); 
} 
} 

MyFirebaseInstanceIDService.java

public class MyFirebaseInstanceIDService extends FirebaseInstanceIdService { 

private static final String TAG = "MyFirebaseIIDService"; 

@Override 
public void onCreate() { 
    super.onCreate(); 
    Log.e(TAG, "oncreate........."); 
} 

/** 
* Called if InstanceID token is updated. This may occur if the security of 
* the previous token had been compromised. Note that this is called when the InstanceID token 
* is initially generated so this is where you would retrieve the token. 
*/ 
// [START refresh_token] 
@Override 
public void onTokenRefresh() { 
    Log.e(TAG, "onTokenRefresh call..."); 
    // Get updated InstanceID token. 
    Intent intent = new Intent(this, RegistrationIntentService.class); 
    startService(intent); 
    String refreshedToken = FirebaseInstanceId.getInstance().getToken(); 
    Log.d(TAG, "Refreshed token: " + refreshedToken); 

    // If you want to send messages to this application instance or 
    // manage this apps subscriptions on the server side, send the 
    // Instance ID token to your app server. 
    sendRegistrationToServer(refreshedToken); 
} 
// [END refresh_token] 

/** 
* Persist token to third-party servers. 
* 
* Modify this method to associate the user's FCM InstanceID token with any server-side account 
* maintained by your application. 
* 
* @param token The new token. 
*/ 
private void sendRegistrationToServer(String token) { 
    Log.d(TAG, " sendRegistrationToServer Refreshed token: " + token); 
    // TODO: Implement this method to send token to your app server. 
} 
} 

MyFirebaseMessagingService.java

public class MyFirebaseMessagingService extends FirebaseMessagingService { 

private static final String TAG = "MyFirebaseMsgService"; 

@Override 
public void onCreate() { 
    super.onCreate(); 
    Log.e(TAG, "oncreate.........."); 
} 

/** 
* Called when message is received. 
* 
* @param remoteMessage Object representing the message received from Firebase Cloud Messaging. 
*/ 
// [START receive_message] 
@Override 
public void onMessageReceived(RemoteMessage remoteMessage) { 
    // [START_EXCLUDE] 
    // There are two types of messages data messages and notification messages. Data messages are handled 
    // here in onMessageReceived whether the app is in the foreground or background. Data messages are the type 
    // traditionally used with GCM. Notification messages are only received here in onMessageReceived when the app 
    // is in the foreground. When the app is in the background an automatically generated notification is displayed. 
    // When the user taps on the notification they are returned to the app. Messages containing both notification 
    // and data payloads are treated as notification messages. The Firebase console always sends notification 
    // messages. For more see: https://firebase.google.com/docs/cloud-messaging/concept-options 
    // [END_EXCLUDE] 

    // TODO(developer): Handle FCM messages here. 
    Log.d(TAG, "From: " + remoteMessage.getFrom()); 

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

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

    // Also if you intend on generating your own notifications as a result of a received FCM 
    // message, here is where that should be initiated. See sendNotification method below. 
} 
// [END receive_message] 

/** 
* Create and show a simple notification containing the received FCM message. 
* 
* @param messageBody FCM message body received. 
*/ 
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) 
      .setContentTitle("FCM Message") 
      .setContentText(messageBody) 
      .setAutoCancel(true) 
      .setSound(defaultSoundUri) 
      .setContentIntent(pendingIntent); 

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

    notificationManager.notify(0 /* ID of notification */, notificationBuilder.build()); 
} 
} 

AndroidManifest.xml

<application 

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

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

    <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> 
    <service android:name="RegistrationIntentService" ></service> 
</application> 

enter image description here

OnCreate() для MyFirebaseInstanceIDService и MyFirebaseMessagingService не был вызван, и маркер возвращается нуль.

Журнал:

02-20 18:05:28.273 23322-23322 W/InstanceID/Rpc: Failed to resolve REGISTER intent, falling back 

02-20 18:05:28.273 23322-23322 W/InstanceID/Rpc: Both Google Play Services and legacy GSF package are missing 

02-20 18:05:28.273 23322-23322 W/InstanceID/Rpc: Failed to resolve REGISTER intent, falling back 

02-20 18:05:28.273 23322-23322 W/InstanceID/Rpc: Both Google Play Services and legacy GSF package are missing 

02-20 18:05:28.273 23322-23322 D/HelloJni: Subscribed to news topic, null 

ответ

0

На устройстве или эмуляторе, на котором вы тестируете, нет сервисов Google Play или Google Service Framework (GSF). Большинство API-интерфейсов Firebase используют возможности Служб Google Play и не запускаются, если их нет на устройстве.

0

положить это, наконец, после того, как зависимость в вашем уровне приложения Gradle. apply plugin: 'com.google.gms.google-services'

и поместите это в свой уровень уровня проекта. classpath 'com.google.gms:google-services:3.0.0'

убедитесь, что вы установили google-service.json в модуль приложения.

0

Вы должны добавить.

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

в последней строке в вашем файле градиента и.

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

в вашем файле на уровне проекта. Класс сервиса IntentService будет вызываться только в том случае, если ваше приложение включено, поэтому каждый раз удаляйте приложение и каждый раз набирайте intrall, когда вы хотите создать tocken.

0

Я вижу причину. Я запускаю приложение с Android-телефоном, сделанным в Китае, и у этих телефонов нет сервиса и магазина Google Play.

 Смежные вопросы

  • Нет связанных вопросов^_^