簡體   English   中英

將數據從 Activity 傳遞到帶有 Intent 的廣播接收器

[英]Pass data from Activity to Broadcast Receiver with Intent

我正在通過BroacastReciever在特定時間安排通知。 我想將數據從通知點擊傳遞到活動的newIntent方法。 到目前為止,通知通過后一切正常。 但是,我在將數據從activity傳遞到我的BrocastReceiver class 時遇到問題。 問題是我傳遞的變量存在於我的activity class 中,而不是broadcastReceiver中。 我不知道如何將這些數據輸入我的接收器 class。

活動.java

private void setTimer(String place){
        AlarmManager alarmManager = (AlarmManager) this.getSystemService(Context.ALARM_SERVICE);
        Intent intent = new Intent(this, BroadcastAlarm.class);
        intent.setAction("MY_NOTIFICATION_MESSAGE");
        intent.putExtra("place", place); //this doesn't send data to notification. I want to send place string to notification
        PendingIntent pendingIntent = PendingIntent.getBroadcast(this, 100, intent, PendingIntent.FLAG_UPDATE_CURRENT);
        alarmManager.set(AlarmManager.RTC_WAKEUP, calendar.getTimeInMillis(), pendingIntent);
    }

BroadcastReceiver.java

  @Override
    public void onReceive(Context context, Intent intent) {

  Intent intent1 = new Intent(context, SearchActivity.class);
intent1.putExtra("place", stringNotHere); //if I send data from here it gets available but the problem is that my place data is on my activity class not here
   intent1.setFlags(Intent.FLAG_ACTIVITY_SINGLE_TOP | Intent.FLAG_ACTIVITY_CLEAR_TOP);
        PendingIntent pendingIntent = PendingIntent.getActivity(context, 100, intent1, PendingIntent.FLAG_UPDATE_CURRENT);
        NotificationCompat.Builder notification= new NotificationCompat.Builder(context, NOTIFICATION_CHANNEL_ID);
        notification.setContentIntent(pendingIntent)
    }

如您所見,我需要在BroadcastReceiver上提供活動的place變量。 我怎樣才能做到這一點?

代替:

intent1.putExtra("place", stringNotHere);

有了這個:

String place = intent.getStringExtra("place");
intent1.putExtra("place", place);

暫無
暫無

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

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