注册BroadcastReceiver 两种方式:
1、静态注册
2、动态注册
静态注册方式:
步骤1:通过Manifest文件注册广播接收器:
<!-- 开机启动完成广播接收器 -->
<receiver android:name="com.spreadtrum.BroadcastReceiver.BootReceiver" android:permission="android.permission.RECEIVE_BOOT_COMPLETED">
<intent-filter>
<action android:name="android.intent.action.BOOT_COMPLETED"></action>
</intent-filter>
</receiver>
步骤2:编写一个广播接收器类,继承于BroadcastReceiver,并实现onReceive方法:
public class BootReceiver extends BroadcastReceiver {
private static final String TAG = "BootReceiver";
@Override
public void onReceive(Context context, Intent intent) {
// TODO Auto-generated method stub
if (Intent.ACTION_BOOT_COMPLETED.equals(intent.getAction())){
//处理接收到该广播时的逻辑事务
}
}
}
动态注册
public class MainActivity extends Activity {
private BroadcastReceiver receiver = null;
protected void onCreate(Bundle savedInstanceState) {
// TODO Auto-generated method stub
super.onCreate(savedInstanceState);
Log4debug.i(TAG, "onCreate", null);
setContentView(R.layout.main_activity);
receiver = new BroadcastReceiver() {
@Override
public void onReceive(Context context, Intent intent) {
// TODO Auto-generated method stub
if (Intent.ACTION_BOOT_COMPLETED.equals(intent.getAction())){
//处理接收到该广播时的逻辑事务
}
}
};
registerReceiver(receiver, new IntentFilter(Intent.ACTION_BOOT_COMPLETED));
}
}