android_onAttachedToWindow () 和 onDetachedFromWindow ()

来源:互联网 发布:玻璃胶 知乎 编辑:程序博客网 时间:2024/06/04 23:19
自定义的组件或者是在Activity中:

onAttachedToWindow这方法中做初始化工作,比如注册一些广播等等……

 

开发文档就简单的两句。也就是我们销毁View的时候。我们写的这个View不再显示

这时我们就在这个方法做一些收尾工作,如:取消广播注册等等。


===========================================================================================

关于在Activity中什么时候调用onAttachedToWindow()和onDetachedFromWindow(),我通常测试打了下log,发现onAttachedToWindow()在onResume()之后运行,onDetachedFromWindow()则在onDestory()之后才会调用。


个人应用的代码:



    @Override
    protected void onAttachedToWindow() {
        super.onAttachedToWindow();


        if (!mAttached) {
            mAttached = true;
            IntentFilter filter = new IntentFilter();
            filter.addAction(Intent.ACTION_BOOT_COMPLETED);
            filter.addAction(DHBalanceService.ACTION_REG_UPDATE);
            filter.addCategory("com.broadcom.bavs.intent.category.BROADEVT");
            filter.addAction(DHBalanceService.ACTION_STATE_UPDATE);
            getContext().registerReceiver(mIntentReceiver, filter, null, getHandler());
        }
    }


    @Override
    protected void onDetachedFromWindow() {
        super.onDetachedFromWindow();
        if (mAttached) {
            getContext().unregisterReceiver(mIntentReceiver);
            mAttached = false;
        }
    }


    private final BroadcastReceiver mIntentReceiver = new BroadcastReceiver() {
        @Override
        public void onReceive(Context context, Intent intent) {
            String action = intent.getAction();
            if (action.equals(Intent.ACTION_BOOT_COMPLETED)) {
            Intent it = new Intent();
    it.setClass(context, DHBalanceService.class);
    context.startService(it);
            } else if (action.equals(DHBalanceService.ACTION_REG_UPDATE)) {
            String protocol = intent.getStringExtra("PARAM1");
            if (!"sip1".equals(protocol)) {
            return;
            }
            Log.i(TAG, "-------BroadcastReceiver--------->>>----"+action);
            Intent it = new Intent();
                it.setAction(DHBalanceService.ACTION_REG_UPDATE);
    it.setClass(context, DHBalanceService.class);
    context.startService(it);
            } else if (action.equals(DHBalanceService.ACTION_STATE_UPDATE)) {
            String uriBalance = intent.getStringExtra("UPDATE");
            updateBalance(uriBalance);
            }
        }
    };  
    
    private void updateBalance(String uriBalance) {
// TODO Auto-generated method stub
    setText("Balance ".concat(uriBalance));
}

原创粉丝点击