`
zhy20045923
  • 浏览: 153386 次
  • 性别: Icon_minigender_1
  • 来自: 深圳
社区版块
存档分类
最新评论

Android模拟按键

阅读更多
如果想要实现类似iphone的悬浮框按钮,那就必须知道如何去模拟真实按键,然后才能将按键功能与悬浮框按钮联系起来,下面就详细说明一下具体的模拟实现:
实现方式有两种,一种是通过Command命令方式,另外一种是通过Instrumentation方式。
一 Command命令方式:
		try{
			String keyCommand = "input keyevent " + KeyEvent.KEYCODE_BACK;
			Runtime runtime = Runtime.getRuntime();
			Process proc = runtime.exec(keyCommand);
		} catch(IOException e){
			
		}

二 Instrumentation方式:
		
private Instrumentation in =new Instrumentation();
new Thread(new Runnable() {
			@Override
			public void run() {
				in.sendKeyDownUpSync(KeyEvent.KEYCODE_BACK);
			}
		}).start();

注意sendKeyDownUpSync方法必须放到非主线程去调用。

以上两种方法都有一个缺点,那就是home是无法模拟的,那至于home键我们需要如何做呢?首先需要分析home键的功能,短按home键是返回桌面,长按home键是拉起最近使用程序列表,知道这些就简单了,只需要在虚拟home键的地方实现上述两个功能就可以了,具体如下:
一 短按home:
		Intent intent = new Intent(Intent.ACTION_MAIN);
        intent.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
        intent.addCategory(Intent.CATEGORY_HOME);
        startActivity(intent);


二 长按home:
	IStatusBarService mStatusBarService;
	final Object mServiceAquireLock = new Object();
    IStatusBarService getStatusBarService() {
        synchronized (mServiceAquireLock) {
            if (mStatusBarService == null) {
                mStatusBarService = IStatusBarService.Stub.asInterface(
                        ServiceManager.getService("statusbar"));
            }
            return mStatusBarService;
        }
    }

        try {
            IStatusBarService statusbar = getStatusBarService();
            if (statusbar != null) {
                statusbar.toggleRecentApps();
            }
        } catch (RemoteException e) {
            mStatusBarService = null;
        }


长按home键功能在android最新版本是在SystemUI中实现的,此法只针对新版,老版本的没有研究过
0
1
分享到:
评论

相关推荐

Global site tag (gtag.js) - Google Analytics