2017-04-02 37 views
0

我正在开发使用本地主机进行Firebase通知的演示。未从本地服务器接收到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> 

这里是我的Android代码

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

好吧,我面临着因为服务器密钥传统服务器密钥之间有点误会与FCM相同的问题。

  • 对于FCM一直使用服务器密钥。由于错误,我们通常需要传统服务器密钥,因为它的长度;我们在GCM中使用了这个简短的Web API密钥。

  • 你需要以发送推送通知您的后端系统使用您的发件人ID;我们从未使用发件人ID在GCM的后端。

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

+0

是绝对正确的我在更改服务器密钥后使用Legacy服务器密钥,它的工作方式就像一个魅力。感谢周日的回应。你让我的星期天值得,而非常感谢。 –

相关问题