Android Learning Note broadcastreceiver Broadcast ...

Source: Internet
Author: User

PS: Keep Improving yourself, is a good thing ...

Learning content:

1.BroadcastReceiver of Use:

2. Start service via Broadcastreceiver ...

1.BroadcastReceiver ...

Broadcast receivers, used to receive broadcasts from systems and applications ... The Android broadcast mechanism is still a lot of places, such as: When the network status changes, by receiving this broadcast can respond in a timely manner, and then complete some operations. This is the broadcasting mechanism ... It does not implement the graphical user interface itself ... Just a trigger action ...

There are several steps to using the broadcast ...

I. That is to create a class to implement a broadcast, and then define the response in the class method ... To complete some response actions ...

II. Broadcast this thing is required to register, do not register is not available ....

There are two ways to register:

One is static registration, static registration is configured Androidmanifest.xml file configuration, by the system management receiver, belongs to the resident type ...

<!--This piece of code is added between application and you can ...  -<receiverAndroid:name=". Mybroadcast "android:enabled= "true">            <Intent-filter>                <ActionAndroid:name= "Android.intent.action.EDIT"/>            </Intent-filter></receiver>

Two types are dynamic registration ... are very resident, and hidden between blocks of code ... Not easy to find ...

Private broadcastreceiver receiver;receiver=new  callreceiver (); // dynamic registration of broadcast addresses ... Registerreceiver (receiver,new intentfilter ("Android.intent.action.EDIT")); // To cancel the registered broadcast address, be sure to write off the broadcasting mechanism ... Unregisterreceiver (receiver);

Iii. after the registration is completed, it is to send the broadcast ... So that the broadcast receiver can work properly ... Build a Intent object first, and then call the Sendbroadcast (Intent) method to emit the broadcast ...

Another point is that the broadcast is valid when the object calls the OnReceive () method, and when returned from this function, the object is invalid. So the broadcast life cycle is very short, just more than 10 seconds of life cycle, so do not add some time-consuming operations, time-consuming operations can be handed over to the service to complete, broadcast is to complete some very small operation on it ... Glue a code ...

 PackageCom.example.broadcast_receiver;ImportAndroid.content.BroadcastReceiver;ImportAndroid.content.Context;Importandroid.content.Intent;ImportAndroid.widget.Toast; Public classMybroadcastextendsbroadcastreceiver{@Override Public voidOnReceive (Context context, Intent Intent) {//TODO auto-generated Method StubString Str=intent.getstringextra ("MSG");    Toast.maketext (context, str, toast.length_short). Show (); }}

Above is the definition of a broadcast receive class, it inherits from Broadcastreceiver, in which to complete some corresponding operation ....

 PackageCom.example.broadcast_receiver;ImportAndroid.os.Bundle;Importandroid.app.Activity;ImportAndroid.view.Menu;ImportAndroid.view.View;ImportAndroid.view.View.OnClickListener;Importandroid.content.Intent; Public classMainactivityextendsActivityImplementsView.onclicklistener {PrivateIntent intent=NewIntent (Intent.action_edit); @Overrideprotected voidonCreate (Bundle savedinstancestate) {Super. OnCreate (savedinstancestate);        Setcontentview (R.layout.activity_main); Findviewbyid (R.id.broadcast). Setonclicklistener ( This); } @Override Public BooleanOncreateoptionsmenu (Menu menu) {//inflate the menu; This adds items to the action bar if it is present.getmenuinflater (). Inflate (R.menu.main, menu); return true; } @Override Public voidOnClick (View v) {//TODO auto-generated Method Stub        Switch(V.getid ()) { CaseR.id.broadcast:intent.putextra ("MSG", "AA"); Mainactivity. This. Sendbroadcast (Intent);  Break; }    }}

This is how to call the broadcast receiver in the mainactivity, a very simple action, is the trigger button, and then the screen output "AA" this message ... Very simple one operation, layout file on a button, no need to paste ... It is important to understand this process, do not forget to use the Broadcastreceiver must be registered, otherwise it can not be used ....

2. How to use Broadcastreceiver to start the service ...

As already mentioned, the life cycle of the Broadcastreceiver object is very short-lived ... The time-consuming action cannot be performed here, but we can call service in Broadcastreceiver ... Allow service to perform time-consuming services ... Simply introduce how to start the service ...

I. First we define a service ...

 PackageCom.example.broadcast_receiver;ImportAndroid.app.Service;Importandroid.content.Intent;ImportAndroid.media.MediaPlayer;ImportAndroid.os.IBinder; Public classMyServiceextendsservice{PrivateMediaPlayer Media; @Override Publicibinder onbind (Intent Intent) {//TODO auto-generated Method Stub        return NULL; } @Override Public voidonCreate () {Super. OnCreate (); Media=mediaplayer.create (MyService. This, R.RAW.A); MyService. This. Media.prepare (); MyService. This. Media.start (); Media.setlooping (true); } @Override Public voidOnDestroy () {Super. OnDestroy (); } @Override Public voidOnStart (Intent Intent,intStartid) {        Super. OnStart (Intent, Startid); }}

Here we need to copy a song to the Res\raw folder next song ... raw folder we do our own new ...

 PackageCom.example.broadcast_receiver;ImportAndroid.content.BroadcastReceiver;ImportAndroid.content.Context;Importandroid.content.Intent;ImportAndroid.widget.Toast; Public classMybroadcastextendsbroadcastreceiver{@Override Public voidOnReceive (Context context, Intent Intent) {//TODO auto-generated Method StubIntent newintent =NewIntent (Context,myservice.class);        Context.startservice (newintent); String Str=intent.getstringextra ("MSG");    Toast.maketext (context, str, toast.length_short). Show (); }  }

This is a broadcast class, from the inside of the broadcast to start the service ..... Then add the code <service android:name= "between <application> and </application> in the Androidmanifest.xml file. MyService "android:enable=" true "/> is done ...

This completes the start service inside the Broadcastreceiver () .....

Android Learning Note broadcastreceiver Broadcast ...

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.