From: http://www.apkbus.com/forum.php? MoD = viewthread & tid = 20282.
I recently learned about the Sina Weibo Open Platform and implemented an application. I monitored Weibo data through the backend service. After I found that the data was updated, I notified the foreground program and sent the blog data list to the foreground activity.
The broadcastreceiver object is used to register a broadcast in the activity and service respectively, and control data exchange between the foreground and the backend by sending different broadcasts, and pass the complex custom object type to activity through the serializable object.
The program snippet is as follows: backend monitoring of Weibo Service
// Inherit from the subclass of the service
Copy code
Andriodfocusme main UI Activity
Public class andriodfocusme extends activity implements runnable {
/** Called when the activity is first created .*/
Datareceiver; // broadcastreceiver object
Progressbar;
Listview;
Int performance_stop_service = 0;
Int performance_reset_service = 1;
Int pai_get_weibo_data = 2;
@ Override
Public void oncreate (bundle savedinstancestate ){
Super. oncreate (savedinstancestate );
Setcontentview (R. layout. weibodataview );
Button beginouathbtn = (button) findviewbyid (R. Id. button_weibo );
Button endbtn = (button) findviewbyid (R. Id. flashdata );
Listview = (listview) findviewbyid (R. Id. weibodatalist );
Progressbar = (progressbar) findviewbyid (R. Id. wbprogressbar );
Progressbar. setvisibility (view. Invisible );
Beginouathbtn. setonclicklistener (New button. onclicklistener ()
{
@ Override
Public void onclick (view V)
{
Intent myintent = new intent (andriodfocusme. This, weiboservice. Class );
Andriodfocusme. This. startservice (myintent); // send intent to start the service
Progressbar. setvisibility (view. Visible );
}
});
Endbtn. setonclicklistener (New button. onclicklistener ()
{
@ Override
Public void onclick (view V)
{
Intent intent = new intent (); // create an intent object
Intent. setaction ("weibo4andriod. focusme. weiboservice ");
Intent. putextra ("cmd", pai_get_weibo_data );
Sendbroadcast (intent); // send Broadcast
}
});
}
Private class datareceiver extends broadcastreceiver {// inherit from the subclass of broadcastreceiver
Arraylist @ Override
Public void onreceive (context, intent) {// override the onreceive Method
Try {
Bundle bundle = intent. getextras ();
// Deserialization, rebuilding data locally
Serializable DATA = bundle. getserializable ("weibodata ");
If (Data! = NULL ){
Weibodatalist = (arraylist
Simpleadapter mschedule = new simpleadapter (andriodfocusme. This, weibodatalist,
R. layout. weibodata_itemview,
New String [] {"createdat", "weibotext "},
New int [] {R. Id. Title, R. Id. weibotext });
Listview. setadapter (mschedule );
} Else {
Return;
}
} Catch (exception e ){
Log. V ("test", E. tostring ());
}
Progressbar. setvisibility (view. Gone );
}
}
@ Override
Protected void onstart () {// rewrite the onstart Method
// Register the broadcast for receiving service transfer
Datareceiver = new datareceiver ();
Intentfilter filter = new intentfilter (); // create an intentfilter object
Filter. addaction ("weibodatachanged ");
Registerreceiver (datareceiver, filter); // register broadcast Receiver
Icationicationmanager m_notificationmanager = (notificationmanager) getsystemservice (icationication_service );
M_icationicationmanager.cancel (R. Id. textview01 );
Super. onstart ();
}
@ Override
Protected void onstop () {// rewrite the onstop Method
Unregisterreceiver (datareceiver );
Finish ();
Super. onstop ();
}
}
Copy code
Through this example, you can basically understand the usage of commonly used Android components, hoping to help readers, and welcome to provide valuable comments.
// Inherit from the subclass of the service
Public class weiboservice extends Service {
// Used to determine whether Weibo has an update flag
Private Boolean newdateflag = false;
// Weibo object
Weibo;
Icationicationmanager m_notificationmanager;
Notification m_notification;
Pendingintent m_pendingintent;
// Inherits from the broadcastreceiver object to obtain the Command sent by the activity.
Commandreceiver cmdreceiver;
Boolean flag;
// Service command list
Int performance_stop_service = 0;
Int performance_reset_service = 1;
Int pai_get_weibo_data = 2;
@ Override
Public void oncreate () {// override the oncreate Method
Flag = true;
// Initialize Sina Weibo open API
System. setproperty ("weibo4j. oauth. consumerkey", Weibo. consumer_key );
System. setproperty ("weibo4j. oauth. consumersecret", Weibo. consumer_secret );
Weibo = oauthconstant. getinstance (). getweibo ();
// Enter the two strings that Sina gave you at registration.
Weibo. settoken ("xxxxxx", "XXXXXXXX ");
M_notification = new notification ();
Super. oncreate ();
}
@ Override
Public ibinder onbind (intent) {// rewrite the onbind Method
// Todo auto-generated method stub
Return NULL;
}
// When the foreground activity calls startservice, this method is automatically executed
@ Override
Public int onstartcommand (intent, int flags, int startid) {// override the onstartcommand Method
Cmdreceiver = new commandreceiver ();
Intentfilter filter = new intentfilter (); // create an intentfilter object
// Register a broadcast to receive commands sent by the activity and Control Service behaviors, such as sending data and stopping the service.
// String: weibo4andriod. focusme. weiboservice is custom and has no requirements. Generally, use the package name + file name to avoid duplication.
// If it is repeated, the android system will display a list of service programs that receive the same action at runtime for users to choose from.
// Register the program for the same action. Can the program receive broadcasts at the same time? To be tested .....
Filter. addaction ("weibo4andriod. focusme. weiboservice ");
// Register the broadcast Receiver
Registerreceiver (cmdreceiver, filter );
Dojob (); // call the method to start the thread
Return super. onstartcommand (intent, flags, startid );
}
// Method:
Public void dojob (){
New thread (){
Public void run (){
Arraylist While (FLAG ){
Try {// sleep for a period of time
Thread. Sleep (5000 );
}
Catch (exception e ){
E. printstacktrace ();
}
Data = getweibodata ();
If (isnewdateflag ()){
Sendnotification ("XXXXXXXXX ");
}
Setnewdateflag (false );
}
}
}. Start ();
}
// Receive commands sent from activity
Private class commandreceiver extends broadcastreceiver {
@ Override
Public void onreceive (context, intent ){
Int cmd = intent. getintextra ("cmd",-1); // get extra information
If (cmd = cmd_stop_service) {// if the message sent is to stop the service
Flag = false; // stop the thread
Stopself (); // stop the service
}
If (cmd = pai_reset_service) {// if the message is sent, refresh the service.
}
If (cmd = pai_get_weibo_data) {// If the sent message is to send Weibo data
Sendweibodata ();
}
}
}
@ Override
Public void ondestroy () {// override the ondestroy Method
This. unregisterreceiver (cmdreceiver); // cancel the registered commandreceiver.
Super. ondestroy ();
}
/*
* Get Weibo data
*/
Public arraylist
Arraylist = New arraylist
Hashmap <string, string> Map
= New hashmap <string, string> ();
List <status> friendstimeline;
Try {
Friendstimeline = Weibo. getusertimeline ();
For (status: friendstimeline ){
Ofchecknewweibo (status. getcreatedat ());
Map = new hashmap <string, string> ();
Map. Put ("createdat", status. getcreatedat (). tostring ());
Map. Put ("weibotext", status. gettext ());
Weibodatalist. Add (MAP );
}
}
Catch (weiboexception e ){
E. printstacktrace ();
}
Return weibodatalist;
}
Private void ofchecknewweibo O (date createdat ){
// Todo auto-generated method stub
Date weibolastdate;
Editor editor;
// Read and record system configuration information through sharedpreference
Sharedpreferences preferences = getsharedpreferences ("weibodate", context. mode_private );
Weibolastdate = sparsed (preferences. getstring ("lastdate", "mon Nov 29 16:08:43 + 0800 1900 "));
If (weibolastdate. Before (createdat )){
Editor = preferences. Edit ();
Editor. putstring ("lastdate", createdat. tostring ());
Editor. Commit ();
Setnewdateflag (true );
}
}
/**
* Send notifications with Weibo updates
* @ Param sendtext
*/
Public void sendnotification (string sendtext ){
Intent intent = new intent (weiboservice. This, andriodfocusme. Class );
M_icationication.icon = R. drawable. Icon;
M_icationication.tickertext = sendtext;
M_icationication.defaults = notification. default_sound;
M_pendingintent = pendingintent. getactivity (weiboservice. This, 0, intent, 0 );
M_icationication.setlatesteventinfo (weiboservice. This, "title", "text", m_pendingintent );
M_icationicationmanager = (notificationmanager) getsystemservice (icationication_service );
M_icationicationmanager.policy (R. Id. textview01, m_notification );
}
/**
* String to date
* @ Param date
* @ Return
*/
// Compare whether the data is new
Public date sparsed (string date ){
String format = "eee Mmm dd hh: mm: ss z yyyy ";
Simpledateformat dateformat = new simpledateformat (format, locale. US );
Date parsedate = NULL;
Try {
Parsedate = dateformat. parse (date );
} Catch (parseexception e ){
// Todo auto-generated Catch Block
E. printstacktrace ();
}
Return parsedate;
}
Public Boolean isnewdateflag (){
Return newdateflag;
}
Public void setnewdateflag (Boolean newdateflag ){
This. newdateflag = newdateflag;
}
// Send Weibo data list
Public void sendweibodata (){
// Todo auto-generated method stub
Arraylist
Data = getweibodata ();
Intent intent = new intent (); // create an intent object
Bundle bundle = new bundle ();
// Serialize the list and recreate data locally after sending
Bundle. putserializable ("weibodata", data );
Intent. setaction ("weibodatachanged ");
Intent. putextras (bundle );
Sendbroadcast (intent); // send Broadcast
}
}
Copy code