简体   繁体   English

为什么在 Android 中从命令行启动服务需要 root 访问权限(su)?

[英]Why starting a service from command line in Android needs root access (su)?

I am trying to start a service of an another app (not mine) from command line in my Android app.我正在尝试从我的 Android 应用程序中的命令行启动另一个应用程序(不是我的)的服务。 But I've noticed that it works only if I run "su".但我注意到它只有在我运行“su”时才有效。 My phone of course is "rooted".我的手机当然是“root”了。 Maybe there is another way to start a service of an app without needing to execute a shell command?也许还有另一种方式来启动应用程序的服务而无需执行 shell 命令?

This code works:此代码有效:

   try {
                            Process process = Runtime.getRuntime().exec("su", null,null);
                            OutputStream outputStream = process.getOutputStream();

                            outputStream.write(("am startservice -a com.companyname.notmyapp.TEST --option a 1").getBytes("ASCII"));

                            outputStream.flush();
                            outputStream.close();
                            process.waitFor();
                        } catch (IOException e) {
                            e.printStackTrace();
                        } catch (InterruptedException e) {
                            e.printStackTrace();
                        }

This one it doesn't:这一个它没有:

   try {
                            Process process = Runtime.getRuntime().exec("am startservice -a com.companyname.notmyapp.TEST --option a 1", null,null);
                            //OutputStream outputStream = process.getOutputStream();
                            //outputStream.flush();
                            //outputStream.close();
                            process.waitFor();
                        } catch (IOException e) {
                            e.printStackTrace();
                        } catch (InterruptedException e) {
                            e.printStackTrace();
                        }

Intent intent = new Intent(Intent.ACTION_VIEW); Intent 意图 = new Intent(Intent.ACTION_VIEW); String packageName = "com.ang.chapter_2_service"; String packageName = "com.ang.chapter_2_service"; //the package name what you want to start //package 名字你想开始

String className = "com.ang.chapter_2.poolBinder.BinderPoolService"; String className = "com.ang.chapter_2.poolBinder.BinderPoolService"; //service full name what you want to start intent.setClassName(packageName, className); //你要启动的服务全名 intent.setClassName(packageName, className); startService(intent);//or bindService(intent, mConnection, Context.BIND_AUTO_CREATE); startService(intent);//或 bindService(intent, mConnection, Context.BIND_AUTO_CREATE);

the activity is same to this.活动与此相同。

Of course the service or activity what you want to start need a tag in manifest.xml:当然,您要启动的服务或活动需要 manifest.xml 中的标签:

android:exported="true"

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM