将数据从Activity传递到BroadcastReceiver

时间:2012-02-17 04:12:56

标签: android broadcastreceiver

我有一个BroadcastReceiver,它为拨打电话的电话号码添加前缀,前缀由用户添加。

有没有办法将Prefix(字符串变量)传递给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);

请帮我解决这个问题。

6 个答案:

答案 0 :(得分:5)

通过意图你可以这样做 -

传递课程 -

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

收到课程 -

在您的广播接收器类中包含onReceive方法并具有参数意图。这样它就可以用来从bundle中获取结果值。

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

试一试。我已经将一些值传递给我的BroadcastReceiver类了。

答案 1 :(得分:2)

通过使用Intent,我们可以将数据从活动传递到广播接收器。

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

答案 2 :(得分:2)

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

// getmessage是字符串值

在未决意图中你必须使用以下线 -           PendingIntent.FLAG_CANCEL_CURRENT);

在broadcastreceiver中

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

使用此功能将数据从活动传递到广播接收器。

希望这有用

答案 3 :(得分:1)

通过intent你可以将字符串值传递给广播接收器

答案 4 :(得分:0)

我遇到同样的问题,我在清单文件中注册了我的广播接收器,但是不知道如何将预修复号码传递给我的广播接收器。有谁知道怎么做?

答案 5 :(得分:-1)

就我而言,我想保留其价值。因此,将值保存在一个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");  

}
相关问题