无法将Firebase令牌存储在MySQL数据库中。
无法将Firebase令牌存储在MySQL数据库中。
我无法确定自己在哪里出错了。我需要获取Firebase令牌并将其存储在数据库中,并使用这些令牌向这些设备发送通知。以下是我的代码。我真的需要一些帮助。
MainActivity.java
public class MainActivity extends AppCompatActivity { @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_main); FirebaseInstanceId.getInstance().getToken(); FirebaseMessaging.getInstance(); } }
FirebaseInstanceIDService.java
public class FirebaseInstanceIDService extends FirebaseInstanceIdService { @Override public void onTokenRefresh() { String token = FirebaseInstanceId.getInstance().getToken(); Log.e("Token :",token); registerToken(token); } private void registerToken(String token) { OkHttpClient client = new OkHttpClient(); RequestBody body = new FormBody.Builder() .add("Token",token) .build(); Request request = new Request.Builder() .url("http://localhost/notify.php") .post(body) .build(); try { client.newCall(request).execute(); } catch (IOException e) { e.printStackTrace(); } } }
FirebaseMessagingService.java
public class FirebaseMessagingService extends com.google.firebase.messaging.FirebaseMessagingService{ @Override public void onMessageReceived(RemoteMessage remoteMessage) { showNotification(remoteMessage.getData().get("message")); } private void showNotification(String message) { Intent i = new Intent(this,MainActivity.class); i.addFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP); PendingIntent pendingIntent = PendingIntent.getActivity(this,0,i,PendingIntent.FLAG_UPDATE_CURRENT); NotificationCompat.Builder builder = new NotificationCompat.Builder(this) .setAutoCancel(true) .setContentTitle("FCM Test") .setContentText(message) .setSmallIcon(R.drawable.gas45) .setContentIntent(pendingIntent); NotificationManager manager = (NotificationManager) getSystemService(NOTIFICATION_SERVICE); manager.notify(0,builder.build()); } }
notify.php
无法将Firebase令牌存储在MySQL数据库中的问题可能有以下原因和解决方法:
原因:
1. 检查您的互联网连接是否没有代理并且连接正常。
2. 将您的google-service.json
替换为新的文件,您可以在Firebase控制台中获取该文件。
3. 请检查您的设备上是否安装了Google Play服务,并且该服务是否正常工作,因为没有Google Play服务,Firebase将无法正常工作。
解决方法:
1. 检查是否在AndroidManifest.xml文件中注册了Firebase服务,例如FirebaseInstanceId服务。
<!-- Firebase Notifications --> <service android:name="com.indus.corelib.notification.FirebaseMessagingService" android:exported="false" > <intent-filter> <action android:name="com.google.firebase.MESSAGING_EVENT" /> </intent-filter> </service> <service android:name="com.indus.corelib.notification.FirebaseIDService" android:exported="false" > <intent-filter> <action android:name="com.google.firebase.INSTANCE_ID_EVENT" /> </intent-filter> </service>
2. 参考以下链接的步骤来解决该问题:
- https://www.codementor.io/flame3/send-push-notifications-to-android-with-firebase-du10860kb
- https://www.survivingwithandroid.com/2016/09/android-firebase-push-notification.html
祝您好运!