Today I came across the porting of a code to make it compatible for Android 7, so nougat, from the previous version. During this phase I discovered that from the SDK 25 onwards there is no longer the possibility to list via the listFiles of /proc.
This happened for security reasons narrowing the range of action that differentiates Android from iOS. (not of safety is well understood) The code that you glue is the relative one before the SDK 25 version. It remains valid from versions 25 onwards but is restricted to the reading permissions of the user running the application, so it will not list all the processes.
public static Listpidof(String str) { List < String > listOfPid = new ArrayList (); for (File file : new File("/proc").listFiles()) { if (!file.isFile()) { File file2; if (Build.VERSION.SDK_INT < 25) { file2 = new File(file.toString() + "/cmdline");; }else { file2 = new File(file.toString() + "/comm"); } if (file2.canRead()) { try { BufferedReader bufferedReader = new BufferedReader(new FileReader(file2), 8192); while (true) { String readLine = bufferedReader.readLine(); if (readLine == null) { break; } else if (readLine.toString().contains(str.toString())) { listOfPid.add(file2.getPath().split("\/")[2].toString()); } } bufferedReader.close(); } catch (IOException e) { } } else { continue; } } } return listOfPid; }
Alternatively, we always talk about devices with root, you can create a small script in sh:
sudo -c 'pidof processname'
For example, save it in the folder files of our app giving it the correct permissions via adb and then retrieve it via getRuntime().exec().I don't know if there are other valid and functional methods in case you comment to me suggesting?
Thank you all!