Android 开发之 手势开发

手势识别在安卓开发里虽然用到的场景不是很多,但有时候还是能让你的产品更方便,更有趣味。比如登陆时不用每次重复输入密码,只需九宫格手势解锁,就像支付宝客户端那样。下面我们完成一个简单的手势识别开发。 我们首先需要一个描述手势动作的文件,在模拟器里预装一个叫GesturesBuilder的程序,这个程序就是让你创建自己的手势的(GesturesBuilder的源代码在sdk问samples里面有,有兴趣可以看看)。创建的手势将被保存到/sdcard/gestures里面。 建立好自己的手势库后,我们就可以实现手势识别了,新建一个工程,把上面的手势库文件复制到你的工程/res/raw下,你就可以在你的工程里面使用这些手势了。复制到/res/raw下的手势是只读的,也就是说你不能修改或增加手势了。 布局xml文件大概如下:



MainActivity里主要代码:
 public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.main);

 library = GestureLibraries.fromRawResource(this, R.raw.gestures);
library.load();

 overlayView = (GestureOverlayView) this.findViewById(R.id.gestures);
 //只针对单笔手势:overlayView.addOnGesturePerformedListener(new GesturePerformedListener());
 overlayView.addOnGestureListener(new GestureListener());
}

 public void find(View v){

recognize(mgesture);

overlayView.clear(true);
}

 private final class GestureListener implements OnGestureListener{


public void onGestureStarted(GestureOverlayView overlay, MotionEvent event) {






}


public void onGesture(GestureOverlayView overlay, MotionEvent event) {






}


public void onGestureEnded(GestureOverlayView overlay, MotionEvent event) {



mgesture = overlay.getGesture();


}


public void onGestureCancelled(GestureOverlayView overlay, MotionEvent event) {


}
}

 private final class GesturePerformedListener implements OnGesturePerformedListener{


public void onGesturePerformed(GestureOverlayView overlay, Gesture gesture) {



recognize(gesture);


}


}

 private void recognize(Gesture gesture) {


ArrayList predictions = library.recognize(gesture);


if(!predictions.isEmpty()){



Prediction prediction = predictions.get(0);
//6表示60%相似



if(prediction.score >= 6){
//call和close是我们在建立手势库时给手势取得名字




if("call".equals(prediction.name)){





Intent intent = new Intent(Intent.ACTION_CALL, Uri.parse("tel:1350505050"));





startActivity(intent);




}else if("close".equals(prediction.name)){





finish();//关闭Activity




}



}else{




Toast.makeText(getApplicationContext(), R.string.low, 1).show();



}


}else{



Toast.makeText(getApplicationContext(), R.string.notfind, 1).show();


}

}


@Override

protected void onDestroy() {


super.onDestroy();


android.os.Process.killProcess(android.os.Process.myPid());//关闭应用

}
大家看得出来,我这里定义了两个手势动作,当手势形如手势库中call时,就拨打电话,当手势形如手势库中close时,就退出程序。ok,手势识别开发就这么简单,我们可以再这基础之上做一些复杂的,比如实现手势解锁。思想很简单,我们可以修改下GesturesBuilder的源代码放入自己的工程,用户自己定义好手势动作后将其保存在手势库中,这样用户就可以用手势验证了。 

你可能感兴趣的:(Android,开发)