Search code examples
androidandroid-activityfirebase-cloud-messagingandroid-alertdialog

How can I send data between an activity and a non-activity class?


I want to send data from a non-activity class to the MainActivity class and to show that data to the user using an AlertDialog. The data is a RemoteMessage from Firebase. I think I can use an interface but I tried some options and didn't work. Any help would be very appreciated. Thanks!

My non-activity class

public class FcmMessageListenerService extends FirebaseMessagingService  {
private static final String NOTIFICATION_CHANNEL_ID = "CITYLINE_DEFAULT_NOTIFICATION_CHANNEL";

public static final String MANDATOR_ID_KEY = "mandator_id";
public static final String MACHINE_SERIAL_NUMBER_KEY = "serial_number";
private iDialogNotificationInterface myInterface;
private  Map<String, String> data;

private Intent openAppIntent;
@Override
public void onMessageReceived(RemoteMessage remoteMessage) {
    data = remoteMessage.getData();
    String mandatorId = data.get("mandatorID");
    String message = data.get("message");
    String serialNumber = data.get("pmID");
    if (message != null) {
        Log.i("OnMessageReceived: ", message);
        sendNotification(mandatorId, message, serialNumber);
        myInterface.sendDialogNotification(mandatorId, message, serialNumber);
    } else {
        Log.e("OnMessageReceived", "null error");
    }
}

@Override
public void onNewToken(String s) {
    super.onNewToken(s);

    SharedPrefsUtils.setBooleanValue(this, DEVICE_TOKEN_REFRESH_EVENT_KEY, true);
    SharedPrefsUtils.removeValueByKey(this, DEVICE_PUSH_NOTIFICATION_TOKEN_KEY);
    Intent intent = new Intent(this, DeviceRegistrationService.class);
    startService(intent);
}

private void sendNotification(String mandatorId, String message, String serialNumber){
    String notificationTitle = this.getString(R.string.app_name);

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

    if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.O && notificationManager != null) {
        NotificationChannel notificationChannel = new NotificationChannel(NOTIFICATION_CHANNEL_ID, "Default Notifications", NotificationManager.IMPORTANCE_HIGH);
        notificationChannel.setDescription("Status Change Notification");
        notificationChannel.enableLights(true);
        notificationChannel.setLightColor(Color.RED);
        notificationChannel.enableVibration(false);

        notificationManager.createNotificationChannel(notificationChannel);
    }


    if (SharedPrefsUtils.getStringValue(this, SharedPrefsUtils.SESSION_COOKIE_DATA_KEY).equals("")) {
        openAppIntent = new Intent(this, LoginActivity.class);
    } else {
        openAppIntent = new Intent(this, MainActivity.class);
    }
    openAppIntent.putExtra(MANDATOR_ID_KEY, mandatorId);
    openAppIntent.putExtra(MACHINE_SERIAL_NUMBER_KEY, serialNumber);
    TaskStackBuilder taskStackBuilder = TaskStackBuilder.create(this);
    taskStackBuilder.addNextIntentWithParentStack(openAppIntent);
    PendingIntent resultPendingIntent = taskStackBuilder.getPendingIntent(0, PendingIntent.FLAG_UPDATE_CURRENT);

    NotificationCompat.Builder notificationBuilder = new NotificationCompat.Builder(getApplicationContext(), NOTIFICATION_CHANNEL_ID)
            .setSmallIcon(R.drawable.ic_cityline)
            .setLargeIcon(BitmapFactory.decodeResource(getResources(), R.drawable.ic_cityline))
            .setStyle(new NotificationCompat.BigTextStyle().bigText(message))
            .setContentTitle(notificationTitle)
            .setContentText(message)
            .setPriority(NotificationCompat.PRIORITY_HIGH)
            .setContentIntent(resultPendingIntent)
            .setAutoCancel(true);

    int notificationId = SharedPrefsUtils.getIntValue(this, SharedPrefsUtils.NOTIFICATION_UNIQUE_ID_KEY);

    if (notificationManager != null) {
        notificationManager.notify(notificationId, notificationBuilder.build());
        notificationId++;
        if (notificationId > 100000)
            notificationId = 0;
        SharedPrefsUtils.setIntValue(this, SharedPrefsUtils.NOTIFICATION_UNIQUE_ID_KEY, notificationId);
    }
}



 String id = mandatorId;
    String msg = message;
    String serial = serialNumber;

    Intent serviceIntent = new Intent(this, MainActivity.class);
    serviceIntent.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
    serviceIntent.putExtra("ID", id);
    serviceIntent.putExtra("MSG", msg);
    serviceIntent.putExtra("SERIAL", serial);

}

MainActivity

private void openNotificationDialog( String mandatorId, String message, String serialNumber){

    Log.i("RAZZ", getApplicationContext().toString());
    String notificationTitle = this.getString(R.string.app_name);
    infoDialog = mBuilder.create();
    mBuilder.setCancelable(true);
    infoDialog.setTitle(notificationTitle);
    infoDialog.setMessage(message);
    infoDialog.setButton(DialogInterface.BUTTON_POSITIVE, "OK", new DialogInterface.OnClickListener() {
        @Override
        public void onClick(DialogInterface dialogInterface, int i) {
            infoDialog.dismiss();
        }
    });

    infoDialog.getWindow().setType(WindowManager.LayoutParams.TYPE_SYSTEM_ALERT);
    infoDialog.show();
}


@Override
    protected void onNewIntent(Intent intent) {
        super.onNewIntent(intent);

    }

@Override
public void sendDialogNotification(String id, String message, String serialNmb) {
    openNotificationDialog(id, message, serialNmb);
}

The interface

public interface iDialogNotificationInterface {
 void sendDialogNotification(String id, String message, String serialNmb);

}


Solution

  • The usage of interface should go as follows:

    public class A implements interfaceA{
    private interfaceA dataMember;
    public void setMember(interfaceA member)
    {
    dataMember = member;
    }
    // rest of class code
    // when needed to notify interfacemember, you call dataMember.function()
    }
    

    in your MainActivity you should do something like

    FcmMessageListenerService obj.setMember(MainActivity.this)
    

    From you code it seems you are using a service and not a class. As it's a service I'd send the data to MainActivity via intent rather than interface.