Communication between applications in Android software development (18)

Source: Internet
Author: User
Communication between applications in Android software development

If the original Yusong Momo article is reprinted, please note: It is reprinted to my independent domain name blogYusong Momo program Research Institute, Original address: http://www.xuanyusong.com/archives/141


In Android development, the interfaces for communication between programs are rich. This example mainly introduces how to communicate between programs and how to communicate with each other.

1. Use handler to transmit messages

Handler can think of it as a subthread of the main thread (ui thread). It can send data to the main thread (ui thread) to update the main thread (ui thread) handler is a sub-thread, so its time-consuming operations do not block the main thread, everyone knows that in Android development, if the main thread is blocked for more than five seconds in the Code, the system will prompt ANR (the system prompts forced shutdown) therefore, in terms of time-consuming operations, we can consider opening a sub-thread to avoid ANR. The handler will send messages to the main thread and arrange them in the form of queues to wait for the main thread to update the UI logic.

The following example illustrates how to use handler to send messages to update the UI display content of the main thread. After clicking the button, the handler sends messages to update the display time of the UI thread every second until the display time is updated to 10. end the thread.
 

Public class handleractivity extends activity implements runnable {/** Update Time **/public final static int update_time = 0; /** Update time successful **/public final static int update_completed = 1;/** record display time exceeds 10 seconds to end the thread **/private int mshownumber = 0; /** start timer button **/private button mbutton = NULL;/** timer display content **/private textview mtextview = NULL; /** thread **/private thread mthread = NULL;/** mark of thread closure **/private Boolean mrunning = false; handler = new handler () {@ overridepublic void handlemessage (Message MSG) {bundle = MSG. getdata (); // get its value string number = bundle through the key name. getstring ("Number"); // MSG. what is the message number received by handler switch (MSG. what) {Case update_time: mtextview. settext ("updating time" + number); break; Case update_completed: mtextview. settext ("updated"); break;} super. handlemessage (MSG) ;}}; @ override protected void oncreate (bundle savedinstancestate) {setcontentview (R. layout. handler);/** get the button and textview object **/mbutton = (button) findviewbyid (R. id. button0); mtextview = (textview) findviewbyid (R. id. textview0); mthread = new thread (this); mbutton. setonclicklistener (New onclicklistener () {@ override public void onclick (view arg0) {/** click the button to start thread timing **/mrunning = true; mthread. start () ;}}); mtextview. settext ("click to start updating time"); super. oncreate (savedinstancestate);} public void showdialog (string) {alertdialog. builder = new alertdialog. builder (handleractivity. this); builder. seticon (R. drawable. icon); builder. settitle (string); builder. setpositivebutton ("OK", new dialoginterface. onclicklistener () {public void onclick (dialoginterface Diener, int whichbutton) {finish () ;}}); builder. show () ;}@ override public void run () {While (mrunning) {try {mshownumber ++; /** put the required data into the bandle **/bundle bandle = new bundle (); bandle. putstring ("Number", String. valueof (mshownumber )); /** set the ID of this message to the Update Time ** // ** write the bandle to the Message ** // ** and finally send the message **//** mshownumber is earlier than 10; otherwise, the update is completed. **/message MSG = new message (); if (mshownumber <= 10) {MSG. what = update_time;} else {mrunning = false; MSG. what = update_completed;} MSG. setdata (bandle); handler. sendmessage (MSG); thread. sleep (1000);} catch (interruptedexception e) {e. printstacktrace ();}}}}

2. Notification bar Information
The notice bar displays a message to the user on the screen, but does not interrupt the content that the user is reading, unless you manually pull down the notice bar. The advantage of Federation is that it does not affect user operations, for example, when a user is reading very important information, it is very inappropriate to open an activity for him directly because it directly affects his current operation behavior. We recommend that you use the notice bar when users are interrupted during development.


The activation notification bar pops up on the screen.

When you pull the notice bar, the corresponding information will appear.

Public class icationicationactivity extends activity {notificationmanager mmanager = NULL; Notification = NULL; @ override protected void oncreate (bundle savedinstancestate) {setcontentview (R. layout. notification); // The manager object for receiving notification messages. mmanager = (icationicationmanager) getsystemservice (icationication_service) is responsible for managing the sending and clearing of notification messages ); // create notification object parameters to indicate the time when the title of the icon displayed in the notification bar is displayed. Notification = new notification (R. drawable. jay, "android Professional Development Group", system. currenttimemillis (); // when you click in the notification bar, the notification automatically disappears. flags = notification. flag_auto_cancel; // set the new activityintent intent = new intent (this, myshowactivity. class); intent. setflags (intent. flag_activity_clear_top | intent. flag_activity_new_task); // you can use bundle to include some data. Here, the string is passed to bundle = new bundle (); bundle. putstring ("name", "jump from notification"); intent. putextras (bundle); // set the content displayed in the notification bar to pendingintent contentintent = pendingintent. getactivity (this, R. string. app_name, intent, pendingintent. flag_update_current); notification. setlatesteventinfo (this, "android Professional Development Group", "QQ Group 164257885", contentintent); button button0 = (button) findviewbyid (R. id. button0); button0.setonclicklistener (New onclicklistener () {@ override public void onclick (view arg0) {// enable this notification to notify mmanager. Y (0, notification) ;}}); button button1 = (button) findviewbyid (R. id. button1); button1.setonclicklistener (New onclicklistener () {@ override public void onclick (view arg0) {// close this Notification to mmanager. cancelall () ;}}); super. oncreate (savedinstancestate );}}

3. send and receive broadcasts

In Android development, if you need to communicate between two completely unrelated programs, you can use the send broadcast and receive broadcast mechanism, for example, program a sends a broadcast program B and receives something to achieve mutual communication.

Call sendbroadcast () to pass in intent to send Broadcast

Public class broadcastactivity extends activity {button mbutton0 = NULL; button mbutton1 = NULL; @ override protected void oncreate (bundle savedinstancestate) {setcontentview (R. layout. broadcast); mbutton0 = (button) findviewbyid (R. id. button0); mbutton0.setonclicklistener (New onclicklistener () {@ override public void onclick (view arg0) {intent = new intent (myservice. send_ OK _message); intent. putextra ("name", "you sent OK broadcast"); sendbroadcast (intent) ;}); mbutton1 = (button) findviewbyid (R. id. button1); mbutton1.setonclicklistener (New onclicklistener () {@ override public void onclick (view arg0) {intent = new intent (myservice. send_cancle_message); intent. putextra ("name", "you sent the cancle broadcast"); sendbroadcast (intent) ;}}); // start service intent I = new intent (this, myservice. class); startservice (I); super. oncreate (savedinstancestate );}}


To receive a broadcast, we enable a service to receive the broadcast through broadcastreceiver in the service. The premise is that the broadcast to be received must be registered in onstart () in androidmanifest. in XML, you can filter only the broadcasts to be received,

<service android:name=".MyService"><intent-filter><action android:name="cn.m15.xys.MyService"></action></intent-filter><intent-filter><action android:name="send.ok.message" /><action android:name="send.cancle.message" /></intent-filter></service>


Register the two broadcasts required by the program in onstart ().

Public class myservice extends Service {public final static string send_ OK _message = "send. OK. message "; public final static string send_cancle_message =" send. cancle. message "; private broadcastreceiver mybroadcast = new broadcastreceiver () {@ overridepublic void onreceive (context, intent) {string action = intent. getaction (); If (action. equals (send_ OK _message) {toast. maketext (context, "received a broadcast as" + send_ OK _message, toast. length_long ). show ();} else if (action. equals (send_cancle_message) {toast. maketext (context, "received a broadcast as" + send_cancle_message, toast. length_long ). show () ;}};@ override public void oncreate () {super. oncreate () ;}@ override public void onstart (intent, int startid) {// register the two Broadcast intentfilter myfilter = new intentfilter (); myfilter. addaction (send_ OK _message); myfilter. addaction (send_cancle_message); this. registerreceiver (mybroadcast, myfilter); super. onstart (intent, startid) ;}@ override public ibinder onbind (intent arg0) {return NULL ;}}

Note that if the service is unavailable, we cannot receive the broadcast. Therefore, we must ensure that the service is enabled when receiving the broadcast, in the preceding example, the service is enabled when activity is enabled, but if the user turns off the mobile phone and then starts the system, in this case, the service is not enabled, which is very dangerous. At this time, scrvice will not receive any message, unless the user enters the activity again, it will help him open scrvice, so we can directly open scrvice, the specific implementation method is as follows:

Register a boot broadcast in androidmanifest. xml. The broadcast system will only be sent once when it is started. Therefore, if we receive this broadcast, we can check whether the mobile phone is in the boot status.

<receiver android:name=".MyBootReceiver" >       <intent-filter>          <action android:name="android.intent.action.BOOT_COMPLETED" />      </intent-filter>    </receiver>

Note: add permissions

<uses-permission android:name="android.permission.RECEIVE_BOOT_COMPLETED" />


After receiving the boot broadcast in broadcastrecevier and enabling the service, you can start the service at startup.

Public class mybootreceiver extends broadcastreceiver {/** boot broadcast **/static final string boot_completed = "android. intent. action. boot_completed "; @ override public void onreceive (context, intent) {/** enable service **/If (intent. getaction (). equals (boot_completed) {intent I = new intent (context, myservice. class); context. startservice (I );}}}

3. jump between activity and Activity

In the development of software applications, there will certainly be multiple activities so that there will be a relationship between them and the implementation method of the jump or use intent and startactivity, of course, data can be transferred to the previous hop. For example, from A to B, some data in a can be passed to B through intent.

After reading the following code, you will find that intent and bandle are basically the same way of passing values. Why do they have to be divided into two parts? Indeed, the two of them transmit very similar numerical values. The difference between them is that intent transfers scattered data in the past, while bundle transfers scattered data into bundle and passes it in the past. For example, we have three activity. B .C needs to pass data of A to B and then to C, if intent is used for one-by-one transmission, it must be passed to Class B one by one in Class A, and then all values are obtained in Class B and passed to Class C one by one. This is very troublesome, but if it is bundle, Class B directly pass the bundler to C without having to obtain specific values one by one and then directly obtain the parsed values in Class C.

Transfer

/** Transfer value between activities **/button botton3 = (button) findviewbyid (R. id. button3); botton3.setonclicklistener (New onclicklistener () {@ override public void onclick (view arg0) {intent = new intent (mcontext, showactivity. class); // use intent. putextra () directly transmits intent. putextra ("name", "Yu Song Momo"); intent. putextra ("Age", 25); intent. putextra ("boy", true); // put the value into the bundle, and then pass the entire bundle through intent. putextra () Transfer bundle = new bundle (); bundle. putstring ("B _name", "cute"); bundle. putint ("B _age", 23); bundle. putboolean ("B _boy", false); // put the entire bundle in intent. putextras (bundle); // enable a new activity to pass intent to startactivity (intent );}});

Receive

Public class showactivity extends activity {@ override protected void oncreate (bundle savedinstancestate) {setcontentview (R. layout. my); intent = getintent (); string name = intent. getstringextra ("name"); // The second parameter indicates that the default value is int age = intent. getintextra ("Age", 0); Boolean isboy = intent. getbooleanextra ("boy", false); textview textview0 = (textview) findviewbyid (R. id. text0); textview 0. settext ("name" + name + "Age" + age + "boy? "+ Isboy); bundle = intent. getextras (); name = bundle. getstring ("B _name"); // The second parameter is the default value, which means that if the bundle cannot be obtained, the default value is age = bundle. getint ("B _age", 0); isboy = bundle. getboolean ("B _boy", false); textview textview1 = (textview) findviewbyid (R. id. text1); textview1.settext ("name" + name + "Age" + age + "boy? "+ Isboy); Super. oncreate (savedinstancestate );}}


In the end, if you still think that I have not written enough details, it doesn't matter if I post the source code. You are welcome to discuss and study Yu Song Momo and hope to make progress together with everyone.

: Http://www.xuanyusong.com/archives/141

Related Article

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.