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

来源:互联网 发布:网络课和直播课的区别 编辑:程序博客网 时间:2024/06/05 07:21

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 stubint 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 stubnew Thread(new Runnable() {@Overridepublic void run() {// TODO Auto-generated method stubinstrumentation.sendKeyDownUpSync(keycode);}}).start();}

}


0 0