I am trying to invoke a BroadcastReceiver from a service through intent.
I am calling BroadcastReceiver as follows in my service file :
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);
onReceive()
in BroadcastReceiver is as follows:
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);
}
}
But I am getting value in onReceive as zero. How can I get right value in onReceive() method?
You are accessing in wrong way.
Bundle b = arg1.getExtras();
You need to access as follow.
Bundle b = intent.getBundleExtra("Bundle");
================================================
You can alternatively write your code without using bundle also:
In Service
i.putExtra("Counter", counter);
In BroadcastReceiver
intent.getIntExtra("Counter", -1); // -1 is defalut value