现在的位置: 首页 > 综合 > 正文

使用监听Logcat来监听系统home事件

2018年04月27日 ⁄ 综合 ⁄ 共 1457字 ⁄ 字号 评论关闭

一般我们监听home键有监听广播的方式,监听按键的方式。

监听广播的方式存在有的手机会把广播改掉(魅族M90)。而监听按键的方式在高版本系统上不行。

这里补充一个监听系统logcat内容来判断Home事件的方法,代码比较短,复制粘贴即可用。

private Thread createCatchHomeThread() {

        return new Thread(new Runnable() {
            public void run() {
                Process mLogcatProc = null;
                BufferedReader reader = null;

                //记录线程开始的时间
                Date date = new Date(System.currentTimeMillis());
                SimpleDateFormat fmt = new SimpleDateFormat("MM-dd hh:mm:ss.SSS");
                String startDateString = fmt.format(date);

                try {
                    /* 获取logcat信息
                     * logcat:日志类型为logcat
                     * -v 带有format的输出
                     * time 一种format 表示输出日志带着时间
                     * ActivityManager日志Tag为ActivityManager
                     * I:logcat的标识分为: D :Debug I :Info W :Warning E :Error
                     * F :Fatal S :Silent)这里I代表Info。
                     * *:S:日志的所有内容
                     */
                    mLogcatProc = Runtime.getRuntime().exec(
                            new String[] { "logcat", "-v", "time", "ActivityManager:I *:S" });

                    reader = new BufferedReader(new InputStreamReader(
                            mLogcatProc.getInputStream()));

                    Log.d(TAG, "start catch home");
                    String line;
                    while ((line = reader.readLine()) != null && runCatchHomeFlag) {
                        int indexOfHome = line.indexOf("android.intent.category.HOME");
                        if (indexOfHome > 0) {
                            //捕获到HOME键后发送message,在handler中可以自主处理。
//                            Log.e(TAG, "home event thrown");
                            String[] arr = line.split(" ");
                            if (arr.length >= 2) {
                                String time;
                                time = arr[0] + " " + arr[1];
                                //Home事件发生时间大于线程开始监听的时间才进行响应
                                if (time.compareTo(startDateString) >= 0 ) {
                                    Log.e(TAG, startDateString + " -> catch home event: " + line);
                                    //删除日志,有的手机删除不了,所以需要根据时间来判断是否是监听线程开始以后的home时间
                                    Runtime.getRuntime().exec("logcat -c");
                                    mHandler.sendMessage(mHandler.obtainMessage(MSG_CATCH_HOME));
                                    runCatchHomeFlag = false;
                                    break;
                                }
                            }
                        }
                    }
                    Log.d(TAG, "stop catch home");
                } catch (Exception e) {
                    Log.e(TAG, "" + e);
                }
            }

        });
    }

抱歉!评论已关闭.