android开发笔记之Instrumentation一个小应用

本文介绍了一种在Android应用中通过Instrumentation发送虚拟按键的方法。该方法能够模拟按下menu、home和back等按键,适用于自动化测试场景。文章提供了一个具体的实现示例,包括创建按钮并为其设置点击监听器,当触发时将调用sendKeyDownUpSync方法来模拟按键。

开发板推荐:天空星STM32F407VET6开发板

超高性价比 STM32主控 | 超高主频 | 一板兼容百芯 | 比赛神器 | 沉金彩色丝印

Instrumentation:


   在做东西的时候,有时候要模拟一个按键的操作,如按下menu,home,back键,这个时,Instrumentation能完成这个操作


import android.os.Bundle;
import android.app.Activity;
import android.app.Instrumentation;
import android.view.KeyEvent;
import android.view.Menu;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.Button;

public class InstrumentationActivity extends Activity implements OnClickListener {
	
	private Button testKeyMenu;
	private Button testKeyHome;
	private Button testKeyBack;
	
	private Instrumentation instrumentation;

protected void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
		setContentView(R.layout.activity_instrumentation);
		
		testKeyMenu = (Button)findViewById(R.id.testKeyMenu);
		testKeyHome = (Button)findViewById(R.id.testKeyHome);
		testKeyBack = (Button)findViewById(R.id.testKeyBack);
		
		testKeyMenu.setOnClickListener(this);
		testKeyHome.setOnClickListener(this);
		testKeyBack.setOnClickListener(this);
		
		instrumentation = new Instrumentation();
		
	}

public boolean onCreateOptionsMenu(Menu menu) {
		// Inflate the menu; this adds items to the action bar if it is present.
		getMenuInflater().inflate(R.menu.instrumentation, menu);
		return true;
	}

public void onClick(View view) {
		// TODO Auto-generated method stub
		int id = view.getId();
		switch(id){
			case R.id.testKeyMenu:
				sendKey(KeyEvent.KEYCODE_MENU);
				break;
				
			case R.id.testKeyHome:			
				sendKey(KeyEvent.KEYCODE_HOME);
				break;
				
			case R.id.testKeyBack:			
				sendKey(KeyEvent.KEYCODE_BACK);
				break;							
		}
	}

private void sendKey(final int keycode) {
		// TODO Auto-generated method stub
		new Thread(new Runnable() {
			
			@Override
			public void run() {
				// TODO Auto-generated method stub
				instrumentation.sendKeyDownUpSync(keycode);
			}
		}).start();
	}

}


开发板推荐:天空星STM32F407VET6开发板

超高性价比 STM32主控 | 超高主频 | 一板兼容百芯 | 比赛神器 | 沉金彩色丝印

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

hfreeman2008

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值