如何通过Intent将数据从服务传递到Android中的BroadcastReceiver

问题描述 投票:3回答:2

我正在尝试通过意图从服务中调用BroadcastReceiver。

我在服务文件中按以下方式调用BroadcastReceiver:

    final Handler handler = new Handler();   
    final Runnable r = new Runnable()     {     
    public void run()                  {    

                // code here what ever is required  
                System.out.println("Runnnn");
                counter++;

                Intent i = new Intent();
                i.setAction("Refresh");
                Bundle b = new Bundle();
                b.putInt("Counter", counter);
                i.putExtra("Bundle", b);
                ctx.sendBroadcast(i);

                handler.postDelayed(this, 1000);     


                Toast.makeText(getApplicationContext(), "counter"+counter, Toast.LENGTH_LONG).show();



                }    

          };     
          handler.postDelayed(r, 1000);

BroadcastReceiver中的[onReceive()如下:

public void onReceive(Context context, Intent arg1) {
    System.out.println("OnReceiveeeeee");

    if(arg1.getAction().equalsIgnoreCase("Refresh"))
    {
        System.out.println("Received Intent");
        Bundle b = arg1.getExtras();
        c=b.getInt("Counter");
        System.out.println("Counter in Receiver:::"+c);
    }
}

但是我在onReceive中获得的价值是零。如何在onReceive()方法中获得正确的值?

android android-2.2-froyo
2个回答
1
投票

您使用错误的方式访问。

Bundle b = arg1.getExtras();

您需要按以下方式访问。

Bundle b = intent.getBundleExtra("Bundle");

=================================================

您也可以不使用bundle来编写代码:

服务中

i.putExtra("Counter", counter);

在BroadcastReceiver中]

intent.getIntExtra("Counter", -1); // -1 is defalut value

1
投票

这里是我用来广播注销以提示我所有应用的活动的代码段,请返回登录屏幕时关闭

© www.soinside.com 2019 - 2024. All rights reserved.