Android Programming Tutorials

(Romina) #1
Messages From The Great Beyond

We create a fresh Intent on our defined action, populate our variable data


as "extras", and call sendBroadcast() to send it off.


Step #2: Catch and Use the Intent


Receiving a broadcast Intent is similarly simple.


First, we need to decide when we want our receiver to be active and alive. In


some situations, where the broadcasts are merely advisory, we can enable


them in onResume() and disable them in onPause(), so we consume no CPU


time processing broadcasts when our activity is not visible. In this case, so


we do not miss an all-important tweet, we should ensure the receiver is


active whenever our account registered with PostMonitor is active.


First, we need to register a receiver in onCreate() before we bind to our


service:


registerReceiver(receiver, new IntentFilter(PostMonitor.STATUS_UPDATE));

And, we need to unregister said receiver after we unbind from the service:


unregisterReceiver(receiver);

Of course, none of this will work without a receiver itself. We want the


receiver to do what our callback object does, except that instead of getting


the data as method parameters, we get it as "extras" on the broadcast


Intent. Here is one implementation of receiver that will accomplish this


end:


private BroadcastReceiver receiver=new BroadcastReceiver() {
public void onReceive(Context context,
final Intent intent) {
String friend=intent.getStringExtra(PostMonitor.FRIEND);
String createdAt=intent.getStringExtra(PostMonitor.CREATED_AT);
String status=intent.getStringExtra(PostMonitor.STATUS);

adapter.insert(new TimelineEntry(friend, createdAt, status),
0 );
}
};

273
Free download pdf