我们在Windows下常常有一些快捷键来启动某个应用的需求,同样在我们的Android系统下也可以实现这样的作用。

比如按下CAMERA键,来启动Camera应用。

使用步骤如下,

1 先定义好CAMEAR键值,比如KEYCODE_CAMERA=27并要在xxx_Keypad.kl定义好扫描码与CAMERA对应的关系

如 key 212   CAMERA

2 定义相关BROADCAST_INTENT_ACTION @Intent.java

@SdkConstant(SdkConstantType.BROADCAST_INTENT_ACTION)

public static final String ACTION_CAMERA_BUTTON = "android.intent.action.CAMERA_BUTTON";

3 在系统文件PhoneWindow.java中有onKeyDown()函数来捕获CAMERA键值并发送相关intent.

case KeyEvent.KEYCODE_CAMERA: {

....

// Broadcast an intent that the Camera button was longpressed

Intent intent = new Intent(Intent.ACTION_CAMERA_BUTTON, null);

intent.putExtra(Intent.EXTRA_KEY_EVENT, event);

getContext().sendOrderedBroadcast(intent, null);

}

4 在camera应用下如果要接收这个Broadcast消息,需要在AndroidManifest.xml中增加receive 相关的intent-filter.

5 定义类CameraButtonIntentReceiver 并重载onReceive方法来启动CameraActivity

public class CameraButtonIntentReceiver extends BroadcastReceiver {

public CameraButtonIntentReceiver() {

}

@Override

public void onReceive(Context context, Intent intent) {

// Try to get the camera hardware

CameraHolder holder = CameraHolder.instance();

if (holder.tryOpen() == null) return;

// We are going to launch the camera, so hold the camera for later use

holder.keep();

holder.release();

Intent i = new Intent(Intent.ACTION_MAIN);

i.setClass(context, Camera.class);

i.addCategory("android.intent.category.LAUNCHER");

i.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK);

context.startActivity(i);

}

}

Logo

为开发者提供学习成长、分享交流、生态实践、资源工具等服务,帮助开发者快速成长。

更多推荐