[Android]BroadcastReceiver静态注册

静态注册的方法:

    

<?xml version="1.0" encoding="utf-8"?>
<manifest xmlns:android="http://schemas.android.com/apk/res/android"
    package="com.example.broadcast2"
    android:versionCode="1"
    android:versionName="1.0" >

    <uses-sdk
        android:minSdkVersion="22"
        android:targetSdkVersion="22" />

    <application
        android:allowBackup="true"
        android:icon="@drawable/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="clsReceiver2"> 
			<intent-filter> 
			<action	android:name="android.intent.action.ACTION_TIME_CHANGED"/> 
			</intent-filter>	 
		</receiver>
    </application>

</manifest>

上面我注册了一个广播接收器BroadcastReceiver名称叫clsReceiver2

注册方式是<receiver> </receiver>标签来注册,里面要设置一个intent-filter ,action是标准广播Action之一 

[时间重新设置事件]

ACTION_TIME_CHANGED

这样当系统时间被修改时会发送一个这个消息,clsReceiver2会接收该事件,进入onReceive()方法内处理。

如果是通过手动发送事件的话,需要通过动态注册接收器以及主动发送事件给接收器:

IntentFilter filter = new IntentFilter("com.broadcast2.MY_ACTION");
clsReceiver2 clsReceiver = new clsReceiver2();
registerReceiver(clsReceiver,filter);//动态注册广播接收器,会响应com.broadcast2.MY_ACTION事件

Intent intent=new Intent();
intent.setAction("com.broadcast2.MY_ACTION");
intent.putExtra("myMsg","我手动发送数据给接收器");
sendBroadcast(intent);

接收器关键代码:该接收器名称与上面所说的不同,因为我是复制粘贴以前的代码

        private Context context;
	public MyReceiver(Context context) {
		this.context=context;
	}
	
	@Override
	public void onReceive(Context context, Intent intent) {			
		String msg = intent.getStringExtra("myMsg");//接收intent中的myMsg额外消息放入msg字符串变量
		Toast.makeText(this.context, msg, Toast.LENGTH_LONG).show();
	}
注意myMsg是与上面的一致,即第一个参数的名字就是额外消息的名字,获取它要通过该名字获取。
intent.putExtra("myMsg","我手动发送数据给接收器");

猜你喜欢

转载自blog.csdn.net/qq_39574690/article/details/80646930