How to get the Linux application group name programmatically ?
There is no direct way to get it using the SDK.
public static String getGroupName(Context context) {
String groupName = null;
ActivityManager am = (ActivityManager) context.getSystemService(Context.ACTIVITY_SERVICE);
List<ActivityManager.RunningAppProcessInfo> runningProcesses = am.getRunningAppProcesses();
for (ActivityManager.RunningAppProcessInfo processInfo : runningProcesses) {
for (String activeProcess : processInfo.pkgList) {
try {
if (activeProcess.compareTo(context.getPackageName()) == 0) {
Process process = Runtime.getRuntime().exec("ps -p " + processInfo.pid);
String psOutput = streamToString(process.getInputStream());
String[] lines = psOutput.split("\n");
String valueLine = lines[1];
int firstSpace = valueLine.indexOf(" ", 0);
groupName = valueLine.substring(0, firstSpace);
}
}
catch (IOException ioe){
Log.e(TAG, "Error while getting group name", ioe);
}
catch (RuntimeException rte){
Log.e(TAG, "Error while getting group name", rte);
}
}
}
return groupName;
}
private static String streamToString(InputStream is) {
BufferedReader br = null;
StringBuilder sb = new StringBuilder();
String line;
try {
br = new BufferedReader(new InputStreamReader(is));
while ((line = br.readLine()) != null) {
sb.append(line).append("\n");
}
} catch (IOException e) {
Log.e(TAG, "Error while reading stream", e);
} finally {
if (br != null) {
try {
br.close();
} catch (IOException e) {
Log.e(TAG, "Error while closing stream", e);
}
}
}
return sb.toString();
}
Related
How to know the ip connected to my hotspot in android
I try to under code but /proc/net/arp is not reachable file in android 10
https://developer.android.com/about/versions/10/privacy/changes#proc-net-filesystem
BufferedReader br = null;
final ArrayList<ClientScanResult> result = new ArrayList<ClientScanResult>();
try {
br = new BufferedReader(new FileReader("/proc/net/arp"));
String line;
while ((line = br.readLine()) != null) {
String[] splitted = line.split(" +");
if ((splitted != null) && (splitted.length >= 4)) {
// Basic sanity check
String mac = splitted[3];
if (mac.matches("..:..:..:..:..:..")) {
boolean isReachable = InetAddress.getByName(splitted[0]).isReachable(reachableTimeout);
if (!onlyReachables || isReachable) {
result.add(new ClientScanResult(splitted[0], splitted[3], splitted[5], isReachable));
}
}
}
}
} catch (Exception e) {
Log.e(this.getClass().toString(), e.toString());
} finally {
try {
br.close();
} catch (IOException e) {
Log.e(this.getClass().toString(), e.getMessage());
}
}
I am trying to save this boolean array. When I read the array the string array (parts) says that
parts[0]=true;
,but when I use Boolean.parseBoolean array[0] is still false. Can someone help me and tell me what I am doing wrong. Please and Thank You.
public void writeArraytofile() {
try {
OutputStreamWriter outputStreamWriter = new OutputStreamWriter(openFileOutput("array.txt", Context.MODE_PRIVATE));
outputStreamWriter.write(Arrays.toString(array));
outputStreamWriter.close();
} catch (IOException e) {
Log.v("MyActivity", e.toString());
}
}
public boolean[] read(){
String result = "";
boolean[] array = new boolean[2];
try {
InputStream inputStream = openFileInput("array.txt");
if (inputStream != null) {
InputStreamReader inputStreamReader = new InputStreamReader(inputStream);
BufferedReader bufferedReader = new BufferedReader(inputStreamReader);
String tempString = "";
StringBuilder stringBuilder = new StringBuilder();
while ((tempString = bufferedReader.readLine()) != null) {
stringBuilder.append(tempString);
}
inputStream.close();
result = stringBuilder.toString();
String[] parts = result.split(" ");
for (int i = 0; i < array.length; i++){
array[i]=Boolean.parseBoolean(parts[i]);
}
}
} catch (FileNotFoundException e) {
Log.v("MyActivity", "File not found" + e.toString());
} catch (IOException e) {
e.printStackTrace();
} catch (NumberFormatException e) {
//here you catch and watch the problem
Log.e("MyActivity", "cant parse string: " + result);
}
return array;
}
Arrays.toString() will print brackets and commas, so when you read the string back in and call .split(" "), the first piece will be "[true,". Since that is not just "true", Boolean.parseBoolean() will return false.
recently
I try A.txt file read content.
but if my device have not a.txt , occur FileNotFoundException
so I want if my device have not a.txt, How can i stay to proceed?
String path = "/sdcard/Download";
String textName = "a.txt";
String serverVersion = null;
BufferedReader br = null;
try {
br = BufferedReaderFactory.create(path, textName);
StringBuilder contentGetter = new StringBuilder();
while ((serverVersion = br.readLine()) != null) {
serverVersion = serverVersion.trim().toLowerCase();
contentGetter.append('\n' + serverVersion);
Log.d(TAG, " myServerVersion = " + serverVersion);
break;
}
} catch (FileNotFoundException e) {
e.printStackTrace();
} catch (Exception e) {
e.printStackTrace();
}
You can simple create a variable before try/catch like
boolean isFileFound = false;
So, at the final of the try you set isFileFound = true
like:
String path = "/sdcard/Download";
String textName = "a.txt";
boolean isFileFound = false;
String serverVersion = null;
BufferedReader br = null;
try {
br = BufferedReaderFactory.create(path, textName);
StringBuilder contentGetter = new StringBuilder();
while ((serverVersion = br.readLine()) != null) {
serverVersion = serverVersion.trim().toLowerCase();
contentGetter.append('\n' + serverVersion);
Log.d(TAG, " myServerVersion = " + serverVersion);
break;
}
isFileFound = true;
} catch (FileNotFoundException e) {
e.printStackTrace();
} catch (Exception e) {
e.printStackTrace();
}
if (!isFileFound){ // This is equals to if(isFileFound != null)
//Do some message here, like:
Toast toast = Toast.makeText(context, "File not found", Toast.LENGTH_SHORT).show();
}
It looks like you are already handling the exception. If there is no file your code will continue as planned. After your try/catch blocks, you should check if(serverVersion == null) and if it returns true, you know that the serverVersion was not read from the file.
I have been working on this for a while and I am about to pull my hair out!!
If I use this...
public void readFile() {
BufferedReader buffReader = null;
StringBuilder result = new StringBuilder();
try {
FileInputStream fileIn = openFileInput("VariableStore.txt");
buffReader = new BufferedReader(new InputStreamReader(fileIn));
String line;
while ((line = buffReader.readLine()) != null) {
result.append(line);
}
} catch (IOException e) {
e.printStackTrace();
} finally {
try {
assert buffReader != null;
buffReader.close();
} catch (IOException e) {
e.printStackTrace();
}
}
String resultString = result.toString();
String[] controlString = resultString.split("$");
// String wb = controlString[4];
// String sb = controlString[5];
((Button) this.findViewById(R.id.wakeButton)).setText(resultString);
// ((Button) this.findViewById(R.id.sleepButton)).setText(sb);
// ((Button)this.findViewById(R.id.wakeButton)).setText(result);
// ((Button)this.findViewById(R.id.wakeButton)).setText(result);
// ((Button)this.findViewById(R.id.wakeButton)).setText(result);
}
The Button.setText works fine with "resultString" or with "result" which is a string I have input formatted as xxx$xxx$xxx$xxx$xxx so when I read it back in with the readFile() I want to use .Split and put it into an array "controlString" and then assign the array elements to my widgets i.e. setText(controlString[0]); but if I so much as even uncomment the lines String wb = controlString[4]; or String sb = controlString[5]; my program crashes. Why wont the array elemts work here?
Here is my writeFile().... (Which works perfectly.
public void writeFile() {
BufferedWriter buffWriter = null;
String wb = ((Button)this.findViewById(R.id.wakeButton)).getText().toString();
String sb = ((Button)this.findViewById(R.id.sleepButton)).getText().toString();
String tb = ((EditText)this.findViewById(R.id.textHoursBetween)).getText().toString();
String ti = ((EditText)this.findViewById(R.id.textIncrementTime)).getText().toString();
String td = ((EditText)this.findViewById(R.id.textIncrementDays)).getText().toString();
String writeString = wb + "$" + sb + "$" + tb + "$" + ti + "$" + td;
try {
FileOutputStream fileOut = openFileOutput("VariableStore.txt", Context.MODE_PRIVATE);
buffWriter = new BufferedWriter(new OutputStreamWriter(fileOut));
try {
buffWriter.write(writeString);
} catch (IOException e) {
e.printStackTrace();
}
} catch (FileNotFoundException e) {
e.printStackTrace();
}finally {
try {
assert buffWriter != null;
buffWriter.close();
} catch (IOException e) {
e.printStackTrace();
}
}
}
I found the problem...
Instead of this:
String[] controlString = resultString.split("$");
I had to use this:
String[] controlString = resultString.split(Pattern.quote("$"));
String myString = "hello world";
How could I save the contents of myString into a .txt file within the Phone/Android, which will be there after the application ends and so that I can edit the value in future?
Use this method:
public void WriteToFile(String str)
try {
OutputStreamWriter outputStreamWriter = new OutputStreamWriter(context.openFileOutput("config.txt", Context.MODE_PRIVATE));
outputStreamWriter.write(data);
outputStreamWriter.close();
}
catch (IOException e) {
Log.e("Exception", "File write failed: " + e.toString());
}
private String readFromFile() {
String ret = "";
try {
InputStream inputStream = openFileInput("config.txt");
if ( inputStream != null ) {
InputStreamReader inputStreamReader = new InputStreamReader(inputStream);
BufferedReader bufferedReader = new BufferedReader(inputStreamReader);
String receiveString = "";
StringBuilder stringBuilder = new StringBuilder();
while ( (receiveString = bufferedReader.readLine()) != null ) {
stringBuilder.append(receiveString);
}
inputStream.close();
ret = stringBuilder.toString();
}
}
catch (FileNotFoundException e) {
Log.e("login activity", "File not found: " + e.toString());
} catch (IOException e) {
Log.e("login activity", "Can not read file: " + e.toString());
}
return ret;
}