Java – How do I set system properties from an Android application?

How do I set system properties from an Android application?… here is a solution to the problem.

How do I set system properties from an Android application?

I need to do setprop through the app.

Now I’m trying to run it as a shell command :

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();
            }
        }
    }
}

This gives me:

exec command: setprop service.adb.tcp.port 5555

exec command: setprop: failed to set property ‘service.adb.tcp.port’
to ‘5555’

How do I set system properties from an application?

EDIT: Sorry, I should add that my device is rooted and this app is a system app.

Solution

You cannot set this particular property from a regular application.
Protected by the system.

Prior to Android 5, your application needed to include sharedUserId=”android.uid.system”

in your list, and from Android 5 and later, it needed to be sharedUserId="android .uid.shell"

However, if your app has one of these user IDs, it must be signed with a system certificate to install, so you can only do this on development boards and custom ROMs.

Another option is that if your device is rooted, you can run the setprop command using su.

Related Problems and Solutions