Thursday 29 August 2019

How to create the token by using the FCM in android.
//Add the application package name and SHA during add application on FCM console
//Make the FirebaseMessagingService

public class FirebaseMessagingService extends com.google.firebase.messaging.FirebaseMessagingService {
    Notification notification;
    private static final String TAG = "MyFirebaseMsgService";

    /**
     * Called when message is received.
     *
     * @param remoteMessage Object representing the message received from Firebase Cloud Messaging.
     */
    // [START receive_message]
    @Override
    public void onMessageReceived(RemoteMessage remoteMessage) {

        // TODO(developer): Handle FCM messages here.
        Log.d(TAG, "Data: " + remoteMessage.getData());
        // Check if message contains a data payload.
        if (remoteMessage.getData().size() > 0) {
            Log.d(TAG, "Message data payload: " + remoteMessage.getData());
            Map<String, String> data = remoteMessage.getData();
            //, data.get("title")
            sendNotification(this,data.get("body"),data.get("imei"));

        }

    }

    //Getting the normal notification here
    @RequiresApi(api = Build.VERSION_CODES.O)
    private void sendNotification(Context context, String title, String time) {
        try {
                if (!title.equals("") || title != null) {
                    int icon = R.mipmap.app_icon;
                    NotificationManager notificationManager = (NotificationManager) context.getSystemService(Context.NOTIFICATION_SERVICE);
                    NotificationCompat.Builder mBuilder;
                    if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.O) {
                        String channelId = getString(R.string.CHANNEL_ID);
                        int imp=NotificationManager.IMPORTANCE_HIGH;
                        NotificationChannel mChannel = new NotificationChannel(channelId, title, imp);
                       // mChannel.setDescription(title);
                        mChannel.setLightColor(Color.CYAN);
                        mChannel.canShowBadge();
                        mChannel.setShowBadge(true);
                        mChannel.enableVibration(true);
                        mChannel.setVibrationPattern(new long[]{100, 200, 300, 400, 500, 400, 300, 200, 400});
                        notificationManager.createNotificationChannel(mChannel);

                        Intent notificationIntent = new Intent(context, "your acctivity name");
                        notificationIntent.putExtra(Constant.NOTIFICATION_RECEIVED, true);
                        notificationIntent.putExtra(Constant.TYPE, time);
                        notificationIntent.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
                        notificationIntent.setFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP | Intent.FLAG_ACTIVITY_SINGLE_TOP);
                        PendingIntent intent = PendingIntent.getActivity(context, 0, notificationIntent, PendingIntent.FLAG_UPDATE_CURRENT);
/*

                        Notification.BigPictureStyle notiStyle = new Notification.BigPictureStyle();
                        notiStyle.setBigContentTitle(title);
                        notiStyle.setSummaryText(title);
*/

                        notification = new Notification.Builder(this, "")
                                .setContentTitle(title)
                                //.setContentText(title)
                                .setNumber(5)
                                .setSmallIcon(icon)
                                .setAutoCancel(true)
                                .setChannelId(channelId)
                                .setVisibility(View.VISIBLE)
                                .setContentIntent(intent)
                                .setCategory(Notification.CATEGORY_PROMO)
                                .setPriority(Notification.PRIORITY_HIGH).build();
                               // .setStyle(notiStyle).build();

                        notification.flags |= Notification.FLAG_AUTO_CANCEL;
                        notification.defaults |= Notification.DEFAULT_SOUND;
                        notification.defaults |= Notification.DEFAULT_VIBRATE;
                        notification.defaults |= Notification.DEFAULT_LIGHTS;
                        notificationManager.notify(1, notification);

                    } else {

                        Intent notificationIntent = new Intent(context, "your acctivity name");
                        notificationIntent.putExtra(Constant.NOTIFICATION_RECEIVED, true);
                        notificationIntent.putExtra(Constant.TYPE, time);
                        notificationIntent.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
                        notificationIntent.setFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP | Intent.FLAG_ACTIVITY_SINGLE_TOP);
                        PendingIntent intent = PendingIntent.getActivity(context, 0, notificationIntent, PendingIntent.FLAG_UPDATE_CURRENT);


                      /*  NotificationCompat.BigPictureStyle notiStyle = new NotificationCompat.BigPictureStyle();
                        notiStyle.setBigContentTitle(title);
                        notiStyle.setSummaryText(title);*/



                        Notification notification = new NotificationCompat.Builder(context)
                                .setContentTitle(title)
                                //.setContentText(title)
                                .setSmallIcon(icon)
                                .setContentIntent(intent)
                                .setCategory(Notification.CATEGORY_PROMO)
                                .setPriority(Notification.PRIORITY_HIGH)
                                .setVisibility(View.VISIBLE).build();
                                //.setStyle(notiStyle).build();

                        notification.flags |= Notification.FLAG_AUTO_CANCEL;
                        notification.defaults |= Notification.DEFAULT_SOUND;
                        notification.defaults |= Notification.DEFAULT_VIBRATE;
                        notification.defaults |= Notification.DEFAULT_LIGHTS;
                        notificationManager.notify(0, notification);
                    }
                }

        } catch (Exception e) {
            e.printStackTrace();
        }

    }
    /**
     * Called if InstanceID token is updated. This may occur if the security of
     * the previous token had been compromised. Note that this is called when the InstanceID token
     * is initially generated so this is where you would retrieve the token.
     */
    @Override
    public void onNewToken(String token) {
        Log.d(TAG, "Refreshed token: " + token);

        // If you want to send messages to this application instance or
        // manage this apps subscriptions on the server side, send the
        // Instance ID token to your app server.
        sendRegistrationToServer(token);
    }



    /**
     * Persist token to third-party servers.
     *
     * Modify this method to associate the user's FCM InstanceID token with any server-side account
     * maintained by your application.
     *
     * @param token The new token.
     */
    private void sendRegistrationToServer(String token) {
        Log.i(TAG, "sendRegistrationToServer: "+token);
    }

}


//Add this method on main activity for getting token in android
 private void getToken() {
        FirebaseInstanceId.getInstance().getInstanceId()
                .addOnCompleteListener(new OnCompleteListener<InstanceIdResult>() {
                    @Override
                    public void onComplete(@NonNull Task<InstanceIdResult> task) {
                        if (!task.isSuccessful()) {
                            Log.w("", "getInstanceId failed", task.getException());
                            return;
                        }
                        // Get new Instance ID token
                        mToken = task.getResult().getToken();
                    }
                });
    }


//Add the fcm lib in app gradle.

implementation 'com.google.firebase:firebase-core:16.0.8'
implementation 'com.google.firebase:firebase-iid:17.1.1'
implementation 'com.google.firebase:firebase-messaging:17.5.0'



//Add the some line in manifest file.

 <meta-data
                android:name="com.google.firebase.messaging.default_notification_icon"
                android:resource="@drawable/app_logo" />
            <meta-data
                android:name="com.google.firebase.messaging.default_notification_color"
                android:resource="@color/colorAccent" />
        <!-- [END fcm_default_icon] -->
        <!-- [START fcm_default_channel] -->
        <meta-data
                android:name="com.google.firebase.messaging.default_notification_channel_id"
                android:value="@string/default_notification_channel_id" />
        <!-- [END fcm_default_channel] -->
        <service
                android:name=".fcm.FirebaseMessagingService"
                android:exported="false">
            <intent-filter>
                <action android:name="com.google.firebase.MESSAGING_EVENT" />
            </intent-filter>
        </service>
 How to add the multiple language in android Application.
 //Create the Locale Helper class in project

public class LocaleHelper {

    private static final String SELECTED_LANGUAGE = "Locale.Helper.Selected.Language";

    public static Context onAttach(Context context) {
        String lang = getPersistedData(context, Locale.getDefault().getLanguage());
        return setLocale(context, lang);
    }

    public static Context onAttach(Context context, String defaultLanguage) {
        String lang = getPersistedData(context, defaultLanguage);
        return setLocale(context, lang);
    }

    public static String getLanguage(Context context) {
        return getPersistedData(context, Locale.getDefault().getLanguage());
    }

    public static  Context setLocale(Context context, String language) {
        persist(context, language);

        if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.N) {
            return updateResources(context, language);
        }

        return updateResourcesLegacy(context, language);
    }

    private static String getPersistedData(Context context, String defaultLanguage) {
        SharedPreferences preferences = PreferenceManager.getDefaultSharedPreferences(context);
        return preferences.getString(SELECTED_LANGUAGE, defaultLanguage);
    }

    private static void persist(Context context, String language) {
        SharedPreferences preferences = PreferenceManager.getDefaultSharedPreferences(context);
        SharedPreferences.Editor editor = preferences.edit();

        editor.putString(SELECTED_LANGUAGE, language);
        editor.apply();
    }

    @TargetApi(Build.VERSION_CODES.N)
    private static Context updateResources(Context context, String language) {
        Locale locale = new Locale(language);
        Locale.setDefault(locale);

        Configuration configuration = context.getResources().getConfiguration();
        configuration.setLocale(locale);
        configuration.setLayoutDirection(locale);

        return context.createConfigurationContext(configuration);
    }

    @SuppressWarnings("deprecation")
    private static Context updateResourcesLegacy(Context context, String language) {
        Locale locale = new Locale(language);
        Locale.setDefault(locale);

        Resources resources = context.getResources();

        Configuration configuration = resources.getConfiguration();
        configuration.locale = locale;
        if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.JELLY_BEAN_MR1) {
            configuration.setLayoutDirection(locale);
        }

        resources.updateConfiguration(configuration, resources.getDisplayMetrics());

        return context;
    }
}


//Create the string.xml for all language
1) values-fr => strings
      <string name="user_name">Utilisateur</string>
1) values => strings
<string name="user_name">UserName</string>


//Declare local helper class in main activity.
 //Changing the language here
        if (Credentials.getLanguage(getActivity()).equals("english")) {
            Context context = LocaleHelper.setLocale(getActivity(), "en");
            resources = context.getResources();

        } else {
            Context context = LocaleHelper.setLocale(getActivity(), "fr");
            resources = context.getResources();
        }


//Change the language here
txtTitle.setText(resources.getString(R.string.filter));