【发布时间】:2018-02-23 07:13:26
【问题描述】:
我不知道哪里出错了。我需要获取 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);
}
?>
【问题讨论】:
-
请查看我之前的回答[this](stackoverflow.com/a/40283178/4741746)
-
你在onTokenRefresh的方法中得到token了吗?
-
不..我没有得到
-
您的代码有什么问题?请记住:您是我们中唯一可以在调试器中运行此代码并告诉我们发生了什么的人。
标签: php android mysql firebase firebase-cloud-messaging