码迷,mamicode.com
首页 > 其他好文 > 详细

home键监听、屏蔽和模拟home键

时间:2014-09-27 12:18:09      阅读:132      评论:0      收藏:0      [点我收藏+]

标签:activity   home   监听   屏蔽   

 
   /**
     * 模拟按home键
     * 程序退到后台运行
     * @param context
     */
    private void imitatePressHome(Context context)
    {
        Intent intent = new Intent(Intent.ACTION_MAIN);  
        intent.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
        intent.addCategory(Intent.CATEGORY_HOME);  
        context.startActivity(intent);  
    }


    /**
     * 注册home键监听
     * @param context
     */
    private void registerHomeReceiver(Context context)
    {
        context.registerReceiver(mHomeKeyEventReceiver, new IntentFilter(  
                Intent.ACTION_CLOSE_SYSTEM_DIALOGS));
    }
    /**
     * home键处理
     */
    private BroadcastReceiver mHomeKeyEventReceiver = new BroadcastReceiver() {  
        String SYSTEM_REASON = "reason";  
        String SYSTEM_HOME_KEY = "homekey";  
        String SYSTEM_HOME_KEY_LONG = "recentapps";  
           
        @Override  
        public void onReceive(Context context, Intent intent) {  
            String action = intent.getAction();  
            if (action.equals(Intent.ACTION_CLOSE_SYSTEM_DIALOGS)) {  
                String reason = intent.getStringExtra(SYSTEM_REASON);  
                if (TextUtils.equals(reason, SYSTEM_HOME_KEY)) {  
                     //表示按了home键,程序到了后台  
                    Toast.makeText(context, "home pressed", 1000).show();  
                }else if(TextUtils.equals(reason, SYSTEM_HOME_KEY_LONG)){  
                    //表示长按home键,显示最近使用的程序列表
                    Toast.makeText(context, "home long pressed", 1000).show();
                }  
            }   
        }  
    };  


/**
 * home键屏蔽
 */
    @Override  
    public void onAttachedToWindow() {  
        // TODO Auto-generated method stub  
        this.getWindow().setType(WindowManager.LayoutParams.TYPE_KEYGUARD);  
        super.onAttachedToWindow();  
    }


在4.0 以后,无论是在onCreate()还是onAttachedToWindow()中都不能重设window的Type,想用此法屏蔽Home键无效!
4.0以上执行这段代码会报java.lang.IllegalArgumentException: Window type can not be changed after the window is added.至于怎么屏蔽,现在网上还没有很好的解决办法,mtk的到是有解决办法,其他平台的就不行了....除非修改底层框架
mtk的解决办法:
public static final int FLAG_HOMEKEY_DISPATCHED = 0x80000000;
在onCreate中执行
this.getWindow().setFlags(FLAG_HOMEKEY_DISPATCHED, FLAG_HOMEKEY_DISPATCHED);

home键监听、屏蔽和模拟home键

标签:activity   home   监听   屏蔽   

原文地址:http://blog.csdn.net/tangnengwu/article/details/39610597

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