Ive looked but havnt managed to find a windows .exe convertor to windows mobile. Ive found a program which can shutdown remote pcs on the same network and want to port it to my windows mobile (6.1) - HTC Kaiser.
Ive installed the visual studio and the sdk aswell as the 2.0 mobile framework.
Any ideas where to go from here?
Thanks
Source code to Windows App...
Code:
//-----------------------------------------------------------
// Remote Shutdown v1.0 Console Mode
// Copyright (C) 2002, MATCODE Software
// http://www.matcode.com
// Author: Vitaly Evseenko
//-----------------------------------------------------------
#include <windows.h>
#include <stdlib.h>
#include <stdio.h>
#pragma hdrstop
int RemoteShutdown(LPSTR lpMachineName, LPSTR lpMessage,
DWORD dwTimeout, BOOL bForceAppsClosed,
BOOL bRebootAfterShutdown )
{
HANDLE hToken;
TOKEN_PRIVILEGES TokenPrivileges;
OpenProcessToken( GetCurrentProcess(),
TOKEN_ADJUST_PRIVILEGES | TOKEN_QUERY, &hToken ) ;
LookupPrivilegeValue( NULL, SE_REMOTE_SHUTDOWN_NAME, &(TokenPrivileges.Privileges[0].Luid));
TokenPrivileges.PrivilegeCount = 1;
TokenPrivileges.Privileges[0].Attributes = 2;
AdjustTokenPrivileges( hToken, FALSE, &TokenPrivileges,
sizeof(TOKEN_PRIVILEGES), NULL, NULL );
if(!InitiateSystemShutdown(
lpMachineName, // name of computer to shut down
lpMessage, // address of message to display
dwTimeout, // time to display dialog box
bForceAppsClosed, // force applications with unsaved changes flag
bRebootAfterShutdown ))
{
return GetLastError();
}
return 0;
}
void OutUsage(void)
{
printf("\nUsage: RSD-CON ComputerName [Message] [/tnn] [/f] [/s]\n");
printf("\tComputerName - remote computer name\n");
printf("\tMessage - specify message to display\n");
printf("\t/t - time to display message (nn seconds)\n");
printf("\t/f - do not force applications with unsaved changes flag\n");
printf("\t/s - the computer is to shut down.\n");
printf("Example: RSD-CON PC_LARRY This computer will be restarted now. /t20\n");
}
void main( int argc, char *argv[] )
{
char szMachineName[100];
char szMessage[200];
DWORD dwTimeout;
BOOL bForceAppsClosed;
BOOL bRebootAfterShutdown;
int i, Err;
printf("Remote Shutdown v1.0, Console\n");
printf("Copyright (C) 2002, MATCODE Software\n");
printf("http://www.matcode.com\n");
if (GetVersion() & 0x80000000) // Not Windows NT/2000/XP
{
printf("\n\tThis is a Windows NT/2000/XP application.\n"
"This program will not work on Windows 95/98/ME !\n");
return;
}
if(argc<2)
{
OutUsage();
return;
}
strcpy(szMachineName, argv[1]);
dwTimeout = 0;
bForceAppsClosed = TRUE;
bRebootAfterShutdown = TRUE;
szMessage[0] = '\0';
for( i = 2; i < argc; i++ )
{
// if not started with / then message ;-)
if( argv[i][0] != '/')
{
strcat(szMessage, argv[i]);
strcat(szMessage, " ");
continue;
}
// parse option type
if(argv[i][1]=='t' || argv[i][1]=='T')
{
dwTimeout = atol(&argv[i][2]);
}
else if(argv[i][1]=='f' || argv[i][1]=='F')
{
bForceAppsClosed = FALSE;
}
else if(argv[i][1]=='s' || argv[i][1]=='S')
{
bRebootAfterShutdown = FALSE;
}
}
if (dwTimeout == 0 && szMessage[0])
{
dwTimeout = 5;
}
Err = RemoteShutdown(szMachineName, szMessage,
dwTimeout, bForceAppsClosed,
bRebootAfterShutdown );
if(Err)
{
LPSTR lpstErr = "\0";
if(Err == 53)
{
lpstErr = "The network path was not found.\n"
"Invalid computer name or is not Windows NT/2000/XP machine.\n";
}
else if(Err == 5)
{
lpstErr = "Access is denied. You have no administrative rights on the specified computer.\n";
}
printf("\nUnable to shutdown computer %s, Error: %d.\n%s",
szMachineName, Err, lpstErr);
OutUsage();
}
else
{
printf("\nComputer %s is shut down.\n", szMachineName);
}
}
Hi
This is not that easy. While a lot API calls exists in both Windows and WinMo I doubt that the ones used in this tool are available.
cool this is one development many people is waiting for, especially me
wish you good luck
Hi..interesting topics anyway.
As long as the APIs used in Windows app are also available in Windows Mobile, that will be possible IMO.
The one I'm sure about, the Windows Mobile apps built using .net, will also be available to run in Windows
Related
Hi !
I testing make Out of procces server on XDA II (MDA II) in eVc++4. I have problems
with this. If i called in client this :
IComMDA m_ComMda;
COleException m_Error;
if (m_ComMda.CreateDispatch(_T("ComMDA.Document"),&m_Error))
{
AfxMessageBox(_T("CreateDispatch - TRUE"),MB_OK,0);
return TRUE;
}
else
{
AfxMessageBox(_T("CreateDispatch - FALSE"),MB_OK,0);
return FALSE;
}
the error occur
==> CreateDispatch returning scode = severity: SEVERITY_ERROR, facility:
FACILITY_WIN32 ($800700C1).
IComMDA is class created from typelibrary :
class IComMDA : public COleDispatchDriver
{
public:
IComMDA() {} // Calls COleDispatchDriver default constructor
IComMDA(LPDISPATCH pDispatch) : COleDispatchDriver(pDispatch) {}
IComMDA(const IComMDA& dispatchSrc) : COleDispatchDriver(dispatchSrc) {}
// Attributes
public:
// Operations
public:
BOOL InitInterface();
};
interface is declared :
[ uuid(713B5595-EF1F-4961-A179-E374E0C82903), version(1.0) ]
library ComMDA
{
importlib("stdole32.tlb");
importlib("stdole2.tlb");
// Primary dispatch interface for CComMDADoc
[ uuid(901AD61B-9974-448a-9E79-7898E0C80FFE) ]
dispinterface IComMDA
{
properties:
// NOTE - ClassWizard will maintain property information here.
// Use extreme caution when editing this section.
//{{AFX_ODL_PROP(CComMDADoc)
//}}AFX_ODL_PROP
methods:
// NOTE - ClassWizard will maintain method information here.
// Use extreme caution when editing this section.
//{{AFX_ODL_METHOD(CComMDADoc)
[id(1)] boolean InitInterface();
//}}AFX_ODL_METHOD
};
// Class information for CComMDADoc
[ uuid(E523187A-FFB7-46e9-AA64-A6CB1BEAF9BB) ]
coclass Document
{
[default] dispinterface IComMDA;
};
//{{AFX_APPEND_ODL}}
//}}AFX_APPEND_ODL}}
};
Class is registered as :
CString strServerName;
CString strLocalServerName;
CString strLocalShortName;
CString strLocalFilterName;
CString strLocalFilterExt;
if (!m_pDocTemplate->GetDocString(strServerName,
CDocTemplate::regFileTypeId) || strServerName.IsEmpty())
{
return;
}
if (!m_pDocTemplate->GetDocString(strLocalServerName,
CDocTemplate::regFileTypeName))
strLocalServerName = strServerName; // use non-localized name
if (!m_pDocTemplate->GetDocString(strLocalShortName,
CDocTemplate::fileNewName))
strLocalShortName = strLocalServerName; // use long name
if (!m_pDocTemplate->GetDocString(strLocalFilterName,
CDocTemplate::filterName))
ASSERT(nAppType != OAT_DOC_OBJECT_SERVER);
if (!m_pDocTemplate->GetDocString(strLocalFilterExt,
CDocTemplate::filterExt))
ASSERT(nAppType != OAT_DOC_OBJECT_SERVER);
ASSERT(strServerName.Find(' ') == -1); // no spaces allowed
int nIconIndex = 0;
POSITION pos = AfxGetApp()->GetFirstDocTemplatePosition();
for (int nIndex = 1; pos != NULL; nIndex++)
{
CDocTemplate* pTemplate = AfxGetApp()->GetNextDocTemplate(pos);
if (pTemplate == m_pDocTemplate)
{
nIconIndex = nIndex;
pos = NULL; // set exit condition
}
}
BOOL bResult = FALSE;
if (TRUE)
{
// call global helper to modify system registry
// progid, shortname, and long name are all equal in this case
if (!(bResult = AfxOleRegisterServerClass(m_clsid, strServerName,
strLocalShortName, strLocalServerName, nAppType,
rglpszRegister, rglpszOverwrite, nIconIndex,
strLocalFilterName, strLocalFilterExt)))
{
// not fatal (don't fail just warn)
AfxMessageBox(AFX_IDP_FAILED_TO_AUTO_REGISTER);
}
}
else
{
bResult = AfxOleUnregisterServerClass(m_clsid, m_lpszProgID, m_lpszProgID,
m_lpszProgID, OAT_DISPATCH_OBJECT);
}
return;
------------------------------------------------
type library is registered as AfxOleRegisterTypeLib(AfxGetInstanceHandle(),
clsid);
where >// {713B5595-EF1F-4961-A179-E374E0C82903}
static const GUID clsid =
{ 0x713b5595, 0xef1f, 0x4961, { 0xa1, 0x79, 0xe3, 0x74, 0xe0, 0xc8, 0x29,
0x3 } };
Thanks for your help.
Save me from madness!!!
I have a several smartphone devices with windows CE
CE 6.0 - hp IPAQ 500 series
CE 5.0 - Samsung i600
I need to inject DLL into the process "home.exe". I use method with performcallback4 function. This method works successfully for all processes ("device.exe", "service.exe", etc.) except process "home.exe". In what a problem?
source code : InjectDLL.exe link with toolhelp.lib
#include <windows.h>
#include <Tlhelp32.h>
typedef struct _CALLBACKINFO {
HANDLE hProc;
FARPROC pfn;
PVOID pvArg0;
} CALLBACKINFO;
extern "C"
{
DWORD PerformCallBack4(CALLBACKINFO *pcbi,...);
LPVOID MapPtrToProcess(LPVOID lpv, HANDLE hProc);
BOOL SetKMode(BOOL fMode);
DWORD SetProcPermissions(DWORD newperms);
};
DWORD GetProcessId(WCHAR *wszProcessName)
{
HANDLE hTH= CreateToolhelp32Snapshot(TH32CS_SNAPPROCESS, 0);
PROCESSENTRY32 pe;
pe.dwSize= sizeof(PROCESSENTRY32);
DWORD PID=0;
if (Process32First(hTH, &pe))
{
do {
if (wcsicmp(wszProcessName, pe.szExeFile)==0)
{
PID=pe.th32ProcessID;
}
} while (Process32Next(hTH, &pe));
}
CloseToolhelp32Snapshot(hTH);
return PID;
}
HMODULE GetDllHandle(DWORD ProcessId,WCHAR* ModuleName)
{
HANDLE ToolHelp=CreateToolhelp32Snapshot(TH32CS_SNAPMODULE,ProcessId);
if (ToolHelp!=INVALID_HANDLE_VALUE)
{
MODULEENTRY32 ModuleEntry={sizeof MODULEENTRY32};
if (Module32First(ToolHelp,&ModuleEntry))
do
{
if (wcsicmp(ModuleEntry.szModule, ModuleName)==0)
return ModuleEntry.hModule;
}
while(Module32Next(ToolHelp,&ModuleEntry));
CloseToolhelp32Snapshot(ToolHelp);
}
return NULL;
}
BOOL InjectDll(WCHAR* ProcessName,WCHAR* ModuleName)
{
DWORD ProcessId=GetProcessId(ProcessName);
HMODULE ModuleHandle=GetDllHandle(ProcessId,ModuleName);
if (ModuleHandle!=NULL)
return TRUE;
HANDLE Process=OpenProcess(0,0,ProcessId);
if (Process==NULL)
return FALSE;
void* ModuleNamePtr=MapPtrToProcess(ModuleName,GetCurrentProcess());
if (ModuleNamePtr==NULL)
return FALSE;
CALLBACKINFO ci;
ci.hProc=Process;
void* LoadLibraryPtr=MapPtrToProcess(GetProcAddress(GetModuleHandle(L"coredll.dll"),L"LoadLibraryW"),Process);
if (LoadLibraryPtr==NULL)
return FALSE;
ci.pfn=(FARPROC)LoadLibraryPtr;
ci.pvArg0=ModuleNamePtr;
PerformCallBack4(&ci); in this place process exit. visual studio output message : "process exit with code 0xc0000030"
Sleep(500);
CloseHandle(Process);
return GetDllHandle(ProcessId,ModuleName)!=NULL;
}
extern "C"
{
BOOL SetKMode(BOOL fMode);
DWORD SetProcPermissions(DWORD newperms);
};
#define DLLNAME L"MyDll.dll"
int WINAPI WinMain(HINSTANCE hInstance,HINSTANCE hPrevInstance,LPWSTR lpCmdLine,int nShowCmd)
{
WCHAR Path[MAX_PATH];
GetModuleFileName(NULL,Path,MAX_PATH);
wcscpy(wcsrchr(Path,L'\\')+1,DLLNAME);
WCHAR NewPath[MAX_PATH]=L"\\Windows\\";
wcscat(NewPath,DLLNAME);
CopyFile(Path,NewPath,FALSE);
BOOL Res=InjectDll(L"home.exe",L"MyDll.dll");
return 0;
}
the error code is
#define STATUS_INVALID_PARAMETER_MIX 0xC0000030
(maybe too fast for getting the thread infos?)
try to make the "Sleep(500);" before "PerformCallBack4(&ci);"
I have tried, a problem not in it. Any ideas?
I have not found the reason.... I Use other method without performcallback4
Problem with injection dll to cprog.exe process?
I want to inject dll to cprog.exe process. but it doesn't work.
source code.
Code:
VOID
InjectDllToCprog()
{
WCHAR DllPath[MAX_PATH] = L"";
CallbackInfo ci;
GetModuleFileName(NULL, DllPath, MAX_PATH);
PWCHAR p = wcsrchr(DllPath, L'\\');
DllPath[p - DllPath] = '\0';
wcscat(DllPath, L"\\CprogInject.dll");
ZeroMemory(&ci, sizeof(ci));
g_hCprog = FindCprogProcess(L"Cprog.exe"); // the handle is right.
if(g_hCprog != NULL)
{
DWORD dwMode = SetKMode(TRUE);
DWORD dwPerm = SetProcPermissions(0xFFFFFFFF);
FARPROC pFunc = GetProcAddress(GetModuleHandle(L"Coredll.dll"), L"LoadLibraryW");
ci.ProcId = (HANDLE)g_hCprog;
ci.pFunc = (FARPROC)MapPtrToProcess(pFunc, g_hCprog);
ci.pvArg0 = MapPtrToProcess(DllPath, GetCurrentProcess());
g_InjectCprog = (HINSTANCE)PerformCallBack4(&ci, 0, 0, 0);
if(GetLastError() != 0) // GetLastError() = 5
DbgError(L"PerformCallBack 执行失败", GetLastError());
SetKMode(dwMode);
SetProcPermissions(dwPerm);
}
}
GetLastError() return 0x00000005(Access is denied)
Anyone can help me? Sorry for my poor english.
Hi All,
I am developing a VOIP application for Windows Mobile. I want the user to switch the between the Speaker and Earpiece of the Mobile Phone. I have searched the Forum and found the following link
http://teksoftco.com/forum/viewtopic.php?p=1909
As you know we have to use LoadLibrary and GetProcAddress to access the RIL APIs in Windows Mobile. I have written following piece of code for this i.e.
Code:
HRIL hRIL;
bool speakerphone = true; // false;
HRESULT result = RIL_Initialize(1, ResultCallback, NotifyCallback, RIL_NCLASS_MISC, 0, &hRIL);
if (result != S_OK) {
wchar_t buffer[200];
wsprintf(buffer, L"Could not open RIL, error=0x%x", result);
AfxMessageBox(buffer);
return;
}
RILAUDIODEVICEINFO info;
info.cbSize = sizeof(info);
info.dwParams = RIL_PARAM_ADI_ALL; // RIL_PARAM_ADI_TXDEVICE;
info.dwRxDevice = RIL_AUDIO_HANDSET;
info.dwTxDevice = speakerphone ? RIL_AUDIO_NONE : RIL_AUDIO_HANDSET;
result = RIL_SetAudioDevices(hRIL, &info);
if (result != S_OK) {
wchar_t buffer[200];
wsprintf(buffer, L"Could not open RIL, error=0x%x", result);
AfxMessageBox(buffer);
}
RIL_Deinitialize(hRIL);
But this doesn't seems to work, i.e. some time it causes both the audio input and output to halt, sometime audio input is halted (i.e. no voice is heard on the other end).
I have also tried another techniques to accomplish this task, like:
Technique 2
--------------
Code:
#define MM_WOM_FORCESPEAKER (WM_USER+2)
static void SetSpeakerMode(bool speakerphone)
{
MMRESULT result = waveOutMessage((HWAVEOUT)0, MM_WOM_FORCESPEAKER, speakerphone, 0);
if (result != MMSYSERR_NOERROR) {
wchar_t buffer[200];
wsprintf(buffer, L"Could not do speakerphone switch, error=%u", result);
AfxMessageBox(buffer);
}
}
Technique 3
--------------
Code:
/* Stuff from Wavedev.h */
#define IOCTL_WAV_MESSAGE 0x001d000c
typedef struct {
UINT uDeviceId;
UINT uMsg;
DWORD dwUser;
DWORD dwParam1;
DWORD dwParam2;
} MMDRV_MESSAGE_PARAMS;
/* End of Wavedev.h extract */
class WavDevice
{
private:
HANDLE hWavDev;
public:
WavDevice()
{
hWavDev = CreateFile(TEXT("WAV1:"), GENERIC_READ | GENERIC_WRITE, 0, NULL, OPEN_EXISTING, 0, NULL);
if (hWavDev == INVALID_HANDLE_VALUE) {
wchar_t buffer[200];
wsprintf(buffer, L"Could not open device, error=%u", GetLastError());
AfxMessageBox(buffer);
}
}
~WavDevice()
{
if (hWavDev != INVALID_HANDLE_VALUE)
CloseHandle(hWavDev);
}
bool SendMessage(UINT uMsg, DWORD dwParam1 = 0, DWORD dwParam2 = 0)
{
if (hWavDev == INVALID_HANDLE_VALUE)
return false;
DWORD dwRet = 0, dwOut;
MMDRV_MESSAGE_PARAMS mp;
memset(&mp,0,sizeof(mp));
mp.uMsg = uMsg;
mp.dwParam1 = dwParam1;
mp.dwParam2 = dwParam2;
if (DeviceIoControl(hWavDev, IOCTL_WAV_MESSAGE, &mp, sizeof(mp), &dwOut, sizeof(dwOut), &dwRet, 0))
return true;
wchar_t buffer[200];
wsprintf(buffer, L"Could not do speakerphone switch, error=%u", GetLastError());
AfxMessageBox(buffer);
return false;
}
};
static void SetSpeakerMode(bool speakerphone)
{
WavDevice wd;
if (!wd.SendMessage(1002, speakerphone ? 0 : 2))
return;
if (!wd.SendMessage(1012, speakerphone ? 0 : 1))
return;
if (speakerphone && !wd.SendMessage(1013))
return;
wd.SendMessage(1000, speakerphone ? 2 : 4, speakerphone ? 0 : 7);
}
Technique 4
--------------
Code:
class OsSvcsDll
{
private:
HMODULE hDLL;
typedef HRESULT (* SetSpeakerModeFn)(DWORD mode);
SetSpeakerModeFn pfnSetSpeakerMode;
public:
OsSvcsDll()
{
hDLL = LoadLibrary(L"\\windows\\ossvcs.dll");
if (hDLL == NULL) {
wchar_t buffer[200];
wsprintf(buffer, L"Could not open DLL, error=%u", GetLastError());
AfxMessageBox(buffer);
}
pfnSetSpeakerMode = (SetSpeakerModeFn)GetProcAddress(hDLL, (LPCTSTR)218);
if (pfnSetSpeakerMode == NULL) {
wchar_t buffer[200];
wsprintf(buffer, L"Could not open DLL, error=%u", GetLastError());
AfxMessageBox(buffer);
}
}
~OsSvcsDll()
{
if (hDLL != NULL)
FreeLibrary(hDLL);
}
bool SetSpeakerMode(DWORD speakerphone)
{
if (pfnSetSpeakerMode == NULL)
return false;
HRESULT result = pfnSetSpeakerMode(speakerphone);
if (result == 0)
return true;
wchar_t buffer[200];
wsprintf(buffer, L"Could not do speakerphone switch, error=0x%x", result);
AfxMessageBox(buffer);
return false;
}
};
static void SetSpeakerMode(bool speakerphone)
{
OsSvcsDll dll;
dll.SetSpeakerMode(speakerphone ? 1 : 0);
}
But no procedure seems to work properly.
Can you please guide me where i am going wrong or some other way of achieving this.
I am using
Visual C++ MFC Dialog based Application
Visual Studio 2008
Windows Mobile 6 SDK For PocketPC
I have tested the above mentioned sample on
HTC Touch
Sony Erricsson XPeria
Waiting for response.
Regards,
Ghazanfar Ali
Regards,
Ghazanfar Ali
When I try to create a socket in a C++ program I get an INVALID_SOCKET.
I've used the code shown below and the error code from the socket function
is 10047, which according to MSDN is WSAEAFNOSUPPORT (Address family not supported by protocol family)
I've used the exact same piece of code on a HTC Touch Diamond 2 and it works. The problem only appears on the HD2.
Any help would be appreciated.
Thanks,
TJ
// Initialize WSA
WORD wVersionRequested = MAKEWORD(2,2);
if (WSAStartup(wVersionRequested, &m_wsaData) != 0)
{
Log(L"Failed to start WSA");
return false;
}
if ( LOBYTE( m_wsaData.wVersion ) != 2 ||
HIBYTE( m_wsaData.wVersion ) != 2 ) {
/* Tell the user that we could not find a usable */
/* WinSock DLL. */
Log(L"Wrong winsock version");
WSACleanup( );
return false;
}
// Create the listening socket
m_listenSocket = socket(AF_BTH, SOCK_STREAM, BTHPROTO_RFCOMM);
if (INVALID_SOCKET == m_listenSocket)
{
std::stringstream errorMessage;
errorMessage << "ERROR: Could not create socket.\n Error code: " << GetLastError();
Log(A2W(errorMessage.str().c_str()));
return false;
}
I'm an experienced developer but new to Android development. I have an app that runs some native binaries, and I provide a status indicator to show when the native process is running and when it's not. Currently I poll the device to figure this out, using the ActivityManager API to determine if specific processes are running or not.
I'm hoping there is some way to register a listener on process state changes, so I can get notified when my process starts or stops. I looked through the API, and there doesn't seem to be such a thing. Does anyone know how I can keep track of process start and stop other than polling via ActivityManager?
MidnightJava said:
I'm an experienced developer but new to Android development. I have an app that runs some native binaries, and I provide a status indicator to show when the native process is running and when it's not. Currently I poll the device to figure this out, using the ActivityManager API to determine if specific processes are running or not.
I'm hoping there is some way to register a listener on process state changes, so I can get notified when my process starts or stops. I looked through the API, and there doesn't seem to be such a thing. Does anyone know how I can keep track of process start and stop other than polling via ActivityManager?
Click to expand...
Click to collapse
Afaik there's no way to accomplish that other than your way or being system/root app. See this similar question here for reference.
Can you show how you start the process?
EmptinessFiller said:
Can you show how you start the process?
Click to expand...
Click to collapse
Sure. Here's the class that manages starting, stopping, and statusing (running or not) the binary executable. In this case, it's the omniNames service of the omni ORB (CORBA broker).
Code:
public class RHManager {
private TimerTask task = new TimerTask() {
@Override
public void run() {
if (RHManager.this.listener != null) {
listener.running(isOmniNamesRunning());
}
}
};
private IStatusListener listener;
public RHManager() {
}
public void startOmniNames() {
final Exec exec = new Exec();
final String[] args = new String[]
{RhMgrConstants.INSTALL_LOCATION_OMNI_NAMES_SCRIPTS + "/" + RhMgrConstants.OMNI_NAMES_SCRIPT_FILE,
"start"};
final String[] env = new String[] {"LD_LIBRARY_PATH=/sdcard/data/com.axiosengineering.rhmanager/omniORB/lib"};
Thread t = new Thread() {
public void run() {
try {
int res = exec.doExec(args, env);
logMsg("omniNames start return code " + res);
} catch (IOException e) {
logMsg("Failed to start omniNames");
e.printStackTrace();
}
String std = exec.getOutResult();
logMsg("omniNames start: std out==> " + std );
String err = exec.getErrResult();
logMsg("omniNames start: err out==> " + err );
};
};
t.start();
logMsg("omniNames started");
}
private boolean isOmniNamesRunning() {
String pid_s = getOmniNamesPid();
Integer pid = null;
if (pid_s != null) {
try {
pid = Integer.parseInt(pid_s);
} catch (NumberFormatException e) {
return false;
}
}
if (pid != null) {
RunningAppProcessInfo activityMgr = new ActivityManager.RunningAppProcessInfo("omniNames", pid, null);
return activityMgr.processName != null ;
}
return false;
}
public void stopOmniNames() {
String pid = getOmniNamesPid();
android.os.Process.killProcess(Integer.parseInt(pid));
android.os.Process.sendSignal(Integer.parseInt(pid), android.os.Process.SIGNAL_KILL);
}
private String getOmniNamesPid() {
Exec exec = new Exec();
final String[] args = new String[]
{RhMgrConstants.INSTALL_LOCATION_OMNI_NAMES_SCRIPTS + "/" + RhMgrConstants.OMNI_NAMES_SCRIPT_FILE,
"pid"};
String pid = "";
try {
int res = exec.doExec(args, null);
logMsg("oniNames pid return code: " + res);
} catch (IOException e) {
logMsg("Failed to start omniNames");
e.printStackTrace();
return pid;
}
String std = exec.getOutResult();
logMsg("omniNames pid: std out ==> " + std);
String err = exec.getErrResult();
logMsg("omniNames pid: err out ==> " + err);
String[] parts = std.split("\\s+");
if (parts.length >= 2) {
pid = parts[1];
}
return pid;
}
//monitor omniNames status and report status periodically to an IStatusListener
public void startMonitorProcess(IStatusListener listener, String string) {
this.listener = listener;
Timer t = new Timer();
t.schedule(task, 0, 1000);
}
private void logMsg(String msg) {
if (RhMgrConstants.DEBUG) {
System.err.println(msg);
}
}
}
Here's the Exec class that handles invocation of Runtime#exec(), consumes std and err out, and reports those and process return status to the caller.
Code:
public class Exec {
private String outResult;
private String errResult;
private Process process;
private boolean failed = false;
StreamReader outReader;
StreamReader errReader;
public int doExec(String[] cmd, String[] envp) throws IOException{
Timer t = null;
try {
process = Runtime.getRuntime().exec(cmd, envp);
outReader = new StreamReader(process.getInputStream());
outReader.setPriority(10);
errReader = new StreamReader(process.getErrorStream());
outReader.start();
errReader.start();
t = new Timer();
t.schedule(task, 10000);
int status = process.waitFor();
outReader.join();
errReader.join();
StringWriter outWriter = outReader.getResult();
outResult = outWriter.toString();
outWriter.close();
StringWriter errWriter = errReader.getResult();
errResult = errWriter.toString();
errWriter.close();
return (failed ? -1: status);
} catch (InterruptedException e) {
return -1;
} finally {
if (t != null) {
t.cancel();
}
}
}
public int doExec(String[] cmd) throws IOException{
return doExec(cmd, null);
}
public String getOutResult(){
return outResult;
}
public String getErrResult(){
return errResult;
}
private static class StreamReader extends Thread {
private InputStream is;
private StringWriter sw;
StreamReader(InputStream is) {
this.is = is;
sw = new StringWriter(30000);
}
public void run() {
try {
int c;
while ((c = is.read()) != -1){
sw.write(c);
}
}
catch (IOException e) { ; }
}
StringWriter getResult() {
try {
is.close();
} catch (IOException e) {
System.err.println("Unable to close input stream in StreamReader");
}
return sw;
}
}
private TimerTask task = new TimerTask() {
@Override
public void run() {
failed = true;
process.destroy();
}
};
}
Here's the script that startOminNames() invokes. It's the shell script installed with omniORB with functions other than start and get_pid removed, since those are handled by Android classes. You can invoke any executable in place of the script, or wrap your executable in a script.
Code:
#
# omniNames init file for starting up the OMNI Naming service
#
# chkconfig: - 20 80
# description: Starts and stops the OMNI Naming service
#
exec="/sdcard/data/com.axiosengineering.rhmanager/omniORB/bin/omniNames"
prog="omniNames"
logdir="/sdcard/data/com.axiosengineering.rhmanager/omniORB/logs"
logfile="/sdcard/data/com.axiosengineering.rhmanager/omniORB/logs/omninames-localhost.err.log"
options=" -start -always -logdir $logdir -errlog $logfile"
start() {
#[ -x $exec ] || exit 5
echo -n $"Starting $prog: "
$exec $options
}
get_pid() {
ps | grep omniNames
}
case "$1" in
start)
start && exit 0
$1
;;
pid)
get_pid
;;
*)
echo $"Usage: $0 {start|stop|status|restart|condrestart|try-restart|reload|force-reload}"
exit 2
esac
exit $?
And here's the IStatusListener interface
Code:
public interface IStatusListener {
public void running(boolean running);
}
Runtime.exec() has some pitfalls. See this helpful Runtime.exec tutorial for a nice explanation.
And you may also want to check out this post on loading native binaries in Android.