如何获得firebase令牌?

时间:2019-06-11 05:47:58

标签: java android firebase kotlin firebase-cloud-messaging

我正在开发一个通过FCM使用通知的测试应用。我正在使用Volley将数据从设备发送到服务器(WAMP),但是令牌始终是空字符串/我编写的默认值。我搜索了互联网,但我仍然不知道为什么不存储/生成令牌(我是编码新手。) 还有一件事:每次发送令牌时,吐司都会向我显示我在此处编写的“好消息”文本,但同时也会给我很多html代码。 这是我的文件: MainActivity.kt

import android.content.Context
import android.support.v7.app.AppCompatActivity
import android.os.Bundle
import android.util.Log
import android.view.View
import android.widget.Button
import android.widget.Toast
import com.android.volley.AuthFailureError
import com.android.volley.Request
import com.android.volley.Response
import com.android.volley.toolbox.StringRequest

class MainActivity : AppCompatActivity() {
    var url: String = "......"
    override fun onCreate(savedInstanceState: Bundle?) {
        super.onCreate(savedInstanceState)
        setContentView(R.layout.activity_main)
        var button: Button = findViewById(R.id.save_token)
        button.setOnClickListener(object : View.OnClickListener{
            override fun onClick(v: View?) {
                val sharedPreferences =
                    applicationContext.getSharedPreferences(getString(R.string.FCM_PREF), Context.MODE_PRIVATE)
                var token: String = sharedPreferences.getString(getString(R.string.FCM_TOKEN),"noToken")
//                var token: String = "sss";
                val request = object : StringRequest(Request.Method.POST, url,
                    Response.Listener { response ->
                        Toast.makeText(this@MainActivity, "Good one $response", Toast.LENGTH_SHORT).show()
                        Log.i("My success", "" + response)
                    }, Response.ErrorListener { error ->
                        Toast.makeText(this@MainActivity, "my error :$error", Toast.LENGTH_LONG).show()
                        Log.i("My error", "" + error)
//                        println("Error $error")
                    }) {
                    @Throws(AuthFailureError::class)
                    override fun getParams(): Map<String, String> {

                        val params = HashMap<String, String>()
                        params.put("fcm_token", token)

                        return params
                    }
                }
                MySingleton.getmInstance(this@MainActivity).addToRequestQueue(request)
            }
        })

    }
}

FcmInstanceIdService.java

public class FcmInstanceIdService extends FirebaseMessagingService{
    @Override
    public void onNewToken(String s) {

        String  recent_token = s;
        SharedPreferences sharedPreferences = getApplicationContext().getSharedPreferences(getString(R.string.FCM_PREF),Context.MODE_PRIVATE);
        SharedPreferences.Editor editor = sharedPreferences.edit();
        editor.putString(getString(R.string.FCM_TOKEN), recent_token);
        editor.commit();
    }
}

这是我从成功祝酒中获得的日志:

2019-06-11 08:48:45.135 5684-5684/com.example.rares.firebaselast D/My success: connection success<br />
    <font size='1'><table class='xdebug-error xe-notice' dir='ltr' border='1' cellspacing='0' cellpadding='1'>
    <tr><th align='left' bgcolor='#f57900' colspan="5"><span style='background-color: #cc0000; color: #fce94f; font-size: x-large;'>( ! )</span> Notice: Undefined variable: mysqli_close in C:\wamp64\www\firebase\fcm_insert.php on line <i>7</i></th></tr>
    <tr><th align='left' bgcolor='#e9b96e' colspan='5'>Call Stack</th></tr>
    <tr><th align='center' bgcolor='#eeeeec'>#</th><th align='left' bgcolor='#eeeeec'>Time</th><th align='left' bgcolor='#eeeeec'>Memory</th><th align='left' bgcolor='#eeeeec'>Function</th><th align='left' bgcolor='#eeeeec'>Location</th></tr>
    <tr><td bgcolor='#eeeeec' align='center'>1</td><td bgcolor='#eeeeec' align='center'>0.0023</td><td bgcolor='#eeeeec' align='right'>402152</td><td bgcolor='#eeeeec'>{main}(  )</td><td title='C:\wamp64\www\firebase\fcm_insert.php' bgcolor='#eeeeec'>...\fcm_insert.php<b>:</b>0</td></tr>
    </table></font>
    <br />
    <font size='1'><table class='xdebug-error xe-uncaught-exception' dir='ltr' border='1' cellspacing='0' cellpadding='1'>
    <tr><th align='left' bgcolor='#f57900' colspan="5"><span style='background-color: #cc0000; color: #fce94f; font-size: x-large;'>( ! )</span> Fatal error: Uncaught Error: Function name must be a string in C:\wamp64\www\firebase\fcm_insert.php on line <i>7</i></th></tr>
    <tr><th align='left' bgcolor='#f57900' colspan="5"><span style='background-color: #cc0000; color: #fce94f; font-size: x-large;'>( ! )</span> Error: Function name must be a string in C:\wamp64\www\firebase\fcm_insert.php on line <i>7</i></th></tr>
    <tr><th align='left' bgcolor='#e9b96e' colspan='5'>Call Stack</th></tr>
    <tr><th align='center' bgcolor='#eeeeec'>#</th><th align='left' bgcolor='#eeeeec'>Time</th><th align='left' bgcolor='#eeeeec'>Memory</th><th align='left' bgcolor='#eeeeec'>Function</th><th align='left' bgcolor='#eeeeec'>Location</th></tr>
    <tr><td bgcolor='#eeeeec' align='center'>1</td><td bgcolor='#eeeeec' align='center'>0.0023</td><td bgcolor='#eeeeec' align='right'>402152</td><td bgcolor='#eeeeec'>{main}(  )</td><td title='C:\wamp64\www\firebase\fcm_insert.php' bgcolor='#eeeeec'>...\fcm_insert.php<b>:</b>0</td></tr>
    </table></font>

3 个答案:

答案 0 :(得分:1)

//Get Firebase FCM token
        FirebaseInstanceId.getInstance().getInstanceId().addOnSuccessListener(activity, new OnSuccessListener<InstanceIdResult>() {
            @Override
            public void onSuccess(InstanceIdResult instanceIdResult) {
                String token = instanceIdResult.getToken();

            }
        });

将此代码放入您的第一个活动的onCreate方法中以获取FCM令牌。您可以将其保存在全局变量中

答案 1 :(得分:0)

为您的应用创建应用类:

class MyApplication : Application() {


override fun onCreate() {
    super.onCreate()
    initFCM()
}


private fun initFCM(){
    FirebaseInstanceId.getInstance().instanceId
            .addOnCompleteListener(OnCompleteListener { task ->
                if (!task.isSuccessful) {
                    return@OnCompleteListener
                }
                // Get new Instance ID token
                val token = task.result?.token
            })
}}

在Androidmanifest.xml文件的android:name标签中,添加您的自定义应用程序类名称,如下所示。

<application
    android:name=".MyApplication "
    android:allowBackup="true" 

答案 2 :(得分:0)

尝试           FirebaseInstanceId

  

Firebase实例ID为每个应用程序提供唯一的标识符   实例以及验证和授权操作的机制

科林

        FirebaseInstanceId.getInstance().instanceId
                .addOnSuccessListener(object : OnSuccessListener<InstanceIdResult> {
                    override fun onSuccess(instanceIdResult: InstanceIdResult) {
                        val token = instanceIdResult.token //Token

                }
              })