how to get android cpu temperature programmatically - android

Tried this but got 0.0 and on physical device nothing found..
Any way to get cpu temperature in android
SensorManager mySensorManager = (SensorManager) getSystemService(SENSOR_SERVICE);
Sensor AmbientTemperatureSensor
= mySensorManager.getDefaultSensor(Sensor.TYPE_AMBIENT_TEMPERATURE);
if (AmbientTemperatureSensor != null) {
mySensorManager.registerListener(
AmbientTemperatureSensorListener,
AmbientTemperatureSensor,
SensorManager.SENSOR_DELAY_NORMAL);
}
private final SensorEventListener AmbientTemperatureSensorListener
= new SensorEventListener() {
#Override
public void onAccuracyChanged(Sensor sensor, int accuracy) {
// TODO Auto-generated method stub
}
#Override
public void onSensorChanged(SensorEvent event) {
if (event.sensor.getType() == Sensor.TYPE_AMBIENT_TEMPERATURE) {
temperature = event.values[0];
Messages.sendMessage(getApplicationContext(),Float.toString(temperature));
}
}
};

public static float cpuTemperature()
{
Process process;
try {
process = Runtime.getRuntime().exec("cat sys/class/thermal/thermal_zone0/temp");
process.waitFor();
BufferedReader reader = new BufferedReader(new InputStreamReader(process.getInputStream()));
String line = reader.readLine();
if(line!=null) {
float temp = Float.parseFloat(line);
return temp / 1000.0f;
}else{
return 51.0f;
}
} catch (Exception e) {
e.printStackTrace();
return 0.0f;
}
}

You can find all the thermal values(temp and type) from this code (not only CPU temperature). And also remember that sys/class/thermal/thermal_zone0/temp not always point towards CPU temperature (in my case it was pointing towards battery temperature). Always use this code in background thread. I have tested it on real device as well as emulator and it was working fine.
public void thermal() {
String temp, type;
for (int i = 0; i < 29; i++) {
temp = thermalTemp(i);
if (!temp.contains("0.0")) {
type = thermalType(i);
if (type != null) {
System.out.println("ThermalValues "+type+" : "+temp+"\n");
}
}
}
}
public String thermalTemp(int i) {
Process process;
BufferedReader reader;
String line;
String t = null;
float temp = 0;
try {
process = Runtime.getRuntime().exec("cat sys/class/thermal/thermal_zone" + i + "/temp");
process.waitFor();
reader = new BufferedReader(new InputStreamReader(process.getInputStream()));
line = reader.readLine();
if (line != null) {
temp = Float.parseFloat(line);
}
reader.close();
process.destroy();
if (!((int) temp == 0)) {
if ((int) temp > 10000) {
temp = temp / 1000;
} else if ((int) temp > 1000) {
temp = temp / 100;
} else if ((int) temp > 100) {
temp = temp / 10;
}
} else
t = "0.0";
} catch (Exception e) {
e.printStackTrace();
}
return t;
}
public String thermalType(int i) {
Process process;
BufferedReader reader;
String line, type = null;
try {
process = Runtime.getRuntime().exec("cat sys/class/thermal/thermal_zone" + i + "/type");
process.waitFor();
reader = new BufferedReader(new InputStreamReader(process.getInputStream()));
line = reader.readLine();
if (line != null) {
type = line;
}
reader.close();
process.destroy();
} catch (Exception e) {
e.printStackTrace();
}
return type;
}
Sample Output in Logcat (Image below is Real device output... On emulator it only showed the type battery and its temperature.) :

There is a system service for this kind of stuff
HardwarePropertiesManager that contain a method getDeviceTemperatures(int type, int source) which is available from Nougat
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.N) {
HardwarePropertiesManager hardwarePropertiesManager= (HardwarePropertiesManager) getSystemService(Context.HARDWARE_PROPERTIES_SERVICE);
float[] temp = hardwarePropertiesManager.getDeviceTemperatures(HardwarePropertiesManager.DEVICE_TEMPERATURE_CPU, HardwarePropertiesManager.TEMPERATURE_CURRENT);
}
Take a look to this :
https://developer.android.com/reference/android/os/HardwarePropertiesManager

Related

in Android Q, how to tracking an application's network statistics (rx and tx)

in Android Q, how to tracking an application's network statistics (rx and tx) . not getting rx and tx in android 10 using below code.Its working up to pie without any probs
while (!Thread.currentThread().isInterrupted()) {
// Parse the network traffic statistics pertaining to this connection
DataInputStream in = null;
try {
in = new DataInputStream(new FileInputStream("/proc/net/dev"));
final String prefix = "tun0" + ':';
while (true) {
String line = in.readLine().trim();
if (line.startsWith(prefix)) {
String[] numbers = line.substring(prefix.length()).split(" +");
boolean foundNonZero = false;
for (int i = 1; i < 17 && foundNonZero == false; ++i) {
if (!numbers[i].equals("0")) {
foundNonZero = true;
}
}
if (foundNonZero) {
rxBytes = numbers[NET_INTERFACE_BYTES_IN_COL];
txBytes = numbers[NET_INTERFACE_BYTES_OUT_COL];
}
break;
}
}
} catch (Exception e) {
// ignore
} finally {
try {
in.close();
} catch (Exception e) {
// ignore
}
}

How to get altitude from Google Maps

I am trying to get altitude but it is not getting any rather garbage value. I have followed this link: Get altitude by longitude and latitude in Android.
protected String doInBackground(String... params) {
try {
URL url=new URL("http://gisdata.usgs.gov/"
+ "xmlwebservices2/elevation_service.asmx/"
+ "getElevation?X_Value=" + params[1]
+ "&Y_Value=" + params[0]
+ "&Elevation_Units=METERS&Source_Layer=-1&Elevation_Only=true");
HttpURLConnection httpURLConnection=(HttpURLConnection)url.openConnection();
httpURLConnection.setRequestMethod("POST");
httpURLConnection.setDoInput(true);
httpURLConnection.setDoOutput(true);
OutputStream outputStream=httpURLConnection.getOutputStream();
BufferedWriter bufferedWriter=new BufferedWriter(new OutputStreamWriter(outputStream, "UTF-8"));
bufferedWriter.flush();
bufferedWriter.close();
InputStream inputStream = httpURLConnection.getInputStream();
BufferedReader bufferedReader = new BufferedReader(new InputStreamReader(inputStream, "UTF-8"));
String line = "";
double res = Double.NaN;
while ((line = bufferedReader.readLine()) != null) {
int r = -1;
StringBuffer respStr = new StringBuffer();
while ((r = inputStream.read()) != -1)
respStr.append((char) r);
String tagOpen = "<double>";
String tagClose = "</double>";
if (respStr.indexOf(tagOpen) != -1) {
int start = respStr.indexOf(tagOpen) + tagOpen.length();
int end = respStr.indexOf(tagClose);
String value = respStr.substring(start, end);
res = Double.parseDouble(value);
}
}
inputStream.close();
httpURLConnection.disconnect();
Log.v("Altitude D",String.valueOf(res));
return String.valueOf(res);
} catch (MalformedURLException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
return null;
}
and the way i have called it from onLocationChanged.
public void onLocationChanged(Location location) {
if (location == null) {
}
else {
Altitude altitude=new Altitude();
altitude.execute(String.valueOf(location.getLatitude()), String.valueOf(location.getLongitude()));
}
}
You need to call the runnable, something like this.
public void onLocationChanged(Location location) {
if (location == null) {
}
else {
new Thread(new Runnable() {
public void run() {
final double alt = getAltitude(lon, lat);
}
}).run();
}
You are attempting to get the value of it from a string, when you have already parsed it to double.
double res = Double.NaN;
while ((line = bufferedReader.readLine()) != null) {
int r = -1;
StringBuffer respStr = new StringBuffer();
while ((r = inputStream.read()) != -1)
respStr.append((char) r);
String tagOpen = "<double>";
String tagClose = "</double>";
if (respStr.indexOf(tagOpen) != -1) {
int start = respStr.indexOf(tagOpen) + tagOpen.length();
int end = respStr.indexOf(tagClose);
String value = respStr.substring(start, end);
// parsing to double here.
res = Double.parseDouble(value);
}
}
inputStream.close();
httpURLConnection.disconnect();
Log.v("Altitude D",String.valueOf(res));
// return String.valueOf(res); get rid of this line
return res;
} catch (MalformedURLException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
// or return res down here.
return res;
}

need some advice in threading

I have an app which can download images from a website,
it runs perfectly, but there is only one thing that annoys me, it is CPU intensive.
here is my code, could anyone give any advice how to handle this?
thank you so much!
Task.java
public class Task implements Runnable {
private String url;
private int server;
public Task(String url, int server) {
this.url = url;
this.server = server;
}
#Override
public void run() {
android.os.Process
.setThreadPriority(android.os.Process.THREAD_PRIORITY_LESS_FAVORABLE);
int page = 1;
String r1 = "";
if (server == 1) {
r1 = getRaw(url);
} else if (server == 2) {
url = url + "page/";
r1 = getRaw(url + page);
}
try {
Thread.sleep(1000);
} catch (InterruptedException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
String subs = url.substring(0, url.lastIndexOf('/') + 1);
List<String> a1 = getPackage(r1, server);
String t1 = getImageLink(r1, server);
String loc = DownloadXML.UNDUH + File.separator + a1.get(0)
+ File.separator + a1.get(1) + ' ' + a1.get(2);
File f1 = new File(loc);
if (!f1.exists())
f1.mkdirs();
getImage(loc, t1, page);
try {
Thread.sleep(2000);
} catch (InterruptedException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
page++;
if (server == 1) {
while (true) {
r1 = getRaw(subs + page);
t1 = getImageLink(r1, server);
if (t1 != null) {
getImage(loc, t1, page);
page++;
try {
Thread.sleep(1000);
} catch (InterruptedException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
} else {
break;
}
}
return;
} else if (server == 2) {
int maxPage = Integer.parseInt(a1.get(3));
while (page <= maxPage) {
r1 = getRaw(subs + page);
t1 = getImageLink(r1, server);
if (t1 != null) {
getImage(loc, t1, page);
page++;
try {
Thread.sleep(1000);
} catch (InterruptedException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
} else {
break;
}
}
return;
}
}
private String getRaw(String link) {
String raw = null;
try {
URL myUrl = new URL(link);
HttpURLConnection conn = (HttpURLConnection) myUrl.openConnection();
conn.setRequestProperty(
"User-Agent",
"Mozilla/5.0 (Windows NT 6.1; WOW64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/28.0.1500.29 Safari/537.36");
InputStreamReader is = new InputStreamReader(conn.getInputStream());
BufferedReader in = new BufferedReader(new InputStreamReader(
conn.getInputStream()));
String line;
while ((line = in.readLine()) != null) {
raw += line;
}
is.close();
in.close();
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
return null;
}
return raw;
}
private List<String> getPackage(String raw, int server) {
List<String> pack = new ArrayList<String>();
switch (server) {
case 1:
Pattern pattern = Pattern
.compile("<span class=\"visible-desktop visible-tablet.+?</span>.+?<span class=\"visible-desktop visible-tablet.+?</span>");
Matcher matcher = pattern.matcher(raw);
String b = null;
while (matcher.find()) {
b = matcher.group();
if (b != null) {
String[] t = b.split("<[^>]*>");
for (int i = 0; i < t.length; i++) {
if (!t[i].isEmpty()) {
pack.add(t[i].trim());
}
}
}
}
break;
case 2:
Pattern pattern1 = Pattern
.compile("<div class=\"topbar_left\">.+?</a>.+?</a>");
Matcher matcher1 = pattern1.matcher(raw);
Pattern pPage = Pattern.compile("<div class=\"tbtitle dropdown_parent dropdown_right\"><div class=\"text\">[0-9]+ </div>");
Matcher mPage = pPage.matcher(raw);
while (matcher1.find()) {
String s = matcher1.group().trim();
s = s.replaceAll("<[^>]*>", "");
String[] temp = s.split("[:]+");
for (int i = 0; i < temp.length; i++) {
if (temp[i] != null)
if (i == 1) {
pack.add(temp[i].replaceAll("[a-zA-z]+", "").trim());
} else if (i == 2) {
pack.add("- "
+ temp[i].trim().replaceAll(
"[^a-zA-z0-9]+", "_"));
} else {
pack.add(temp[i].trim());
}
}
}
while (mPage.find()) {
pack.add(mPage.group().replaceAll("<[^>]*>", "").trim());
}
break;
}
return pack;
}
private String getImageLink(String raws, int server) {
/*
* Return image link
*/
switch (server) {
case 1:
Pattern pattern = Pattern.compile("http://img.+(jpg|png)");
Matcher matcher = pattern.matcher(raws);
while (matcher.find()) {
return matcher.group();
}
break;
case 2:
Pattern pattern1 = Pattern
.compile("http://manga.redhawkscans.com/content/comics/.+?(jpg|png)");
Matcher matcher1 = pattern1.matcher(raws);
while (matcher1.find()) {
if (matcher1.group().contains("thumb")) {
return null;
} else {
return matcher1.group();
}
}
break;
}
return null;
}
private void getImage(String loc, String link, int page) {
/*
* Get image and save it
*/
try {
URL url = new URL(link);
HttpURLConnection conn = (HttpURLConnection) url.openConnection();
conn.setRequestProperty(
"User-Agent",
"Mozilla/5.0 (Windows NT 6.1; WOW64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/28.0.1500.29 Safari/537.36");
String form = link.substring(link.lastIndexOf('.') + 1);
String p = "0";
if (page < 10) {
p += Integer.toString(page);
} else {
p = Integer.toString(page);
}
File f = new File(loc, p + '.' + form);
Bitmap bitmap = BitmapFactory.decodeStream(conn.getInputStream());
FileOutputStream fos = new FileOutputStream(f);
if (form == "jpg") {
bitmap.compress(Bitmap.CompressFormat.JPEG, 100, fos);
} else {
bitmap.compress(Bitmap.CompressFormat.PNG, 100, fos);
}
conn.disconnect();
fos.flush();
fos.close();
} catch (MalformedURLException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
}
}
and in another class, I just call new Thread(new Task(link,server)).start() to start the threading.
A lot of code that uses RegExps working with large strings (web pages?)
converting images on the fly.
new URLConnection on every request.
Try to:
Test your RegExp's performance and work with it. Short and too complicated RegExps like [abc] is very slow on large strings.
Do you really need to recompress your bitmaps. May be it's better to store original stream to file rather than recompress it?
Create Connection pool or shared connection to increase connection time and minimize unneeded initializations.
Also you can try minimize thread priority to BACKGROUND:
android.os.Process.setThreadPriority(android.os.Process.THREAD_PRIORITY_BACKGROUND);

Android - How to know when Super User is granted to my Application?

My application requires root access. For example this code:
Process p;
try {
p = Runtime.getRuntime().exec("su");
BufferedReader es = new BufferedReader(new InputStreamReader(p.getErrorStream()));
String line;
if((line = es.readLine()) != null)
{
if(line.contentEquals("Permission denied"))
Log.e("TrisTag", "ROOT isn't granted");
}
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
So I know when my root access is denied (Read from the error stream). But what's about granted ? How to know ?
Answer from kevin.
public class Root {
private static String LOG_TAG = Root.class.getName();
public boolean isDeviceRooted() {
if (checkRootMethod1()){return true;}
if (checkRootMethod2()){return true;}
if (checkRootMethod3()){return true;}
return false;
}
public boolean checkRootMethod1(){
String buildTags = android.os.Build.TAGS;
if (buildTags != null && buildTags.contains("test-keys")) {
return true;
}
return false;
}
public boolean checkRootMethod2(){
try {
File file = new File("/system/app/Superuser.apk");
if (file.exists()) {
return true;
}
} catch (Exception e) { }
return false;
}
public boolean checkRootMethod3() {
if (new ExecShell().executeCommand(SHELL_CMD.check_su_binary) != null){
return true;
}else{
return false;
}
}
}
 
/**
* #author Kevin Kowalewski
*
*/
public class ExecShell {
private static String LOG_TAG = ExecShell.class.getName();
public static enum SHELL_CMD {
check_su_binary(new String[] {"/system/xbin/which","su"}),
;
String[] command;
SHELL_CMD(String[] command){
this.command = command;
}
}
public ArrayList<String> executeCommand(SHELL_CMD shellCmd){
String line = null;
ArrayList<String> fullResponse = new ArrayList<String>();
Process localProcess = null;
try {
localProcess = Runtime.getRuntime().exec(shellCmd.command);
} catch (Exception e) {
return null;
}
BufferedWriter out = new BufferedWriter(new OutputStreamWriter(localProcess.getOutputStream()));
BufferedReader in = new BufferedReader(new InputStreamReader(localProcess.getInputStream()));
try {
while ((line = in.readLine()) != null) {
Log.d(LOG_TAG, "--> Line received: " + line);
fullResponse.add(line);
}
} catch (Exception e) {
e.printStackTrace();
}
Log.d(LOG_TAG, "--> Full response was: " + fullResponse);
return fullResponse;
}

Homemade Google Analytics

Since Google analytics can raise many privacy concerns, I implemented an events logger.
My first idea is to track user's generated events into a logfile and then send them back to the server that will perform the analysis of data for the System Administrator and Application Engineers.
For the moment the idea is to instantiate the Logger into an Application or a Service class and use those elements onCreate and onDestroy to safely handle the LogFile.
The solution is quite simple:
Open file
Append to it every time an event is generated
Once the a MAX_NUM_LINES is reached, send the log to the server (possibly I'll zip the text file I am generating)
I wonder if there's anything already baked there in the wild I am unaware of that you might know (something like ACRA).
Every contribution will be appreciated.
Here my implementation.
However any better version is much appreciated.
The TSG objet is just a static class that I use as time manager.
Use the code and improve it as long as you repost / edit the modifications.
public class Logger {
private BufferedWriter logFile;
private String nameFile;
public int fileLines;
private File fTemp;
private timeStampGenerator TSG;
private int LOG_LINES_LIMIT = 100;
private Object mutex;
public enum EventType {
BUTTON_PRESSED,
PAGE_VIEWED,
LOADED_ACTIVITY,
GENERIC_EVENT
}
public Logger (String fileName) throws IOException {
nameFile = fileName;
createLogFile();
fileLines = countLines();
TSG = new timeStampGenerator();
// This is our mutex to access to the file
mutex = new Object();
}
public void createLogFile() throws IOException{
fTemp = new File (nameFile);
if (!fTemp.exists()) {
fTemp.createNewFile();
}
logFile = new BufferedWriter(new FileWriter(nameFile, true));
}
public void LogEvent(EventType event, String comment, String value) {
String line = "";
line += TSG.getTimestampMillis();
line += ",";
line += event.name();
line += ",";
if (comment != "") {
line += comment.replaceAll(",", ";");
} else {
line += " ";
}
line += ",";
if (value != "") {
line += value.replaceAll(",", ";");
} else {
line += " ";
}
line += "\n";
synchronized (mutex) {
try {
logFile.append(line);
} catch (IOException e) {
// Do wathever you want here
}
fileLines++;
}
}
public int countLines() //throws IOException
{
InputStream is;
try {
is = new BufferedInputStream(new FileInputStream(nameFile));
} catch (FileNotFoundException e1) {
//let's consider it an empty file
return 0;
}
int count = 0;
boolean empty = true;
try {
int readChars = 0;
byte[] c = new byte[1024];
while ((readChars = is.read(c)) != -1) {
empty = false;
for (int i = 0; i < readChars; ++i) {
if (c[i] == '\n')
++count;
}
}
} catch(IOException e) {
// Do wathever you want here
}
try {
is.close();
} catch (IOException e) {
// Do wathever you want here
}
return (count == 0 && !empty) ? 1 : count;
}
public boolean isLimitReached() {
return (fileLines >= LOG_LINES_LIMIT);
}
public void close () {
flush();
try {
logFile.close();
} catch (IOException e) {
// Do wathever you want here
}
}
/**
* clear the content of the file
*/
public void clearFile() {
synchronized (mutex) {
if ( fTemp.delete() ) {
try {
createLogFile();
} catch (IOException e1) {
// Do wathever you want here
}
}
}
}
/**
* Get the full content of the file
* #return the content
*/
public String getContent() {
StringBuffer fileData = new StringBuffer();
synchronized (mutex) {
try {
BufferedReader reader = new BufferedReader(new FileReader( nameFile ));
char[] buf = new char[1024];
int numRead = 0;
while ((numRead = reader.read(buf)) != -1) {
String readData = String.valueOf(buf, 0, numRead);
fileData.append(readData);
}
reader.close();
} catch (IOException e) {
// Do wathever you want here
}
}
return fileData.toString();
}
public void flush() {
try {
logFile.flush();
} catch (IOException e) {
// Do wathever you want here
}
}
}

Categories

Resources