android获取app父进程ID

在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.csdn.net/liujiahan629629/article/details/18013523

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值