Push notification in hybrid app

Asked

Viewed 493 times

-1

I’m creating a hybrid Android app, which is actually a webview running a system, hosted on some server, made in php.

I need to deploy a notification system (Push Notification) that sends personalized notifications to specific users registered on the system.

A PHP Script will be run from time to time on the server and this will analyze to which users will send a notification based on some rules I will put.

Is it possible to do? What is the best tool to use? Would anyone have any tutorial to indicate?

1 answer

0

Whoa, that’s all right!?

Even being just a webView on Android, vc can implement some classes and make native:

  1. Class to make a request to the server and save the mobile id
  2. Other Box to receive notification.

First do the Firebase Imports in build.Gradle (Module: app), assuming that you are already using firebase in your project, because there are other basic steps needed to work (those that firebase teaches you to configure when you create the project in the console):

implementation 'com.google.firebase:firebase-messaging:12.0.1'

You will need these following parameters in your manifest within the application tag (along with the activitys declaration).

<!--notificação -->
<service
    android:name=".FCM.FCMInstanceIdService">
    <intent-filter>
        <action android:name="com.google.firebase.INSTANCE_ID_EVENT"/>
    </intent-filter>
</service>
<service
    android:name=".FCM.FCMService" >
    <intent-filter>
        <action android:name="com.google.firebase.MESSAGING_EVENT"/>
    </intent-filter>
</service>

Next you will need to create the classes for the FCM (Firebase Cloud Messaging)

Fcminstanceidservice.java: to generate the device’s unique token. This write token, is to write to my own server, in case you do not use delete this class):

/**
 * Criado por Leonardo Figueiredo em 20/08/2018.
 */
public class FCMInstanceIdService extends FirebaseInstanceIdService {

public static String TAG = "FirebaseLog";
String refreshedToken;

@Override
public void onTokenRefresh() {
    super.onTokenRefresh();
    refreshedToken = FirebaseInstanceId.getInstance().getToken();
    gravaToken();
    Log.d(TAG, "Token: " + refreshedToken);
}

public void gravaToken() {
    TokenModel tokenModel = new TokenModel();
    tokenModel.setTokenDevice(refreshedToken);
    tokenModel.setSo("Android");

    Call<TokenModel> call = new RetrofitConfig().getApiCandidato().gravaToken(tokenModel.getTokenDevice(), tokenModel.getSo());
    call.enqueue(new Callback<TokenModel>()
    {
        @Override
        public void onResponse(Call<TokenModel> call, Response<TokenModel> response) {
            //sucesso
        }

        @Override
        public void onFailure(Call<TokenModel> call, Throwable t) {
            //falha
        }
    });
    }
}

Now you need the Fcmservice.java class: you are responsible for receiving and handling the notification.

/**
 * Criado por Leonardo Figueiredo em 20/08/2018.
 */
public class FCMService extends FirebaseMessagingService {

public static String TAG = "FirebaseLog";

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

    Log.v(TAG, "recebeu mensagem do firebase");

    //verifica se recebeu alguma notificacao
    if (remoteMessage.getNotification() != null) {
        String mensagem = remoteMessage.getNotification().getBody();

        Intent intent = new Intent(getBaseContext(), PrincipalActivity.class);

        PendingIntent pendingIntent = PendingIntent.getActivity(getBaseContext(), 0, intent, 0);

        NotificationCompat.Builder builder = new NotificationCompat.Builder(getBaseContext())
                .setContentTitle(String.valueOf(getResources().getString(R.string.app_name)))
                .setSmallIcon(R.drawable.ic_notificacao)
                .setLargeIcon(BitmapFactory.decodeResource(getResources(), R.drawable.ic_logo_color))
                .setDefaults(Notification.DEFAULT_VIBRATE | Notification.DEFAULT_SOUND)
                .setContentIntent(pendingIntent)
                .setStyle(new NotificationCompat.BigTextStyle().bigText(mensagem))
                .setContentText(mensagem)
                .setAutoCancel(true);

        NotificationManager notificationManager = (NotificationManager) getSystemService(NOTIFICATION_SERVICE);
        notificationManager.notify(99, builder.build());
        Log.d(TAG, "Menssagem: " + remoteMessage.getNotification().getBody());
    }
}
}

Now just go to your firebase console, go to the Zoom -> Cloud Messaging menu. If you want to send directly by your scrip, see this link step by step, so that Automatize and send by your script: https://gist.github.com/rolinger/d6500d65128db95f004041c2b636753a

Fill in the data and send it and be happy.

NOTE: Place a breakpoint in the Fcminstanceidservice class and check if it generated a hash, this is your device’s unique id (only happens the first time you install the App).

Before sending, place a breakpoint in the Fcmservice class, as this is where the message will arrive.

Browser other questions tagged

You are not signed in. Login or sign up in order to post.