Android 应用程序查找设备的方法——以串口为例

 

Android 应用程序要经常访问底层设备,访问设备就要用到设备文件描述符,在应用 open ()函数打开设备前,需要先找到设备的路径,因此我们需要通过 JDK 中各种访问文件的方法来查找到设备的路径。这里以串口设备的查找为例,分析一下 Android 应用程序查找设备路径的过程:

1. 查找设备驱动

这是查找串口驱动的源码程序:

private Vector<Driver> mDrivers = null ;

Vector<Driver> getDrivers() throws IOException {

if ( mDrivers == null ) {

mDrivers = new Vector<Driver>();

LineNumberReader r = new LineNumberReader(new FileReader("/proc/tty/drivers"));

String l;

while ((l = r.readLine()) != null ) {

String[] w = l.split( " +" );

if ((w. length == 5) && (w[4].equals( "serial" ))) {

Log.d( TAG , "Found new driver: " + w[1]);

mDrivers .add( new Driver(w[0], w[1]));

}

}

r.close();

}

return mDrivers ;

}

该步骤先创建一个新的行号阅读器 LineNumberReader ,读取 /proc/tty/drivers 文件,我在开发板上摘取 /proc/tty/drivers 的文件内容如下:

# cat drivers

/dev/tty          /dev/tty         5    0     system:/dev/tty

/dev/console   /dev/console   5   1    system:console

/dev/ptmx      /dev/ptmx       5    2    system

/dev/vc/0      /dev/vc/0         4    0    system:vtmaster

sdio_uart        /dev/ttySDIO   250  0-7   serial

usbserial        /dev/ttyUSB    188   0-253    serial

ttySAC      /dev/s3c2410_serial  204   64-67   serial

serial         /dev/ttyS          4    64-67      serial

pty_slave     /dev/pts      136    0-1048575    pty:slave

pty_master   /dev/ptm    128    0-1048575    pty:master

pty_slave     /dev/ttyp     3       0-255       pty:slave

pty_master  /dev/pty       2       0-255       pty:master

unknown      /dev/tty       4       1-63         console

然后,逐行读取,取出满足条件的行,添加到驱动队列中。

2. 查找设备

这是查找串口设备的源码程序:

Vector<File> mDevices = null ;

public Vector<File> getDevices() {

if ( mDevices == null ) {

mDevices = new Vector<File>();

File dev = new File( "/dev" );

File[] files = dev.listFiles();

int i;

for (i=0; i<files. length ; i++) {

if ( files[i].getAbsolutePath().startsWith(mDeviceRoot) ) {

Log.d( TAG , "Found new device: " + files[i]);

mDevices .add(files[i]);

}

}

}

return mDevices ;

}

在找到驱动后,就要查找符合驱动的设备,本段程序实现在 "/dev" 文件下查找串口驱动的设备,这里 mDeviceRoot 是 /dev/ttySDIO 、 /dev/ttyUSB 、 /dev/s3c2410_serial 和 /dev/ttyS 。

下面是开发板上的 "/dev" 文件部分内容:

# cd /dev

# ls

:

s3c-pp

s3c-rotator

s3c2410_serial0

s3c2410_serial1

s3c2410_serial2

s3c2410_serial3

snd

socket

:

ttyS0

ttyS1

ttyS2

ttyS3

:

通过这个方法的实现,便可以查找到串口设备的路径。

  • 1
    点赞
  • 5
    收藏
    觉得还不错? 一键收藏
  • 3
    评论
评论 3
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值