在android.os.Process中可以直接获取当前应用的进程号:
int pid = android.os.Process.myPid();
在Process中是有获取父进程ID方法的,但是不能用:
通过反射来实现:
//获取对应的类
Class<Process> processClass = android.os.Process.class;
//创建一个对象
Process process = null;
try {
process = processClass.newInstance();
} catch (InstantiationException e) {
e.printStackTrace();
} catch (IllegalAccessException e) {
e.printStackTrace();
}
int ppid = 0;
try {
//创建方法process中myPpid方法
Method method = processClass.getMethod("myPpid");
//调用方法,传入对象
ppid = (int) method.invoke(process);
} catch (NoSuchMethodException e) {
e.printStackTrace();
} catch (InvocationTargetException e) {
e.printStackTrace();
} catch (IllegalAccessException e) {
e.printStackTrace();
}
主要看看invoke方法:
* @param receiver
* the object on which to call this method (or null for static methods)
* @param args
* the arguments to the method
* @return the result
*
* @throws NullPointerException
* if {@code receiver == null} for a non-static method
* @throws IllegalAccessException
* if this method is not accessible (see {@link AccessibleObject})
* @throws IllegalArgumentException
* if the number of arguments doesn't match the number of parameters, the receiver
* is incompatible with the declaring class, or an argument could not be unboxed
* or converted by a widening conversion to the corresponding parameter type
* @throws InvocationTargetException
* if an exception was thrown by the invoked method
*/
public native Object invoke(Object receiver, Object... args)
throws IllegalAccessException, IllegalArgumentException, InvocationTargetException;
第一个参数receiver是调用该方法的对象,就是之前创建的process对象,第二个参数是对应方法的参数,由于myPpid()没有参数就不用传了。
关于反射更详细的介绍看:
http://blog.youkuaiyun.com/liujiahan629629/article/details/18013523