zoukankan      html  css  js  c++  java
  • 监听home键+模拟home键

    一、监听home键首先定义一个广播接受者

    HomeKeyReceiver

    package com.kale.floattest;
    
    
    import com.kale.floattest.service.DrawService;
    
    import android.content.BroadcastReceiver;
    import android.content.Context;
    import android.content.Intent;
    import android.util.Log;
    
    public class HomeKeyReceiver extends BroadcastReceiver{
        
        static final String SYSTEM_REASON = "reason";
        static final String SYSTEM_HOME_KEY = "homekey";// home key
        static final String SYSTEM_RECENT_APPS = "recentapps";// long home key
    
        @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 (reason != null) {
                    if (reason.equals(SYSTEM_HOME_KEY)) {
                        Log.e("homekey", "home键被点击");
                        context.stopService(new Intent(context,DrawService.class));
                    } else if (reason.equals(SYSTEM_RECENT_APPS)) {
                         Log.e("homekey", "长按home键");
                    }
                }
            }
        }
    }

    这里的事件我写了关闭一个服务,当然大家可以自由发挥。下面是在服务中注册

        // 监听HOME键
        HomeKeyReceiver receiver;
    
    @Override
        public void onCreate() {
            super.onCreate();
            // 注册监听home键广播
            receiver = new HomeKeyReceiver();
            registerReceiver(receiver, new IntentFilter(Intent.ACTION_CLOSE_SYSTEM_DIALOGS));
    }
    @Override
        public void onDestroy() {
            super.onDestroy();
            //取消监听home键
                unregisterReceiver(receiver);
            
        }            

    二、模拟home键(执行代码后就等于点击了home键)

        protected void virtualHome() {
            //模拟HOME键
            Intent i= new Intent(Intent.ACTION_MAIN);
            i.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK); //如果是服务里调用,必须加入new task标识
            i.addCategory(Intent.CATEGORY_HOME);
            startActivity(i);
        }
  • 相关阅读:
    博客添加点线粒子
    获取微信公众号音乐
    Linux 命令汇总
    Hbase 数据导入导出
    scala SimpleDateFormat
    shell 日期加减运算
    selenium获取全部页面的html
    关于EEG参考电极
    反相器和晶振做振荡
    HC系列蓝牙模块连接单片机与电脑,传输数据(蓝牙心电测试)
  • 原文地址:https://www.cnblogs.com/tianzhijiexian/p/3905687.html
Copyright © 2011-2022 走看看