首页 > 解决方案 > 如何从 android 应用程序设置系统属性?

问题描述

我需要做setprop,但从一个应用程序。

现在我正试图将它作为一个 shell 命令运行:

public class MainActivity extends AppCompatActivity {

    private static final String TAG = "test:MainActivity";

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);
        exec("setprop service.adb.tcp.port 5555");
    }

    private void exec(String cmd) {
        Process proc = null;
        BufferedReader successResult = null;
        BufferedReader errorResult = null;

        Runtime runtime = Runtime.getRuntime();
        Log.d(TAG, "exec command: " + cmd);
        try {
            proc = runtime.exec(cmd);
            successResult = new BufferedReader(new InputStreamReader(proc.getInputStream()));
            errorResult = new BufferedReader(new InputStreamReader(proc.getErrorStream()));
            String s;
            while ((s = successResult.readLine()) != null) {
                Log.d(TAG, "exec command: " + s);
            }
            while ((s = errorResult.readLine()) != null) {
                Log.d(TAG, "exec command: " + s);
            }
        } catch (IOException e) {
            Log.e(TAG, "Error running shell command:", e);
        } finally {
            try {
                if (successResult != null) {
                    successResult.close();
                }
                if (errorResult != null) {
                    errorResult.close();
                }
            } catch (IOException e) {
                Log.e(TAG, "Error running shell command:", e);
            }

            if (proc != null) {
                proc.destroy();
            }
        }
    }
}

这给了我:

执行命令:setprop service.adb.tcp.port 5555

执行命令:setprop:未能将属性“service.adb.tcp.port”设置为“5555”

如何从应用程序设置系统属性?

编辑:对不起,我应该添加我的设备已植根并且此应用程序是系统应用程序。

标签: javaandroid

解决方案


您无法从常规应用程序设置此特定属性。它受系统保护。

在 Android 5 之前,您需要sharedUserId="android.uid.system"在清单中包含您的应用,从 Android 5 及更高版本开始,它需要是sharedUserId="android.uid.shell".

但是,如果您的应用具有这些用户 ID 之一,则必须使用要安装的系统证书对其进行签名,因此您只能在开发板和自定义 ROM 上执行此操作。

另一种选择是,如果您的设备已植根,则可以使用 su 运行 setprop 命令。


推荐阅读