无法从本地服务器

时间:2017-04-02 08:08:43

标签: android firebase firebase-cloud-messaging

我正在使用localhost开发firebase通知演示。

我使用android studio配置firebase并将服务器密钥添加到我的php文件中,我在我的Phpmyadmin(Wamp服务器)中获得了令牌,但是当我使用html文件发送通知时,我无法收到通知。

我是android开发人员所以我不知道php api。我认为这可能是send_ntification.php文件中的一个问题。

但我测试使用firebase控制台它工作正常。

以下是我的 php文件

的init.php

<?php

$host = "localhost";
$db_user = "root";
$db_password = "";
$db_name = "fcm_db";

$con = mysqli_connect($host,$db_user,$db_password,$db_name);

if($con)
    echo "Connection Success";
else
   echo"Connection Error....."; 

?>

fcm_insert.php

<?php

require "init.php";
$fcm_token = $_POST["fcm_token"];
$sql = "insert into fcm_info values('".$fcm_token."');";
mysqli_query($con,$sql);
mysqli_close($con)

?>

send_notification.php

<?php

include_once("init.php");

$message =$_POST['message'];

$title = $_POST['title'];
$path_to_fcm = "https://fcm.googleapis.com/fcm/send";
$server_key = "MY SERVER KEY";
$sql = "select fcm_token from fcm_info";
$result = mysqli_query($con,$sql);
$row = mysqli_fetch_row($result);
$key = $row[0];


$headers = array(
'Authorization:key=' .$server_key,
'Content-Type:application/json'
);


$fields = array('to'=>$key,
                'notification'=>array('title'=>$title,'body'=>$message));

$payload = json_encode($fields);

$curl_session = curl_init();
curl_setopt($curl_session, CURLOPT_URL, $path_to_fcm);
curl_setopt($curl_session, CURLOPT_POST, true);
curl_setopt($curl_session, CURLOPT_HTTPHEADER, $headers);
curl_setopt($curl_session, CURLOPT_RETURNTRANSFER, true);
curl_setopt($curl_session, CURLOPT_SSL_VERIFYPEER, false);
curl_setopt($curl_session, CURLOPT_IPRESOLVE, CURL_IPRESOLVE_V4 );
curl_setopt($curl_session, CURLOPT_POSTFIELDS, $payload);

$result = curl_exec($curl_session);

curl_close($curl_session);
mysqli_close($con);

?>

send_notificatiion.html

<html>

<body>

<form action="send_notification.php" method="post">
<table>
<tr>
<td> Title : </td> <td><input type="text" name="title"/></td>
<tr>

<tr>
<td>Message : <td><td><input type="text" name="message"/></td>
</tr>

<td><input type="submit" value="submit"/></td>
</tr>

</table>

</form>

</body>

</html>

这是我的安卓代码

FcmInstenceIdService.java

public class FcmInstenceIdService extends FirebaseInstanceIdService {


    @Override
    public void onTokenRefresh() {

        String recent_token = FirebaseInstanceId.getInstance().getToken();
        Log.e(TAG, "onTokenRefresh: token = "+recent_token );

        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.apply();
    }
}

FcmMessagingService.java

public class FcmMessagingService extends FirebaseMessagingService {

    @Override
    public void onMessageReceived(RemoteMessage remoteMessage) {

        String title = remoteMessage.getNotification().getTitle();
        String message = remoteMessage.getNotification().getBody();

        Intent intent = new Intent(this,MainActivity.class);
        intent.setFlags(Intent.FLAG_ACTIVITY_CLEAR_TASK);
        PendingIntent pendingIntent = PendingIntent.getActivity(this,0,intent,PendingIntent.FLAG_ONE_SHOT);
        NotificationCompat.Builder builder = new NotificationCompat.Builder(this);
        builder.setContentTitle(title);
        builder.setContentText(message);
        builder.setSmallIcon(R.mipmap.ic_launcher);
        builder.setAutoCancel(true);
        builder.setContentIntent(pendingIntent);
        NotificationManager notificationManager = (NotificationManager)getSystemService(Context.NOTIFICATION_SERVICE);
        notificationManager.notify(0,builder.build());

        super.onMessageReceived(remoteMessage);
    }
}

MainActivity.java

public class MainActivity extends AppCompatActivity {

    SharedPreferences sharedPreferences ;

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

    }

    public void SendTokenToServer(View view) {

        sharedPreferences = getApplicationContext().getSharedPreferences(getString(R.string.FCM_PREF), Context.MODE_PRIVATE);

        Log.i("Notificatioin", "SendTokenToServer: token = "+sharedPreferences.getString(getString(R.string.FCM_TOKEN), ""));
        new GetData().execute();

    }


    public class GetData extends AsyncTask<Void, Void, Void> {

        ProgressDialog progressDialog;
        String responseString;

        @Override
        protected void onPreExecute() {
            super.onPreExecute();

            progressDialog = new ProgressDialog(MainActivity.this);
            progressDialog.setMessage("Please wait....");
            progressDialog.setCancelable(true);
            progressDialog.show();
        }

        @Override
        protected Void doInBackground(Void... voids) {

            sharedPreferences.getString(getString(R.string.FCM_TOKEN), "");

            OkHttpClient client = new OkHttpClient();
            RequestBody formBody = new FormBody.Builder()
                    .add("fcm_token", sharedPreferences.getString(getString(R.string.FCM_TOKEN), ""))
                    .build();
            Request request = new Request.Builder()
//                    .url("http://192.168.1.104/fcmtest/fcm_insert.php")
                    .url("http://192.168.0.102/fcmtest/fcm_insert.php")
                    .post(formBody)
                    .build();

            try {

                Response response = client.newCall(request).execute();
                if (!response.isSuccessful()) throw new IOException("Unexpected code " + response);
                {

                    responseString = response.body().string();
                    System.out.println(responseString);
                    response.body().close();
                }
            } catch (Exception e) {
                e.printStackTrace();
            }

            return null;
        }

        @Override
        protected void onPostExecute(Void aVoid) {
            super.onPostExecute(aVoid);
            progressDialog.dismiss();

        }
    }

}

的AndroidManifest.xml

<?xml version="1.0" encoding="utf-8"?>
<manifest xmlns:android="http://schemas.android.com/apk/res/android"
    package="com.production.hometech.fcmdemo">

    <uses-permission android:name="android.permission.INTERNET"/>

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

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

        <service android:name=".FcmInstenceIdService"
            android:enabled="true"
            android:exported="true">
            <intent-filter>
                <action android:name="com.google.firebase.INSTANCE_ID_EVENT" />
            </intent-filter>
        </service>

        <service android:name=".FcmMessagingService"
            android:enabled="true"
            android:exported="true">
            <intent-filter>
                <action android:name="com.google.firebase.MESSAGING_EVENT"/>
            </intent-filter>
        </service>

    </application>

</manifest>

我不明白问题在哪里请帮助我。任何帮助将非常感谢。我花了3个小时来寻找解决方案。

1 个答案:

答案 0 :(得分:1)

嗯,我遇到了与FCM相同的问题,因为服务器密钥旧服务器密钥之间存在一点误解。

  • 对于FCM,请始终使用服务器密钥。由于其长度,我们通常会采用旧服务器密钥;我们在GCM中使用了这个简短的Web API密钥。

  • 您需要在后端系统中使用发件人ID 才能发送推送通知;我们从未在后端使用发件人ID 用于GCM。

请按照以下两个步骤操作,希望您能收到来自FCM的推送通知。