没有通过php使用firebase在Android设备上接收通知

时间:2018-03-04 13:49:19

标签: php android firebase firebase-cloud-messaging

我想通过PHP表单向特定用户或一组用户发送通知。 但是我无法得到它。

PHP脚本:

<?php
require "init.php";

$message = $_POST['message'];
$title = $_POST['title'];
$path_to_fcm = 'http://fcm.googleapis.com/fcm/send';
$server_key = 'API_KEY';
$sql = "select fcm_token from fcm_info";
$result = mysqli_query($conn,$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)
                );

echo $title;
echo $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);
mysqli_close($conn);

?>

FCM insert.php

点击按钮,通过应用程序将fcm令牌插入数据库。

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

MyFirebaseMessagingService.java

这里我编码从服务器获取标题和消息,并使用通知管理器将其显示为通知。

public class MyFirebaseMessagingService 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_TOP);
    PendingIntent pendingIntent = PendingIntent.getActivity(this,0,intent,PendingIntent.FLAG_ONE_SHOT);

    NotificationCompat.Builder notificationBuilder = new NotificationCompat.Builder(this);
    notificationBuilder.setContentTitle(title);
    notificationBuilder.setContentText(message);
    notificationBuilder.setAutoCancel(true);
    notificationBuilder.setSmallIcon(R.drawable.trophyy);
    notificationBuilder.setContentIntent(pendingIntent);

    NotificationManagerCompat notificationManager = NotificationManagerCompat.from(this);
   // NotificationManager notificationManager = (NotificationManager) getSystemService(Context.NOTIFICATION_SERVICE);
    notificationManager.notify(0,notificationBuilder.build());
}

}

MyFirebaseInstanceIdServices.java

这里我得到令牌并将其保存到共享偏好。

 public class MyFirebaseInstanceIdServices extends FirebaseInstanceIdService {

private static final String REG_TOKEN = "REG_TOKEN";
@Override
public void onTokenRefresh() {

    String recent_token = FirebaseInstanceId.getInstance().getToken();
    Log.d(REG_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.commit();
}

}

MySingleton.java

public class MySingleton {
private static MySingleton mInstance;
private static Context mCtx;
private RequestQueue requestQueue;

private MySingleton(Context context)
{
    mCtx = context;
    requestQueue = getRequestQueue();
}

private RequestQueue getRequestQueue()
{
    if (requestQueue==null)
    {
        requestQueue = Volley.newRequestQueue(mCtx.getApplicationContext());
    }
    return requestQueue;
}

public static synchronized MySingleton getmInstance(Context context)
{
    if (mInstance==null)
    {
        mInstance = new MySingleton(context);
    }
    return mInstance;
}

public <T> void addToRequestque(Request<T> request)
{
    getRequestQueue().add(request);
}

}

MainActivity.java

这里我从sharedpreference获取令牌并将其发送到数据库。

public class MainActivity extends AppCompatActivity {

Button btn;
String url = "http://192.168.25.18/fcmfire/fcm_insert.php";
@Override
protected void onCreate(final Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.activity_main);

    btn = findViewById(R.id.btn);

    btn.setOnClickListener(new View.OnClickListener() {
        @Override
        public void onClick(View v) {

            SharedPreferences sharedPreferences = getApplicationContext().getSharedPreferences(getString(R.string.FCM_PREF), Context.MODE_PRIVATE);
            final String token = sharedPreferences.getString(getString(R.string.FCM_TOKEN),"");
            Toast.makeText(MainActivity.this, token, Toast.LENGTH_SHORT).show();
            StringRequest stringRequest = new StringRequest(Request.Method.POST, url, new Response.Listener<String>() {
                @Override
                public void onResponse(String response) {

                }
            }, new Response.ErrorListener() {
                @Override
                public void onErrorResponse(VolleyError error) {

                }
            })
            {
                @Override
                protected Map<String, String> getParams() throws AuthFailureError {
                    Map<String,String> params = new HashMap<String, String>();
                    params.put("fcm_token",token);

                    return params;
                }
            };
            MySingleton.getmInstance(MainActivity.this).addToRequestque(stringRequest);
        }
    });
}

}

0 个答案:

没有答案