Android学习日记(yzy):Broadcast Receiver的注册和发送

来源:互联网 发布:php api接口验证 编辑:程序博客网 时间:2024/06/06 10:01

  作为Android应用层的四大组件之一,Broadcast Receiver常用于应用程序之间的信息传输,也可用于应用内的信息传输,在编写广播时我们要注意的重要点:

1:broadcast reseiver的注册有两个方法:①常驻型注册 ②非常驻型注册,常驻型注册是指在manifest.xml配置文件中进行注册,而非常驻型注册是指在java代码中进行动态注册,

这两个注册的不同在于:非常驻型注册的代码伴随着程序的Activity的生命周期,而常驻型注册的广播接收器不会随着程序关闭而关闭,类似于手机应用上的Notification的消息通

知功能便是可利用常驻型注册的广播来运行应用程序。


2:Broacast的消息发送方式分为两种:①无序广播  ②有序广播 ,区别在于有序广播利用优先级进行发送,且广播消息可被修改,终止 等。


代码(将发送广播和广播接收器编入同一个应用中):


public class MainActivity extends Activity {    private final static String TAG = "MainActivity";    private final static String ACTION_NAME = "the content of Broadcast Receiver";    @Override    protected void onCreate(Bundle savedInstanceState) {        super.onCreate(savedInstanceState);        setContentView(R.layout.activity_main);        //register a Broadcasr Receiver        registerBroadcastReceiver();    }    //create a broacast Recever    private BroadcastReceiver mBroadcastReceiver  = new BroadcastReceiver() {        @Override        public void onReceive(Context context, Intent intent) {            String getData;            String action = intent.getAction();            if (action.equals(ACTION_NAME)){                Log.e(TAG,"the broadcast receiver triggered");                getData = intent.getStringExtra("senddata");                Toast.makeText(MainActivity.this,"actually send ths broadcast"+'\n'+getData,Toast.LENGTH_SHORT).show();            }        }    };    //send message to broadcast receiver        protected void BroadcastClick(View view){        Log.e(TAG,"Click the Button");        Intent mIntent = new Intent(ACTION_NAME);        mIntent.putExtra("senddata","the Broadcast send the data");        sendBroadcast(mIntent);    }    private void registerBroadcastReceiver(){        IntentFilter mIntentFilter = new IntentFilter();        mIntentFilter.addAction(ACTION_NAME);        registerReceiver(mBroadcastReceiver,mIntentFilter);    }    protected void onDestroy(){        super.onDestroy();        unregisterReceiver(mBroadcastReceiver);    }}

阅读全文
0 0