码迷,mamicode.com
首页 > 移动开发 > 详细

Android 广播(内部类)

时间:2015-01-16 18:52:39      阅读:170      评论:0      收藏:0      [点我收藏+]

标签:

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 广播(内部类)

标签:

原文地址:http://www.cnblogs.com/zhujiabin/p/4229033.html

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!