调用system服务打印dump信息的方法

public void produceSystemLog() {
        IBinder c = ServiceManager.getService("cpuinfo");
        if (c == null) {
            return;
        }
        FileOutputStream fileOutputStream = null;
        try {
            String file = context.getFilesDir().getAbsolutePath() + "/" + "cup";
            fileOutputStream = new FileOutputStream(file);
            FileDescriptor fileDescriptor = fileOutputStream.getFD();
            c.dump(fileDescriptor, null);
        } catch (RemoteException | IOException e) {
            e.printStackTrace();
        } finally {
            if (fileOutputStream != null) {
                try {
                    fileOutputStream.close();
                } catch (IOException e) {
                    e.printStackTrace();
                }
            }
        }

        return;
    }

其核心思想有这几点:

  1. 使用ServiceManager的getService获取对应service的Binder代理IBinder
  2. 定义FileDescriptor指向目标文件
  3. 调用目标service的dump接口,把dump信息输出到目标文件

另外:
由于ServiceManager是@hide类型的,所以一般应用无法访问,可以通过反射的方法获取到对应service的Binder代理,但是dump需要用到下面的权限:

<uses-permission android:name="android.permission.DUMP"/>

而这个权限要求只有系统应用才能使用,所以普通应用还是无法dump系统信息。

©著作权归作者所有,转载或内容合作请联系作者
【社区内容提示】社区部分内容疑似由AI辅助生成,浏览时请结合常识与多方信息审慎甄别。
平台声明:文章内容(如有图片或视频亦包括在内)由作者上传并发布,文章内容仅代表作者本人观点,简书系信息发布平台,仅提供信息存储服务。