Я использую FCM для push-уведомлений. Но когда я вызываю API с Android, он попадает во множественные безостановочные уведомления.
Вот мой код Android для сервисов, где мой сервис постоянно проверяет столбец finish_by. в базе данных. если API обнаружил данные о текущем времени в базе данных, тогда FCM обращается к соответствующим пользователям.
public class NotifService extends Service {
public static final int notify = 1000; //interval between two services(Here Service run every 5 Minute)
private Handler mHandler = new Handler(); //run on another Thread to avoid crash
private Timer mTimer = null; //timer handling
CharSequence s;
@Override
public IBinder onBind(Intent intent) {
throw new UnsupportedOperationException("Not yet implemented");
}
@Override
public void onCreate() {
if (mTimer != null) // Cancel if already existed
mTimer.cancel();
else
mTimer = new Timer(); //recreate new
mTimer.scheduleAtFixedRate(new TimeDisplay(), 0, notify); //Schedule task
}
@Override
public void onDestroy() {
super.onDestroy();
// mTimer.cancel(); //For Cancel Timer
Toast.makeText(this, "Service is Destroyed", Toast.LENGTH_SHORT).show();
}
@Override
public int onStartCommand(Intent intent, int flags, int startId) {
return START_STICKY;//super.onStartCommand(intent, flags, startId);
}
class TimeDisplay extends TimerTask {
@Override
public void run() {
// run on another thread
mHandler.post(new Runnable() {
@Override
public void run() {
curtime();
String datime = String.valueOf(s);
callAPIHIT(datime);
}
});
}
}
private void callAPIHIT(String datime) {
Call<GetNotifReceiversModel> categoryModelCall = RetrofitClient
.getRetrofitClient()
.create(ApiInterface.class)
.getNotifReceivers(datime);
categoryModelCall.enqueue(new Callback<GetNotifReceiversModel>() {
@Override
public void onResponse(@NonNull Call<GetNotifReceiversModel> call, @NonNull Response<GetNotifReceiversModel> response) {
try {
Toast.makeText(getApplicationContext(), "Service "+response.body().getData().get(0).getTask_name(), Toast.LENGTH_LONG).show();
} catch (Exception e) {
e.printStackTrace();
}
}
@Override
public void onFailure(@NonNull Call<GetNotifReceiversModel> call, @NonNull Throwable t) {
Toast.makeText(getApplicationContext(), t.getLocalizedMessage(), Toast.LENGTH_LONG).show();
}
});
}
public void curtime(){
Date d = new Date();
s = DateFormat.format("dd-MM-yyyy HH:mm:ss", d.getTime());
}
}
Вот код php-сервера FCM, где мы нажимаем уведомление FCM из этой строки кода и вызываем егоAPI в Android.
public function getNotifReceivers(Request $request){
$fin_date = $request->input('fin_date');
$role = 'user';
$api_key = 'AAAA....';
define('API_ACCESS_KEY',$api_key);
$fcmUrl = 'https://fcm.googleapis.com/fcm/send';
$query_out = app('db')->select("SELECT task_id, task_name, task_status FROM `pts_task` WHERE finish_by = '$fin_date'");
if ($query_out) {
if($role == 'user'){
$query = app('db')->select("SELECT firebase_tokenId FROM `pts_user` WHERE u_role != 'user' AND firebase_tokenId IS NOT NULL");
}
else if($role == 'super_user'){
$query = app('db')->select("SELECT firebase_tokenId FROM `pts_user` WHERE u_role NOT IN ('user', 'super_user') AND firebase_tokenId IS NOT NULL");
}
if ($query) {
$someArray = json_decode(json_encode($query),true);
$return_array = array();
for($i = 0; $i < sizeof($someArray); $i++){
// if($someArray[$i]["firebase_tokenId"] != null){
$arr[$i] = $someArray[$i]["firebase_tokenId"];
array_push($return_array, $arr[$i]);
// }
}
$array = json_decode(json_encode($query_out), true);
$task_name = $array[0]['task_name'];
$status = $array[0]['task_status'];
$notification = [
'title' =>'task - '.$task_name,
'body' => 'STATUS - '.$status
];
$extraNotificationData = ["message" =>
$notification,"moredata" =>'dd'];
$fcmNotification = [
'registration_ids' => $return_array, //multple token
array
//'to' => $token, //single token
'notification' => $notification,
'data' => $extraNotificationData,
'click_action'=>'MY PACKAGE NAME'
];
$headers = [
'Authorization: key=' . API_ACCESS_KEY,
'Content-Type: application/json'
];
$ch = curl_init();
curl_setopt($ch, CURLOPT_URL,$fcmUrl);
curl_setopt($ch, CURLOPT_POST, true);
curl_setopt($ch, CURLOPT_HTTPHEADER, $headers);
curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, false);
curl_setopt($ch, CURLOPT_POSTFIELDS,
json_encode($fcmNotification));
$result = curl_exec($ch);
curl_close($ch);
// echo $result;
return response()->json(['status' => $fin_date, 'msg' => 'List of Category', 'data' => $query_out]);
}
}else{
return response()->json(['status' => 'fail', 'msg' => 'Failure', 'data' => $query_out]);
}
}