• 15
name

A PHP Error was encountered

Severity: Notice

Message: Undefined index: userid

Filename: views/question.php

Line Number: 191

Backtrace:

File: /home/prodcxja/public_html/questions/application/views/question.php
Line: 191
Function: _error_handler

File: /home/prodcxja/public_html/questions/application/controllers/Questions.php
Line: 433
Function: view

File: /home/prodcxja/public_html/questions/index.php
Line: 315
Function: require_once

I'm trying to use FCM and the notifications only works when I'm not using the application .

when I send notification from device A to device B , then device B receive the message and "show the notification pop with the default sound" and every thing is good... (this happens when device B is not using the application).

when I send notification from device A to device B , then device B receive the message in the onMessageReceived() method but "does not show the notification pop with the default sound".. (this happens when device B is using the application, I mean when the application is open and is being used).

this is my code FireIDService.java

public class FireIDService extends FirebaseInstanceIdService {

    private final String TAG = "FireIDService";

    @Override
    public void onTokenRefresh() {
        String tkn = FirebaseInstanceId.getInstance().getToken();
        Log.d("Not","Token ["+tkn+"]");
        sendRegistrationToServer(tkn);
    }


    private void sendRegistrationToServer(String token) {
        saveDeviceToken(token);
    }

    private void saveDeviceToken(String deviceToken) {
        //some code..
                    if(response.body().getStatus() == 1){
                        doStuff();
                    }
        //some code...
            }

            @Override
            public void onFailure(Call<SaveDeviceTokenResponse> call, Throwable t) {
                //code...
            }
        });
    }

    private void doStuff(){
        Intent intent = new Intent(this, SplashActivity.class);
        intent.addFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP);
        PendingIntent pendingIntent = PendingIntent.getActivity(this, 1410 /* Request code */, intent,
                PendingIntent.FLAG_ONE_SHOT);

        Uri defaultSoundUri= RingtoneManager.getDefaultUri(RingtoneManager.TYPE_NOTIFICATION);
        NotificationCompat.Builder notificationBuilder = new NotificationCompat.Builder(this)
                .setSmallIcon(R.drawable.ic_launcher_background)
                .setContentTitle("FCM Message")
                .setAutoCancel(true)
                .setSound(defaultSoundUri)
                .setContentIntent(pendingIntent);

        NotificationManager notificationManager =
                (NotificationManager) getSystemService(Context.NOTIFICATION_SERVICE);

        notificationManager.notify(1410 /* ID of notification */, notificationBuilder.build());
    }
}

FireBaseMsgService.java

public class FireBaseMsgService  extends FirebaseMessagingService{

    private final String TAG = "FireBaseMsgService";

    @Override
    public void onMessageReceived(RemoteMessage remoteMessage) {
        super.onMessageReceived(remoteMessage);


        Uri defaultSoundUri = RingtoneManager.getDefaultUri(RingtoneManager.TYPE_NOTIFICATION);


        NotificationCompat.Builder notificationBuilder = new NotificationCompat.Builder(this, "test")
                .setSmallIcon(R.drawable.ic_launcher_background)
                .setContentTitle(remoteMessage.getNotification().getTitle())
                .setLargeIcon(BitmapFactory.decodeResource(getResources(), R.drawable.ic_launcher_background))
                .setContentText(remoteMessage.getNotification().getBody())
                .setAutoCancel(true)
                .setColor(0xffff7700)
                .setVibrate(new long[]{100, 100, 100, 100})
                .setPriority(Notification.PRIORITY_MAX)
                .setSound(defaultSoundUri);

        Intent resultIntent = new Intent(this, SplashActivity.class);
        TaskStackBuilder stackBuilder = TaskStackBuilder.create(this);
        stackBuilder.addParentStack(SplashActivity.class);
        stackBuilder.addNextIntent(resultIntent);
        PendingIntent resultPendingIntent =
                stackBuilder.getPendingIntent(
                        0,
                        PendingIntent.FLAG_UPDATE_CURRENT
                );

        notificationBuilder.setContentIntent(resultPendingIntent);
        NotificationManager mNotificationManager =
                (NotificationManager) getSystemService(Context.NOTIFICATION_SERVICE);


        mNotificationManager.notify(1, notificationBuilder.build());
    }

}

this is what added to the AndroidManifest.xml file

<service android:name=".FireIDService">
            <intent-filter>
                <action android:name="com.google.firebase.INSTANCE_ID_EVENT" />
            </intent-filter>
        </service>
        <service android:name=".FireBaseMsgService">
            <intent-filter>
                <action android:name="com.google.firebase.MESSAGING_EVENT" />
            </intent-filter>
        </service>

and this is the Notify class to be execute

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

    private String tkn;
    private String title;
    private String body;

    public Notify(String tkn, String title, String body){
        this.tkn = tkn;
        this.title = title;
        this.body = body;
    }

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

        Log.e("Token: ", tkn);
        Log.e("Title: ", title);
        Log.e("Body: ", body);

        try {

            URL url = new URL("https://fcm.googleapis.com/fcm/send");
            HttpURLConnection conn = (HttpURLConnection) url.openConnection();

            conn.setUseCaches(false);
            conn.setDoInput(true);
            conn.setDoOutput(true);

            conn.setRequestMethod("POST");
            conn.setRequestProperty("Authorization","key=KEY_HERE");
            conn.setRequestProperty("Content-Type", "application/json");

            JSONObject json = new JSONObject();

            json.put("to", tkn);


            JSONObject info = new JSONObject();
            info.put("title", title);   // Notification title
            info.put("body", body); // Notification body
            info.put("priority", "high");
            info.put("show_in_foreground", "true");

            json.put("notification", info);

            OutputStreamWriter wr = new OutputStreamWriter(conn.getOutputStream());
            wr.write(json.toString());
            wr.flush();
            conn.getInputStream();

        }
        catch (Exception e)
        {
            Log.d("Error",""+e);
        }


        return null;
    }

}

If you are using android 8.0+. You need to specify channelId for notification. When your app is in background (as mention in your first case), the push notification is recieved in system notification tray, rather than your FireBaseMsgService, and it is handled automatically by the system by channelId is genreated by system itself. When your app is in foreground (second case) your FireBaseMsgService is executed and have to create notification channelId

  • 1
Reply Report