前言
如果在Android 的C/C++层或者JNI层有获取屏幕分辨率的需求,或者需要获取设备的触屏设备用来做点事情,可以参考一下代码
代码示例
#include <stdlib.h>
#include <stdio.h>
#include <gui/ISurfaceComposer.h>
#include <gui/Surface.h>
#include <gui/SurfaceComposerClient.h>
#include <ui/DisplayInfo.h>
#include <fcntl.h>
#include <sys/stat.h>
#include <sys/types.h>
#include <sys/ioctl.h>
#include <linux/input.h>
#include <unistd.h>
#include <dirent.h>
#define test_bit(bit, array) (array[bit/8] & (1<<(bit%8)))
#define sizeof_bit_array(bits) ((bits + 7) / 8)
using namespace android;
bool containsNonZeroByte(const uint8_t* array, uint32_t startIndex, uint32_t endIndex) {
const uint8_t* end = array + endIndex;
array += startIndex;
while (array != end) {
if (*(array++) != 0) {
return true;
}
}
return false;
}
int getTouchDevice()
{
char name[64]; /* RATS: Use ok, but could be better */
char buf[256] = { 0, }; /* RATS: Use ok */
int fd = 0;
int i;
uint8_t keyBitmask[(KEY_MAX + 1) / 8];
uint8_t absBitmask[(ABS_MAX + 1) / 8];
char devname[PATH_MAX];
char *filename;
char *dirname = "/dev/input/";
DIR *dir;
struct dirent *de;
dir = opendir(dirname);
if(dir == NULL)
return -1;
strcpy(devname, dirname);
filename = devname + strlen(devname);
*filename++ = '/';
while((de = readdir(dir))) {
if(de->d_name[0] == '.' &&
(de->d_name[1] == '\0' ||
(de->d_name[1] == '.' && de->d_name[2] == '\0'))) {
continue;
}
strcpy(filename, de->d_name);
if ((fd = open(devname, O_RDONLY, 0)) >= 0)
{
ioctl(fd, EVIOCGNAME(sizeof(buf)), buf);
ioctl(fd, EVIOCGBIT(EV_KEY, sizeof(keyBitmask)), keyBitmask);
ioctl(fd, EVIOCGBIT(EV_ABS, sizeof(absBitmask)), absBitmask);
bool haveGamepadButtons = containsNonZeroByte(keyBitmask, sizeof_bit_array(BTN_MISC),
sizeof_bit_array(BTN_MOUSE))
|| containsNonZeroByte(keyBitmask, sizeof_bit_array(BTN_JOYSTICK),
sizeof_bit_array(BTN_DIGI));
if (test_bit(ABS_MT_POSITION_X, absBitmask)
&& test_bit(ABS_MT_POSITION_Y, absBitmask)) {
if (test_bit(BTN_TOUCH, keyBitmask) || !haveGamepadButtons) {
printf("MT TOPUCH DeviceL: %s\n", devname);
}
// Is this an old style single-touch driver?
else if (test_bit(BTN_TOUCH, keyBitmask)
&& test_bit(ABS_X, absBitmask)
&& test_bit(ABS_Y, absBitmask)) {
printf("Old TOPUCH DeviceL: ", devname);
// Is this a BT stylus?
}
}
printf("name: %s\n\n\n", buf);
close(fd);
}
}
closedir(dir);
return 0;
}
int main(){
getTouchDevice();
sp<IBinder> dtoken(SurfaceComposerClient::getBuiltInDisplay(
ISurfaceComposer::eDisplayIdMain));
DisplayInfo dinfo;
status_t status = SurfaceComposerClient::getDisplayInfo(dtoken, &dinfo);
if (status)
return -1;
printf("h:%d, w:%d\n", dinfo.h, dinfo.w);
return 0;
}