Reputation: 13349
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?
Upvotes: 3
Views: 6465
Reputation: 4260
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
Upvotes: 1
Reputation: 14438
here's snippets of the code i use to broadcast a logout to prompt all my apps Activities to close when going back to the login screen
logoutBroadcastReceiver lbr;
@Override
public void onResume(){
...
// register the broadcast receiver
IntentFilter intentfilter = new IntentFilter("com.on3x.action.DO_LOGOUT");
lbr = new logoutBroadcastReceiver();
registerReceiver(lbr,intentfilter);
super.onResume();
...
}
// broadcast receiver grabbing the "test" bundled extra
public class logoutBroadcastReceiver extends BroadcastReceiver {
@Override
public void onReceive(Context context, Intent intent) {
Log.d(getString(R.string.app_name), "broadcast string: " + intent.getStringExtra("string_example"));
Log.d(getString(R.string.app_name), "extra!: " + intent.getIntExtra("int_example",0));
finish();
}
}
// broadcast the intent to logout when logout button clicked
// put the extra "test" in the bundle
public void onClickLogout(View _view) {
Intent i = new Intent("com.on3x.action.DO_LOGOUT");
i.putExtra("string_example", "here is a broadcasted string");
i.putExtra("int_example", 100);
sendBroadcast(i);
}
I hope that code helps you out getting yours working?
Edit: updated to use putExtra()
and getStringExtra()/getIntExtra()
Upvotes: 1