从Activity传递数据到BroadcastReceiver

3

我有一个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);

关于这个问题,请帮我解决。

5个回答

7

通过意图,您可以这样做 -

传递类 -

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

Received Class -

在你的广播接收器类中包含onReceive方法,并带参数intent。因此,它可以用于从bundle获取结果值。

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

尝试这个。我已经像这样向我的 Broadcast Receiver 类传递了一些值。

感谢您的清晰回答。但是,我仍然有一个问题,就是我无法将我的广播接收器作为活动启动。我使用了PackageManager来启用它。这样即使我的应用程序被杀死也能够工作。 - PhatHV
抱歉,伙计。我没有处理过那个。所以我什么也不知道。无论如何,为好的概念点赞。 - Galaxy S2

3
使用Intent,我们可以将数据从活动传递到广播接收器。
intent.getExtras().get("testString");

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

// getmessage是一个字符串值

在PendingIntent中,您需要使用以下行 - PendingIntent.FLAG_CANCEL_CURRENT);

在BroadcastReceiver中

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

使用这个方法,我可以从活动中将数据传递到广播接收器。
希望对您有所帮助。

2

我遇到了同样的问题,我在manifest文件中注册了我的BroadcastReceiver,但不知道如何将前缀号传递给我的BroadcastReceiver。有人知道该怎么做吗?


2

通过意图,您可以将字符串值传递给广播接收器。


网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接