我無法弄清楚我要出錯的地方。我需要獲取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
<?php
if (isset($_POST["Token"])) {
$fcm_Token=$_POST["Token"];
$conn = mysqli_connect("localhost","root","","fcm") or
die("Error connecting");
$q="INSERT INTO users (Token) VALUES ('$fcm_Token')"
."ON DUPLICATE KEY UPDATE Token = '$fcm_Token';";
mysqli_query($conn,$q) or die(mysqli_error($conn));
mysqli_close($conn);
}
?>
請查看我以前的答案[這](https://stackoverflow.com/a/40283178/4741746) –
你得到onTokenRefresh的方法令牌? –
不..我沒有得到 –