首页 > 代码库 > Android 广播(内部类)

Android 广播(内部类)

1.广播定义在一个单独的文件中

源码:

public class MessageReceiver extends BroadcastReceiver{        @Override    public void onReceive(Context context, Intent intent) {        // TODO Auto-generated method stub        if(intent.getAction().equals("android.provider.Telephony.SMS_RECEIVED")){                }    }}

在Manifest中注册:

<receiver android:name=".MessageReceiver">            <intent-filter>                <action android:name="android.provider.Telephony.SMS_RECEIVED"/>            </intent-filter></receiver>

使用代码注册:

//生成广播处理  MessageReceiver  smsBroadCastReceiver = new MessageReceiver ();  //实例化过滤器并设置要过滤的广播  IntentFilter intentFilter = new IntentFilter();  intentFilter.addAction("android.provider.Telephony.SMS_RECEIVED");    //注册广播  this.registerReceiver(smsBroadCastReceiver, intentFilter);  

注销广播:

unregisterReceiver(smsBroadCastReceiver);

2.广播是内部类

public class SettingForSMS extends PreferenceActivity{        @Override    public void onCreate(Bundle savedInstanceState) {        super.onCreate(savedInstanceState);        addPreferencesFromResource(R.layout.sms_setting);    }        public static class MessageChangeReceiver extends BroadcastReceiver {        @Override        public void onReceive(Context context, Intent intent) {            // TODO Auto-generated method stub            Log.i(tag, "onReceive");        }    }}

注意定义的过程中必须声明为static,不然会找不到

在Manifest中注册:

<receiver android:name=".SettingForSMS$MessageChangeReceiver">            <intent-filter>                <action android:name="com.ginwave.message_changed"/>            </intent-filter></receiver>

注意内部类使用$符号而不是.,使用.会出现类找不到异常

在程序内注册,register是放在onCreate中,unregister是放在onDestroy中。

smsBroadCastReceiver = new MessageChangeReceiver ();          //实例化过滤器并设置要过滤的广播          IntentFilter intentFilter = new IntentFilter();          intentFilter.addAction("com.ginwave.message_changed");                    //注册广播          this.registerReceiver(smsBroadCastReceiver, intentFilter); 
unregisterReceiver(smsBroadCastReceiver);

 注意:如果使用getResource()方法,要使用context.getResource()

Android 广播(内部类)