如何在 activity 和非 activity class 之间发送数据?
How can I send data between an activity and a non-activity class?
我想将数据从非 activity class 发送到 MainActivity class 并使用 AlertDialog 向用户显示该数据。数据是来自 Firebase 的 RemoteMessage。我想我可以使用一个界面,但我尝试了一些选项但没有用。任何帮助将不胜感激。谢谢!
我非activityclass
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);
}
界面
public interface iDialogNotificationInterface {
void sendDialogNotification(String id, String message, String serialNmb);
}
接口使用方法如下:
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()
}
在您的 MainActivity 中,您应该做类似
的事情
FcmMessageListenerService obj.setMember(MainActivity.this)
从您的代码看来,您使用的似乎是一项服务,而不是 class。因为它是一项服务,所以我会通过意图而不是接口将数据发送到 MainActivity。
您可以使用 Sharepreference 将数据存储在 Non-Activity class 中,然后将数据提取到您的 Activity class 中,反之亦然。
在Non-Activityclass
初始化
SharedPreferences pref = getApplicationContext().getSharedPreferences("MyPref", 0); // 0 - for private mode
Editor editor = pref.edit();
存储数据
editor.putBoolean("IsNotificationReceived", true); // Storing boolean as true when you receive the notifiaction also store the body or message into this sharedpref form the notification
editor.commit(); // commit changes !Important line to save data into the sharedpreference
在Activityclass
正在检索数据
SharedPreferences pref = getApplicationContext().getSharedPreferences("MyPref", 0);
boolean isNotificationReceived = pref.getBoolean(IsNotificationReceived, false);
在 onResume 或初始化时检查 isNotificationReceived class 如果值为真,则调用对话框并显示适当的消息
确保在打开对话框时将 sharedpref isNotificationReceived 编辑为 false,否则无论何时初始化 class 无论是否收到通知,对话框都会打开
我想将数据从非 activity class 发送到 MainActivity class 并使用 AlertDialog 向用户显示该数据。数据是来自 Firebase 的 RemoteMessage。我想我可以使用一个界面,但我尝试了一些选项但没有用。任何帮助将不胜感激。谢谢!
我非activityclass
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);
}
界面
public interface iDialogNotificationInterface {
void sendDialogNotification(String id, String message, String serialNmb);
}
接口使用方法如下:
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()
}
在您的 MainActivity 中,您应该做类似
的事情FcmMessageListenerService obj.setMember(MainActivity.this)
从您的代码看来,您使用的似乎是一项服务,而不是 class。因为它是一项服务,所以我会通过意图而不是接口将数据发送到 MainActivity。
您可以使用 Sharepreference 将数据存储在 Non-Activity class 中,然后将数据提取到您的 Activity class 中,反之亦然。
在Non-Activityclass
初始化
SharedPreferences pref = getApplicationContext().getSharedPreferences("MyPref", 0); // 0 - for private mode
Editor editor = pref.edit();
存储数据
editor.putBoolean("IsNotificationReceived", true); // Storing boolean as true when you receive the notifiaction also store the body or message into this sharedpref form the notification
editor.commit(); // commit changes !Important line to save data into the sharedpreference
在Activityclass
正在检索数据
SharedPreferences pref = getApplicationContext().getSharedPreferences("MyPref", 0);
boolean isNotificationReceived = pref.getBoolean(IsNotificationReceived, false);
在 onResume 或初始化时检查 isNotificationReceived class 如果值为真,则调用对话框并显示适当的消息
确保在打开对话框时将 sharedpref isNotificationReceived 编辑为 false,否则无论何时初始化 class 无论是否收到通知,对话框都会打开