MTP USB开发
mtpmain.cpp
如下
int main(int argc, char** argv)
{
int ret;
pthread_t inotifyWatchMediaThread;
//Initialize
myDatabase = new MyMtpDatabase();//新建数据库
int fd = open("/dev/mtp_usb", O_RDWR); //fd is closed in MtpServer::run.
if (fd < 0) {
ALOGI("could not open MTP driver, exit with errno %d\n", errno);
return -1;
}
gid_t gid = getgid();
ALOGD("MTP daemon gid %d fd %d\n", gid, fd);
mServer = new MtpServer(fd, myDatabase, false, gid, 0644, 0775);
myDatabase->setMtpServer(mServer);
mInotifyMediaFd = inotify_init();
ret = pthread_create(&inotifyWatchMediaThread, NULL, inotifyWatchMedia, NULL);
if (ret < 0) {
ALOGE("Can't create notifier_thread to monitor /media change in target MTP device\n");
goto fail;
}
inotifyAddWatch();
checkInternalSDcardMounted();
checkExternalSDcardMounted();
installSignalHandler();
//MTP protocol handler
mServer->run();
fail:
//Release
if (mStorage != NULL)
notifyRemoveSDcard();
delete mServer;
delete myDatabase;
if (mExternalStorage != NULL)
notifyRemoveExternalSDcard();
close(mInotifyMediaFd);
}
我们的是基于高通的平台,要显示手机内部存储还有外扩地存储卡,程序中先创建数据库,然后检查mtp的usb驱动是否正常安装,
然后创建一个mtpserver,server绑定数据库。同时开启监听机制,用于监听挂载的情况,创建线程是为了轮询挂载的情况, inotifyAddWatch();整函数内部实现是将/media这个文件夹添加到监听机制列表,
static void inotifyAddWatch() {
ALOGD("%s\n", __func__);
inotify_add_watch(mInotifyMediaFd, "/media",
IN_CREATE | IN_DELETE | IN_MODIFY);
}
当有创建,删除,修改的时候便有中断产生,中断监听在线程里边实现的,
if (ievent->len > 0 && ievent->mask & IN_CREATE &&
!strcmp(ievent->name, "sdcard")) {
// notifyAddExternalSDcard();//
notifyAddSDcard();
} else if (ievent->len > 0 && ievent->mask & IN_DELETE &&
!strcmp(ievent->name, "sdcard")) {
if (mStorage != NULL)
// notifyRemoveExternalSDcard();//
notifyRemoveSDcard();
}
用于监听/media下是否月有sdcard的变动。
checkInternalSDcardMounted();
checkExternalSDcardMounted();
这两个函数主要用于检查内部存储和外部sd卡的挂载情况,以外部存储卡举例来说
fp = fopen("/proc/mounts", "r");
if (fp == NULL) {
ALOGE("%s: could not open /proc/mounts, errno %d\n", __func__, errno);
return;
}
while (!feof(fp)) {
fgets(buf, 128, fp);
if(strstr(buf, "/mnt/sdcard")) {
// ln /media/sdcard to /home/linaro/media if not.
/* if(access("/media/sdcard", F_OK) < 0) {
pid = fork();
if (!pid) {
execl("/bin/ln", "ln", "-sf", "/mnt/sdcard", "/media/sdcard", NULL);
exit(-1);
} else if (pid > 0) {
waitpid(pid, NULL, 0);
ALOGD("%s: finish to ln /media/sdcard\n", __func__);
}
} else
*/{
notifyAddExternalSDcard();
}
break;
}
我们将外部卡存储在/mnt/sdcard路径下,如果在/proc/mounts下发现/mnt/sdcard说明挂载成功。