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

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();
	}

}


你可能感兴趣的:(android,Instrumentation)