簡體   English   中英

將數據從 Activity 傳遞到 BroadcastReceiver

[英]Passing data from Activity to BroadcastReceiver

我有一個BroadcastReceiver ,它為撥出電話的電話號碼添加前綴,前綴由用戶添加。

有沒有辦法將前綴(字符串變量)傳遞給BroadcastReceiver

我的意思是在我的應用程序被殺死后,這個BroadcastReceiver仍然使用用戶想要添加的前綴。

這是我注冊BroadcastReceiver代碼

PackageManager pm  = getApplicationContext().getPackageManager();
ComponentName componentName = new componentName(MyActivity.this,MyBroadcastReceiver.class);
pm.setComponentEnabledSetting(componentName,PackageManager.COMPONENT_ENABLED_STATE_ENABLED,PackageManager.DONT_KILL_APP);

請幫我解決這個問題。

通過意圖,你可以這樣做 -

及格班——

Intent i = new Intent(passing.this, received.class);
Bundle b = new Bundle();
b.putString("keyvalue", "yourprefixvalue");
i.putExtras(b);
startActivity(i);

收到的課程 -

在您的廣播接收器類中包含onReceive方法並具有參數意圖。 這樣它就可以用於從包中獲取結果值。

@Override
public void onReceive(Context context, Intent intent) 
{
    String result = intent.getString("keyvalue");
    // your method
}

試試這個。 我已經像這樣將一些值傳遞給了我的BroadcastReceiver類。

intent = new Intent(getBaseContext(), AlarmReceiver.class);
intent.putExtra("keyvalue",getmessage);

// getmessage 是字符串值

在未決意圖中,您必須使用以下行 - PendingIntent.FLAG_CANCEL_CURRENT);

在廣播接收器中

 String message = context.getStringExtra("keyvalue");

使用這個我將數據從活動傳遞到廣播接收器。

希望這有幫助

通過使用 Intent,我們可以將數據從活動傳遞到廣播接收器。

intent.getExtras().get("testString");

我遇到了同樣的問題,我在 mainfest 文件中注冊了我的廣播接收器,但不知道如何將前綴編號傳遞給我的廣播接收器。 有人知道怎么做嗎?

通過意圖,您可以將字符串值傳遞給廣播接收器

就我而言,我想保留價值。 因此將值保存在一個 volatile 變量中。 像這樣的東西

公共類 GenericDTO {

    public static volatile Map<String, String> dynamicresultSetMap = new HashMap<>();
    public static String getDynamicParamByKey(String key) {
        return (dynamicresultSetMap.get(key))     
    }

}

像這樣保存你的值 GenericDTO.dynamicresultSetMap.put("your_key_here", "your_value_here");

然后在你的廣播接收器里面

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

String value = GenericDTO.getDynamicParamByKey("your_key_here");  

}

暫無
暫無

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

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