(eight) Android broadcast receiver Broadcastreceiver

Source: Internet
Author: User

First, use broadcast Reciver 1. Right-click the Java folder and New->other->broadcast receiver will generate a receiver entry in the Androidmanifest.xml file
<?xml version= "1.0" encoding= "Utf-8"?>
<manifest xmlns:android= "Http://schemas.android.com/apk/res/android"
Package= "Com.example.shiyanshi.learnbroadcast" >

<application
Android:allowbackup= "true"
android:icon= "@mipmap/ic_launcher"
Android:label= "@string/app_name"
Android:theme= "@style/apptheme" >
<activity
Android:name= ". Mainactivity "
Android:label= "@string/app_name" >
<intent-filter>
<action android:name= "Android.intent.action.MAIN"/>

<category android:name= "Android.intent.category.LAUNCHER"/>
</intent-filter>
</activity>

<receiver
Android:name= ". Myreceiver "
Android:enabled= "true"
Android:exported= "true" >
</receiver>
</application>

</manifest>
2. Also generates a Myreceiver class in which onreceive is used to respond to messages sent by the Sendbroadcast function
Package com.example.shiyanshi.learnbroadcast;

Import Android.content.BroadcastReceiver;
Import Android.content.Context;
Import android.content.Intent;

public class Myreceiver extends Broadcastreceiver {
Public Myreceiver () {
}

@Override
public void OnReceive (context context, Intent Intent) {
Todo:this method is called if the Broadcastreceiver is receiving
An Intent broadcast.
throw new Unsupportedoperationexception ("not yet implemented");
System.out.println ("RECV Data:" +intent.getstringextra ("Data"));
}
}
3. Call the Sendbroadcast function to send the message, the function requires a intent
Package com.example.shiyanshi.learnbroadcast;

Import android.app.Activity;
Import android.content.Intent;
Import Android.os.Bundle;
Import Android.view.Menu;
Import Android.view.MenuItem;
Import Android.view.View;


public class Mainactivity extends Activity implements View.onclicklistener {

@Override
protected void OnCreate (Bundle savedinstancestate) {
Super.oncreate (savedinstancestate);
Setcontentview (R.layout.activity_main);

Findviewbyid (r.id.btnsendmsg). Setonclicklistener (this);
}

@Override
public boolean Oncreateoptionsmenu (Menu menu) {
Inflate the menu; This adds items to the action bar if it is present.
Getmenuinflater (). Inflate (R.menu.menu_main, menu);
return true;
}

@Override
public boolean onoptionsitemselected (MenuItem item) {
Handle Action Bar Item clicks here. The Action Bar would
Automatically handle clicks on the Home/up button, so long
As you specify a the parent activity in Androidmanifest.xml.
int id = item.getitemid ();

Noinspection simplifiableifstatement
if (id = = r.id.action_settings) {
return true;
}

return super.onoptionsitemselected (item);
}

@Override
public void OnClick (view view) {
Switch (View.getid ()) {
Case R.ID.BTNSENDMSG:
Intent Intent =new Intent (this,myreceiver.class);
Intent.putextra ("Data", "Henry");
Sendbroadcast (Intent);
Break
}
}
}
Ii. Dynamic registration and deregistration 1. When you delete receiver from the Androidmanifest.xml file, you need to register and log off dynamically to send and receive messages <receiver
Android:name= ". Myreceiver "
Android:enabled= "true"
Android:exported= "true" >
</receiver>
The 2.MainActivity changes are as follows: When sending a message message, intent to use the implicit intent (myreceiver.action as a constant string defined public static final string action= " Com.example.shiyanshi.learnbroadcast.intent.action.MyReceiver ";//The first half of the package name, the latter part when the intent format, Myreceiver is the class used in response to sendbroadcast above), when registering with the Registerreceiver function, the Unregisterreceiver function function prototype is used when logging out: public Intent Registerreceiver (broadcastreceiver receiver, intentfilter filter) public void Unregisterreceiver (broadcastreceiver Receiver receiver is the Myreceiver class that we claim to be used to respond to sendbroadcast when we create a new broadcast, and filter is the filters that need to be remembered for passing implicit intent-like parameters.

public class Mainactivity extends Activity implements View.onclicklistener {

Private Myreceiver Receiver=null;

@Override
protected void OnCreate (Bundle savedinstancestate) {
Super.oncreate (savedinstancestate);
Setcontentview (R.layout.activity_main);

Findviewbyid (r.id.btnsendmsg). Setonclicklistener (this);
Findviewbyid (R.id.btnregister). Setonclicklistener (this);
Findviewbyid (R.id.btnunregister). Setonclicklistener (this);
}

@Override
public boolean Oncreateoptionsmenu (Menu menu) {
Inflate the menu; This adds items to the action bar if it is present.
Getmenuinflater (). Inflate (R.menu.menu_main, menu);
return true;
}

@Override
public boolean onoptionsitemselected (MenuItem item) {
Handle Action Bar Item clicks here. The Action Bar would
Automatically handle clicks on the Home/up button, so long
As you specify a the parent activity in Androidmanifest.xml.
int id = item.getitemid ();

Noinspection simplifiableifstatement
if (id = = r.id.action_settings) {
return true;
}

return super.onoptionsitemselected (item);
}

@Override
public void OnClick (view view) {
Switch (View.getid ()) {
Case R.ID.BTNSENDMSG:
Intent Intent =new Intent (this,myreceiver.class);
Use implicit intent for dynamic registration and logoff, but not for display intent
Intent intent=new Intent (myreceiver.action);
Intent.putextra ("Data", "Henry");
Sendbroadcast (Intent);
Break
Case R.id.btnregister:
if (receiver==null) {
Receiver=new Myreceiver ();
Registerreceiver (receiver,new intentfilter (myreceiver.action));
}
Break
Case R.id.btnunregister:
if (receiver!=null) {
Unregisterreceiver (receiver);
Receiver=null;
}
Break
}
}
}
Broadcast priority when sending data, in the form of an implicit intent (e.g. above), the action name in two receivers simultaneously, both can receive the data simultaneously. By default, the receiver that is written last has a high priority, and the higher the value, the higher the priority, and the more the first response to the data that can be displayed in the Intent-filter under receiver.
<receiver
Android:name= ". MyReceiver1 "
Android:enabled= "true"
Android:exported= "true" >
<intent-filter android:priority= "2" >
<action android:name= "Com.example.shiyanshi.learnbroadcast.intent.action.MyReceiver"/>
</intent-filter>
</receiver>
<receiver android:name= ". Myreceiver "
Android:enabled= "true"
Android:exported= "true" >
<intent-filter android:priority= "1" >
<action android:name= "Com.example.shiyanshi.learnbroadcast.intent.action.MyReceiver"/>
</intent-filter>
</receiver>
</application>
In addition, when the high-priority onreceive executes, you can invoke Abortbroadcast in it to terminate the delivery of the data. OnReceive with low priority will not execute. NOTE: If you want to use the Abortbroadcast function, you will need to use sendorderedbroadcast instead of sendbroadcast when sending it, otherwise you'll get a pop-up error java.lang.RuntimeException : Broadcastreceiver trying to return result during a non-ordered broadcast.
Intent intent=new Intent (myreceiver.action);
Intent.putextra ("Data", "Henry");
Sendbroadcast (Intent);
Sendorderedbroadcast (Intent,null);
Where the second parameter of Sendorderedbroadcast is used to indicate a permission, which can be null


(eight) Android broadcast receiver Broadcastreceiver

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.