问题
I want to use CreateProcess() to execute an ADB command that launches an application/activity. It works using the simpler system(command) function, but I want to eliminate the creation of the command line window by system(). Below is what I have right now. I have tried using different CreateProcess()es, like CreateProcessW and CreateProcessA, but to no avail.
char prog[] = "C:\\Program Files\\Android\\sdk\\platform-tools\\platform-tools\\adb.exe";
char args[] = "adb shell am start -a android.intent.action.MAIN -n com.example.dmiller.myapplication/.Blankscreen";
STARTUPINFO si;
PROCESS_INFORMATION pi;
ZeroMemory(&si, sizeof(si));
si.cb = sizeof(si);
ZeroMemory(&pi, sizeof(pi));
CreateProcess((LPCWSTR)prog, (LPWSTR)args, NULL, NULL, FALSE, CREATE_NO_WINDOW, NULL, NULL, &si, &pi);
I got this partially from this answer How to use createprocess to execute adb program in PATH? but when the command should be executed in my program, nothing happens (when running system(cmd.c_str()), the appropriate app is launched on the attached device). Could anyone provide some help? Alternative methods are welcome as well.
UPDATE: I have applied some things from the below post to try to provide a better question. Code has been updated to my latest version.
CreateProcess doesn't pass command line arguments
回答1:
Type-casting a char
array to have type LPCWSTR
doesn't make it so. The former is an array of one-byte characters. The latter is (a pointer to) an array of two-byte characters. The type cast tells the compiler that the one is really the other, and the compiler trusts you. It does not perform a conversion.
To fix this, declare prog
and args
to have type WCHAR
or wchar_t
instead of char
, and use the L
prefix on the literals:
WCHAR prog[] = L"...";
WCHAR args[] = L"...";
Then you can remove the LPCWSTR
type casts because they won't be necessary anymore.
As usual, whenever you call an API function, it's wise to check the return value and look for any error codes. The documentation advises that you should check whether the function returns zero. If it does, call GetLastError
to find out what the OS thinks the problem was.
来源:https://stackoverflow.com/questions/28637144/use-createprocess-to-execute-adb-command