如何从广播接收器中的活动传递值?

时间:2011-10-21 07:34:26

标签: android android-manifest

如果通过清单文件注册广播接收器,如何从广播接收器中的活动读取数据?请帮忙......

3 个答案:

答案 0 :(得分:3)

首先,您需要将数据存储在SharedPreferences中,然后将它们放入广播接收器中。

您可以在清单文件中使用以下代码:

<receiver android:name=".YourReceiver">
    <intent-filter>
        <action android:name="android.intent.action.BOOT_COMPLETED" />
    </intent-filter>
</receiver>

在代码中你可以使用:

public class YourReceiver extends BroadcastReceiver {

    @Override
    public void onReceive(Context context, Intent intent) {
        if(intent.getAction().equals("android.intent.action.BOOT_COMPLETED"))
        {
            //updateWidget();
            SharedPreferences prfs = context.getSharedPreferences("defaul", 0);
            boolean bb=prfs.getBoolean("eer",false);
            alarm=context.getSharedPreferences("def", 0).getString("alarm_time","");
        }
    }
}

答案 1 :(得分:0)

如果您通过代码呼叫广播接收器,那么您可以像下面那样调用它

Intent intent1 = new Intent(context, TimeAlarm.class)
intent1.putExtra("var1", "value");
PendingIntent pendingIntent = PendingIntent.getBroadcast(context, 0,
             intent1, PendingIntent.FLAG_ONE_SHOT);

答案 2 :(得分:0)

没有从活动到接收器类的值获得扩展广播接收器

Intent inte = new Intent();
    inte.setAction("MyBroadcast");

    inte.putExtra("Phone_number1", phoo1);
    inte.putExtra("Phone_number2",phoo2);
    inte.putExtra("Phone_number3", phoo3);
    sendBroadcast(inte);

Bundle extras = intent.getExtras();
        if (extras != null) {

          String phoo1 = (String) extras.get("Phone_number1");//getting null value
          String phoo2 = (String) extras.get("Phone_number2");
          String phoo3 = (String) extras.get("Phone_number3");
          System.out.println("Value Of Contact Numbers Outside intent in Reciver");
          System.out.println("Value Of First Contact Number"+phoo1);
          System.out.println("Value Of Second Contact Number"+phoo2);
          System.out.println("Value Of Third Contact Number"+phoo3);
}