简体   繁体   中英

Android Runtime.getRuntime().exec

i was reading around on how to get the PID of a running process in android, that is not running inside dalvik (eg, background native process) on a custom device (chinese box) running android 2.2, and it seems there's no native way to do this in java.

The only way i could think of is to execute "ps " and parse the output, but i have encountered an odd problem.

If i run Runtime.getRuntime().exec("ps ") in this very case a ndk-compiled mplayer port, after a random period of time, the command never returns.

Here's the code:

Process process = null;
process = Runtime.getRuntime().exec("ps mplayer");
BufferedReader reader = new BufferedReader( new InputStreamReader(process.getInputStream()),8192);

char[] buffer = new char[8192];
StringBuffer output = new StringBuffer();
while ((read = reader.read(buffer)) > 0) {
      output.append(buffer, 0, read);
}
reader.close();
process.getErrorStream().close();
process.getOutputStream().close();
process.waitFor();

then do some parsing of the output buffer and see if mplayer exists in the output.

This works great for some time, random period, say from 1 hours to 3-4 hours, when the code suddenly stop working when trying to .exec()

If i run it in the main thread via a runable with .postDelayed so it can run many times, it obviously breaks the main thread.

If i run it on a separate thread, i get the same behaviour, of course not blocking the main app thread.

I have been running the check every second, every 5 seconds, every 10 seconds with the same result.

One odd thing i noticed that (not sure if its the cause of the result of the problem) is when the exec is not working, by issuing a ps in adb shell, i can see 2 running applications of mine, and once i kill the most recent, it starts working again.

Has anybody else encountered a similar problem ? I'm not sure if it's the box's android that's at fault, it's a coding problem (maybe something related to exec i'm not doing) or if there's another way, short of having a NDK compiled background app and communicate with it via IPC to check if that process is running or not.

如果您使用服务每隔5秒检查一次,则如果要防止服务崩溃时自动启动服务,则必须从覆盖方法onStartCommand()返回START_NOT_STICKY

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM