簡體   English   中英

如何在活動類和非活動類之間發送數據?

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

我想將數據從非活動類發送到 MainActivity 類,並使用 AlertDialog 向用戶顯示該數據。 數據是來自 Firebase 的 RemoteMessage。 我想我可以使用一個界面,但我嘗試了一些選項並沒有奏效。 任何幫助將不勝感激。 謝謝!

我的非活動課

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);

}

主要活動

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)

從您的代碼看來,您使用的是服務而不是類。 因為它是一項服務,所以我會通過意圖而不是接口將數據發送到 MainActivity。

您可以使用 Sharepreference 在 Non-Activity 類中存儲數據,然后將數據提取到您的 Activity 類中,反之亦然。

在非活動類

初始化

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

在活動類

檢索數據

SharedPreferences pref = getApplicationContext().getSharedPreferences("MyPref", 0);
boolean isNotificationReceived = pref.getBoolean(IsNotificationReceived, false);

在 onResume 上檢查 isNotificationReceived 或當您初始化該類時,如果值為 true,則調用對話框並顯示適當的消息

確保在打開對話框時將 sharedpref isNotificationReceived 編輯為 false,否則無論何時初始化類,無論是否收到通知,對話框都會打開

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM