I have this app, that recieves push notifications from a php based server, the push notification is a data payload that contains a url that automatically opens in a webview when clicked.
My app works, but not in the way I want it to work. I am able to send push notifcations from my php server, but the notification shows only when the app is in the foreground, but when it is on the background it does not display.
When I check the logcat, i discovered that the json data is sent from the server, even when the app is in the background. What could be preventing the push notification from displaying when the app is in background or killed?
Below is my FirebaseMessaging Class
public class MyFirebaseMessagingService extends FirebaseMessagingService{
private final String CHANNEL_ID="notificcation";
@Override
public void onNewToken(String s) {
super.onNewToken(s);
Log.e("NEW_TOKEN",s);
}
@Override
public void onMessageReceived(RemoteMessage remoteMessage) {
super.onMessageReceived(remoteMessage);
handleMessage(remoteMessage.getData().get(Config.STR_KEY));
}
private void handleMessage(String message) {
Intent pushNotification=new Intent(Config.STR_PUSH);
pushNotification.putExtra(Config.STR_MESSAGE,message);
LocalBroadcastManager.getInstance(this).sendBroadcast(pushNotification);
}
}
Here is my PHP script
<?php
require "init.php";
$message=$_POST['message'];
$title=$_POST['title'];
$url=$_POST['url'];
$path_to_fcm='https://fcm.googleapis.com/fcm/send';
$server_key="xxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxx";
$sql="SELECT fcm_token FROM fcm_info";
$result=mysqli_query($con,$sql);
while($row = mysqli_fetch_array($result)) {
$key=$row['fcm_token'];
}
$headers=array(
'Authorization:key=' .$server_key,
'Content-Type:application/json'
);
$fields=array(
'to'=>$key,
'data'=>array('title'=>$title,'body'=>$message,'webUrl'=>$url));
$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($con);
?>
My Main Activity
public class MainActivity extends AppCompatActivity {
private WebView webView;
private ProgressDialog dialog;
private BroadcastReceiver mRegistrationBroadcastReciever;
private final String CHANNEL_ID="notificcation";
String app_server_url="http:/xxxxxxxxxxx/insert.php";
@Override
public void onBackPressed() {
AlertDialog.Builder builder=new AlertDialog.Builder(this);
if(webView.canGoBack()){
webView.goBack();
}else{
builder.setTitle("Do you want to leave the App?");
builder.setMessage("Are you sure?");
builder.setPositiveButton("Exit", new DialogInterface.OnClickListener() {
@Override
public void onClick(DialogInterface dialog, int which) {
finish();
}
});
builder.setNegativeButton("Cancel", new DialogInterface.OnClickListener() {
@Override
public void onClick(DialogInterface dialog, int which) {
}
});
AlertDialog dialog=builder.show();
}
}
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
SharedPreferences sharedPreferences=getApplicationContext().getSharedPreferences(getString(R.string.FCM_PREF), Context.MODE_PRIVATE);
final String token=sharedPreferences.getString(getString(R.string.FCM_TOKEN),"");
StringRequest stringRequest=new StringRequest(Request.Method.POST, app_server_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);
webView=(WebView)findViewById(R.id.webView);
webView.getSettings().setJavaScriptEnabled(true);
webView.setWebChromeClient(new WebChromeClient());
webView.loadUrl("http://default_website");
webView.setWebViewClient(new WebViewClient(){
@Override
public void onPageFinished(WebView view, String url) {
if(dialog.isShowing())
dialog.dismiss();
}
});
mRegistrationBroadcastReciever=new BroadcastReceiver() {
@Override
public void onReceive(Context context, Intent intent) {
if(intent.getAction().equals(Config.STR_PUSH))
{
String message=intent.getStringExtra(Config.STR_MESSAGE);
showNotification("Article",message);
}
}
};
onNewIntent(getIntent());
}
@Override
protected void onNewIntent(Intent intent) {
dialog=new ProgressDialog(this);
if(intent.getStringExtra(Config.STR_KEY)!=null)
{
dialog.show();
dialog.setMessage("Please Wait");
webView.loadUrl(intent.getStringExtra(Config.STR_KEY));
}
}
private void showNotification(String title, String message) {
notificationChannel();
Bitmap picture = BitmapFactory.decodeResource(getResources(),R.mipmap.app_launcher);
Intent intent =new Intent(getBaseContext(),MainActivity.class);
intent.putExtra(Config.STR_KEY,message);
intent.setFlags(Intent.FLAG_ACTIVITY_SINGLE_TOP);
PendingIntent contentIntent=PendingIntent.getActivity(getBaseContext(),0,intent,PendingIntent.FLAG_UPDATE_CURRENT);
NotificationCompat.Builder builder=new NotificationCompat.Builder(getBaseContext(),CHANNEL_ID);
builder.setAutoCancel(true)
.setWhen(System.currentTimeMillis())
.setDefaults(Notification.DEFAULT_ALL)
.setSmallIcon(R.drawable.ic_sms_black_24dp)
.setContentTitle(title)
.setContentText(message)
.setLargeIcon(picture)
.setPriority(NotificationCompat.PRIORITY_HIGH)
.setContentIntent(contentIntent);
NotificationManager notificationManager = (NotificationManager)getBaseContext().getSystemService(Context.NOTIFICATION_SERVICE);
notificationManager.notify(1,builder.build());
}
private void notificationChannel (){
if(Build.VERSION.SDK_INT>=Build.VERSION_CODES.O)
{
CharSequence name="Personal Notificaiton";
String description="include";
int importance=NotificationManager.IMPORTANCE_DEFAULT;
NotificationChannel notificationChannel=new NotificationChannel(CHANNEL_ID,name,importance);
notificationChannel.setDescription(description);
NotificationManager notificationManager=(NotificationManager)getSystemService(NOTIFICATION_SERVICE);
notificationManager.createNotificationChannel(notificationChannel);
}
}
@Override
protected void onPause() {
LocalBroadcastManager.getInstance(this).unregisterReceiver(mRegistrationBroadcastReciever);
super.onPause();
}
@Override
protected void onResume() {
super.onResume();
LocalBroadcastManager.getInstance(this).registerReceiver(mRegistrationBroadcastReciever,new IntentFilter("registration Complete"));
LocalBroadcastManager.getInstance(this).registerReceiver(mRegistrationBroadcastReciever,new IntentFilter(Config.STR_PUSH));
}
}