Android Studio 基础 之 模拟 Home / 音量 + - 加减键按下(扩展到模拟常用的各个物理按键)的操作

 

 

Android Studio 基础 之 模拟 Home / 音量 + - 加减键按下(扩展到模拟常用的各个物理按键)的操作

 

目录

Android Studio 基础 之 模拟 Home / 音量 + - 加减键按下

一、简单介绍

二、实现原理

三、注意实现

四、效果预览

五、实现步骤

六、关键代码

七、扩展到模拟各个物理按键的代码

八、常用的按键keyCode


一、简单介绍

Android 开发中的一些基础操作,使用整理,便于后期使用。

本节介绍,模拟 Home / 音量 + - 加减键按下的操作。

 

二、实现原理

1、音量加减+-键,使用 Runtime  和 Process (Process proc = runtime.exec(keyCommand))实现

2、Home 键,使用意图 intent 的方式实现

3、模拟 adb shell input key keynumber,来实现各个物理按键

 

三、注意实现

1、要点击实现音量真正的加减效果,请在音量调出现的时候,继续按下音量加减,音量就会真正的增加减少

2、代码模拟其他物理按键输入,这里用了shell 命令在程序运行时环境里模拟按键事件。因命令执行会阻塞线程, 所以最好是在子线程里执行命令

 

四、效果预览

 

五、实现步骤

1、打开 Android Studio ,新建工程

 

2、取个名称

 

3、新建一个 EmptyActivity

 

4、完成,新建工程

 

5、编写脚本,实现模拟音量加减 / 和Home 键的功能

 

6、布置一下 layout,测试接口

 

7、打包运行应用,效果如上

 

六、关键代码

1、MainActivity.java

package com.example.administrator.simulatevolumekey;

import android.content.Intent;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.util.Log;
import android.view.KeyEvent;
import android.view.View;

import java.io.IOException;

public class MainActivity extends AppCompatActivity {

    private static final String TAG = MainActivity.class.getSimpleName();

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);
    }


    public void onVolumeAddKeyclick(View view) {

        // 模拟音量+
        OnVolumeAddKey();
    }

    public void onVolumeReduceKeyclick(View view) {

        // 模拟音量-
        OnVolumeReduceKey();

    }

    public void onHomeKeyclick(View view) {

        // 模拟 Home 键
        OnHomeKey();

    }


    /**
     * 模拟音量加减按下
     */
    public void OnVolumeAddKey(){

        try
        {
            String keyCommand = "input keyevent " + KeyEvent.KEYCODE_VOLUME_UP;
            Runtime runtime = Runtime.getRuntime();
            Process proc = runtime.exec(keyCommand);

            Log.i(TAG, "OnVolumeAddKey: 音量加按下");
        }
        catch (IOException e)
        {
            // TODO Auto-generated catch block
            e.printStackTrace();
        }

    }

    /**
     * 模拟音量减键按下
     */
    public void OnVolumeReduceKey(){

        try
        {
            String keyCommand = "input keyevent " + KeyEvent.KEYCODE_VOLUME_DOWN;
            Runtime runtime = Runtime.getRuntime();
            Process proc = runtime.exec(keyCommand);

            Log.i(TAG, "OnVolumeAddKey: 音量减按下");
        }
        catch (IOException e)
        {
            // TODO Auto-generated catch block
            e.printStackTrace();
        }

    }

    /**
     * 模拟Home 键
     */
    public void OnHomeKey(){

        Intent intent = new Intent(Intent.ACTION_MAIN);
        intent.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK);//提示如果是服务里调用,必须加入new task标识
        intent.addCategory(Intent.CATEGORY_HOME);
        startActivity(intent);

    }
}

 

2、activity_main.xml

<?xml version="1.0" encoding="utf-8"?>
<android.support.constraint.ConstraintLayout xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:app="http://schemas.android.com/apk/res-auto"
    xmlns:tools="http://schemas.android.com/tools"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    tools:context=".MainActivity">

    <Button
        android:id="@+id/button"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:layout_marginStart="120dp"
        android:layout_marginTop="84dp"
        android:onClick="onVolumeAddKeyclick"
        android:text="模拟音量+"
        app:layout_constraintStart_toStartOf="parent"
        app:layout_constraintTop_toTopOf="parent" />

    <Button
        android:id="@+id/button2"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:layout_marginStart="120dp"
        android:layout_marginTop="176dp"
        android:onClick="onVolumeReduceKeyclick"
        android:text="模拟音量-"
        app:layout_constraintStart_toStartOf="parent"
        app:layout_constraintTop_toTopOf="parent" />

    <Button
        android:id="@+id/button3"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:layout_marginStart="120dp"
        android:layout_marginTop="280dp"
        android:onClick="onHomeKeyclick"
        android:text="模拟Home键"
        app:layout_constraintStart_toStartOf="parent"
        app:layout_constraintTop_toTopOf="parent" />

</android.support.constraint.ConstraintLayout>

 

七、扩展到模拟各个物理按键的代码

package com.example.administrator.simulatevolumekey;

import android.content.Intent;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.util.Log;
import android.view.KeyEvent;
import android.view.View;

import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;

public class MainActivity extends AppCompatActivity {

    private static final String TAG = MainActivity.class.getSimpleName();

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);
    }


    public void onVolumeAddKeyclick(View view) {

        // 模拟音量+
        //OnVolumeAddKey();

        keyVolumeAdd();
    }

    public void onVolumeReduceKeyclick(View view) {

        // 模拟音量-
        OnVolumeReduceKey();

    }

    public void onHomeKeyclick(View view) {

        // 模拟 Home 键
        OnHomeKey();

    }


    /**
     * 模拟音量加减按下
     */
    public void OnVolumeAddKey(){

        try
        {
            String keyCommand = "input keyevent " + KeyEvent.KEYCODE_VOLUME_UP;
            Runtime runtime = Runtime.getRuntime();
            Process proc = runtime.exec(keyCommand);

            Log.i(TAG, "OnVolumeAddKey: 音量加按下");
        }
        catch (IOException e)
        {
            // TODO Auto-generated catch block
            e.printStackTrace();
        }

    }

    /**
     * 模拟音量减键按下
     */
    public void OnVolumeReduceKey(){

        try
        {
            String keyCommand = "input keyevent " + KeyEvent.KEYCODE_VOLUME_DOWN;
            Runtime runtime = Runtime.getRuntime();
            Process proc = runtime.exec(keyCommand);

            Log.i(TAG, "OnVolumeAddKey: 音量减按下");
        }
        catch (IOException e)
        {
            // TODO Auto-generated catch block
            e.printStackTrace();
        }

    }

    /**
     * 模拟Home 键
     */
    public void OnHomeKey(){

        Intent intent = new Intent(Intent.ACTION_MAIN);
        intent.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK);//提示如果是服务里调用,必须加入new task标识
        intent.addCategory(Intent.CATEGORY_HOME);
        startActivity(intent);

    }

    /**
     * adb shell 命令 模拟音量键+
     */
    public void keyVolumeAdd(){

        new Thread(){
            @Override
            public void run() {
                execByRuntime("input keyevent 24");
            }
        }.start();

    }

    /**
     * 执行shell 命令, 命令中不必再带 adb shell
     *
     * @param cmd
     * @return Sting  命令执行在控制台输出的结果
     */
    public static String execByRuntime(String cmd) {
        Process process = null;
        BufferedReader bufferedReader = null;
        InputStreamReader inputStreamReader = null;
        try {
            process = Runtime.getRuntime().exec(cmd);
            inputStreamReader = new InputStreamReader(process.getInputStream());
            bufferedReader = new BufferedReader(inputStreamReader);

            int read;
            char[] buffer = new char[4096];
            StringBuilder output = new StringBuilder();
            while ((read = bufferedReader.read(buffer)) > 0) {
                output.append(buffer, 0, read);
            }
            return output.toString();
        } catch (Exception e) {
            e.printStackTrace();
            return null;
        } finally {
            if (null != inputStreamReader) {
                try {
                    inputStreamReader.close();
                } catch (Throwable t) {
                    //
                }
            }
            if (null != bufferedReader) {
                try {
                    bufferedReader.close();
                } catch (Throwable t) {
                    //
                }
            }
            if (null != process) {
                try {
                    process.destroy();
                } catch (Throwable t) {
                    //
                }
            }
        }
    }

}

 

八、常用的按键keyCode

键英文名 键中文名 Keycode
KEYCODE_CALL  拨号键  5
KEYCODE_ENDCALL  挂机键  6
KEYCODE_HOME  按键Home  3
KEYCODE_MENU  菜单键  82
KEYCODE_BACK  返回键  4
KEYCODE_SEARCH  搜索键  84
KEYCODE_CAMERA  拍照键  27
KEYCODE_FOCUS  拍照对焦键  80
KEYCODE_POWER  电源键  26
KEYCODE_NOTIFICATION  通知键  83
KEYCODE_MUTE  话筒静音键  91
KEYCODE_VOLUME_MUTE  扬声器静音键  164
KEYCODE_VOLUME_UP  音量增加键  24
KEYCODE_VOLUME_DOWN  音量减小键  25
KEYCODE_ENTER  回车键  66
KEYCODE_ESCAPE  ESC键  111
KEYCODE_DPAD_CENTER  导航键 确定键  23
KEYCODE_DPAD_UP  导航键 向上  19
KEYCODE_DPAD_DOWN  导航键 向下  20
KEYCODE_DPAD_LEFT  导航键 向左  21
KEYCODE_DPAD_RIGHT  导航键 向右  22
KEYCODE_MOVE_HOME  光标移动到开始键  122
KEYCODE_MOVE_END  光标移动到末尾键  123
KEYCODE_PAGE_UP  向上翻页键  92
KEYCODE_PAGE_DOWN  向下翻页键  93
KEYCODE_DEL  退格键  67
KEYCODE_FORWARD_DEL  删除键  112
KEYCODE_INSERT  插入键  124
KEYCODE_TAB  Tab键  61
KEYCODE_NUM_LOCK  小键盘锁  143
KEYCODE_CAPS_LOCK  大写锁定键  115
KEYCODE_BREAK  Break/Pause键  121
KEYCODE_SCROLL_LOCK  滚动锁定键  116
KEYCODE_ZOOM_IN  放大键  168
KEYCODE_ZOOM_OUT  缩小键  169

 

 

 

猜你喜欢

转载自blog.csdn.net/u014361280/article/details/106598213
今日推荐