Get device configuration of android mobile - java

Is there a function or command to get the basic device configurations of android device? Like the RAM size,OS version,number of processor cores, etc..

All of the device information you can get below the ways. Hope for help.
Get CPU Core of device
/**
* Gets the number of cores available in this device, across all processors.
* Requires: Ability to peruse the filesystem at "/sys/devices/system/cpu"
* #return The number of cores, or 1 if failed to get result
*/
private int getNumCores() {
//Private Class to display only CPU devices in the directory listing
class CpuFilter implements FileFilter {
#Override
public boolean accept(File pathname) {
//Check if filename is "cpu", followed by a single digit number
if(Pattern.matches("cpu[0-9]+", pathname.getName())) {
return true;
}
return false;
}
}
try {
//Get directory containing CPU info
File dir = new File("/sys/devices/system/cpu/");
//Filter to only list the devices we care about
File[] files = dir.listFiles(new CpuFilter());
//Return the number of cores (virtual CPU devices)
return files.length;
} catch(Exception e) {
//Default to return 1 core
return 1;
}
}
Get Total RAM of device
public static String getTotalRAM() {
RandomAccessFile reader = null;
String load = null;
try {
reader = new RandomAccessFile("/proc/meminfo", "r");
load = reader.readLine();
} catch (IOException ex) {
ex.printStackTrace();
} finally {
// Streams.close(reader);
}
return load;
}
Other information of device
String _OSVERSION = System.getProperty("os.version");
String _RELEASE = android.os.Build.VERSION.RELEASE;
String _DEVICE = android.os.Build.DEVICE;
String _MODEL = android.os.Build.MODEL;
String _PRODUCT = android.os.Build.PRODUCT;
String _BRAND = android.os.Build.BRAND;
String _DISPLAY = android.os.Build.DISPLAY;
String _CPU_ABI = android.os.Build.CPU_ABI;
String _CPU_ABI2 = android.os.Build.CPU_ABI2;
String _UNKNOWN = android.os.Build.UNKNOWN;
String _HARDWARE = android.os.Build.HARDWARE;
String _ID = android.os.Build.ID;
String _MANUFACTURER = android.os.Build.MANUFACTURER;
String _SERIAL = android.os.Build.SERIAL;
String _USER = android.os.Build.USER;
String _HOST = android.os.Build.HOST;

You can obtain most of the information you want from the /proc/cpuinfo file. Here is a tutorial on how to load and parse that file: How to get Cpu Information on android
Information about the RAM can be obtained from the /proc/meminfo file

Check out the android.os.Build class.
android.os.Build.HARDWARE
android.os.Build.DEVICE
android.os.Build.MODEL
android.os.Build.PRODUCT
android.os.Build.BOARD
android.os.Build.DISPLAY
etc...
To get the OS version number, you can try
System.getProperty("os.version");

You could look at android.os.Build to determine the phone make and model. From there have a lookup to look up the phone specs based on make and model.

Related

Get a list of disks to read free space in Java, using Sigar

I need to get the free available disk space for all disks in system, or all partitions, I don't mind that. (I dont have to use Sigar, but I am using it already on the project for some other processes, so I can use it for this as well)
I am using Sigar API and got this
public double getFreeHdd() throws SigarException{
FileSystemUsage f= sigar.getFileSystemUsage("/");
return ( f.getAvail());
}
But this only gives me the system partition (root), how can i get a list of all partition and loop them to get their free space?
I tried this
FileSystemView fsv = FileSystemView.getFileSystemView();
File[] roots = fsv.getRoots();
for (int i = 0; i < roots.length; i++) {
System.out.println("Root: " + roots[i]);
}
But it only returns the root dir
Root: /
Thanks
Edit
it seems that I could use
FileSystem[] fslist = sigar.getFileSystemList();
But the results i am getting do not match the ones i get from the terminal. On the other hand on this system I am working on, i have 3 disks with a total 12 partitions, so i might be loosing something there. Will try it on some other system in case i can make something useful out of the results.
We use SIGAR extensively for cross-platform monitoring. This is the code we use to get the file system list:
/**
* #return a list of directory path names of file systems that are local or network - not removable media
*/
public static Set<String> getLocalOrNetworkFileSystemDirectoryNames() {
Set<String> ret = new HashSet<String>();
try {
FileSystem[] fileSystemList = getSigarProxy().getFileSystemList();
for (FileSystem fs : fileSystemList) {
if ((fs.getType() == FileSystem.TYPE_LOCAL_DISK) || (fs.getType() == FileSystem.TYPE_NETWORK)) {
ret.add(fs.getDirName());
}
}
}
catch (SigarException e) {
// log or rethrow as appropriate
}
return ret;
}
You can then use that as the input to other SIGAR methods:
FileSystemUsage usageStats = getSigarProxy().getFileSystemUsage(fileSystemDirectoryPath);
The getSigarProxy() is just a convenience base method:
// The Humidor handles thread safety for a single instance of a Sigar object
static final private SigarProxy sigarProxy = Humidor.getInstance().getSigar();
static final protected SigarProxy getSigarProxy() {
return sigarProxy;
}
You can use java.nio.file.FileSystems to get a list of java.nio.file.FileStorages and then see the usable/available space. Per instance (assuming that you are using Java 7+):
import java.io.IOException;
import java.nio.file.FileStore;
import java.nio.file.FileSystem;
import java.nio.file.FileSystems;
import java.util.function.Consumer;
public static void main(String[] args) {
FileSystem fs = FileSystems.getDefault();
fs.getFileStores().forEach(new Consumer<FileStore>() {
#Override
public void accept(FileStore store) {
try {
System.out.println(store.getTotalSpace());
System.out.println(store.getUsableSpace());
} catch (IOException e) {
e.printStackTrace();
}
}
});
}
Also, keep in mind that FileStore.getUsableSpace() returns the size in bytes. See the docs for more information.

JSONObject.toString() returns OutOfMemoryError

I have an Android app.
First, the app do sync process. In this process, the server sends to the device an JSON object as String by which it can build the available questionnaires.
GetQuestionnairesResponse.java:
public class GetQuestionnairesResponse extends ResponseHandler
{
public GetQuestionnairesResponse(String result, AsyncRequest request)
{
super(result, request);
}
#Override
public void handleResponse()
{
DataSyncActivity caller = (DataSyncActivity) request.getCaller();
BackgroundManager bckMng = BackgroundManager.getInstance(caller);
PreferencesManager preference = PreferencesManager.getInstance(null);
boolean status = true;
int numOfWrongJsonVer = 0;
int totalNumOfQuestionnaires = 0;
// Handle data from server
// Creating JSON Parser instance
try
{
QuestionnaireDataSource questionnaireDS = new QuestionnaireDataSource(caller);
questionnaireDS.open();
JSONArray jArr = new JSONArray(result);
JSONObject j = null;
totalNumOfQuestionnaires = jArr.length();
for (int i = 0; i < jArr.length(); i++)
{
j = jArr.getJSONObject(i);
long questId = j.getLong("questionnaireId");
long surveyId = j.getLong("surveyId");
String questName = j.getString("name");
String desc = j.getString("description");
int version = j.getInt("questionnaireVersion");
int jsonVersion = j.getInt("jsonVersion");
if (jsonVersion == PreferencesManager.jsonVersion)
{
// Save the pages part
String filename = questId + "_" + version + "_" + jsonVersion + ".json";
HelpFunctions.writeJSON(filename, j.toString());
Questionnaire quest = questionnaireDS.createQuestionnaire(questId, questName, desc, surveyId, version, jsonVersion, filename);
if (quest == null)
throw new RuntimeException("Cant save the questionnaire: " + questName);
}
else
{
numOfWrongJsonVer ++;
}
}
questionnaireDS.close();
}
catch (Exception e)
{
status = false;
if (e.getMessage() != null)
Log.e(TAG, e.getMessage());
}
caller.setInSync(false);
...
}
The result i get from the server i parse it to Json array.
The result in some cases can bee 3 megabytes.
The solution I found was to add an attribute in manifest.xml:
android:largeHeap="true"
It solved the problem. I don't know why but the problem returned again in the last day.
I will be happy to get suggestions how to solve the problem.
The problem is that the json object not parsed as expected so it
If the JSON was originally 3 MB and you call toString() on the JSONObject parsed from it, the JSONObject is still taking up memory, plus it's going to need to do a 3 MB allocation to hold the String. You may not have that much memory available.
But the thing about OutOfMemoryError is that the allocation that uses up the last bit of RAM isn't necessarily to blame for there being so little RAM available. Big allocations are just more likely to be the thing that pushes it over the edge. It's likely that you have a memory leak somewhere else in your app, and you'll need to use a tool like Eclipse MAT to find it.

How can I check if I am running 32bit or 64bit java in C#

I am writing my first C# program and I want to check using C# code if I am running a 32 or 64 bit version of java ?
I tried this but when I add this code to my class I am not able to debug it
RegistryKey rk = Registry.LocalMachine;
RegistryKey subKey = rk.OpenSubKey("SOFTWARE\\JavaSoft\\Java Runtime Environment");
string currentVerion = subKey.GetValue("CurrentVersion").ToString();
How can I do it ?
Thanks
It isn't clear how you are going to identify which java.exe you are using - a single machine can have many installed. You may have a specific path, or you may need to either use the JAVA_HOME environment variable, or search PATH, or do a combination of both and give priority to one or the other depending on your requirements.
Once you've got your path to java.exe you can use the technique from Kris Stanton on MSDN (which I will repeat here, but is currently linked at MSDN > "Exploring pe file headers using managed code"):
public enum MachineType
{
Native = 0, I586 = 0x014c, Itanium = 0x0200, x64 = 0x8664
}
public static MachineType GetMachineType(string fileName)
{
// dos header is 64 bytes
// PE header address is 4 bytes
const int PE_PTR_OFFSET = 60;
const int MACHINE_OFFSET = 4;
byte[] data = new byte[4096];
using (Stream stm = new FileStream(fileName, FileMode.Open, FileAccess.Read))
{
stm.Read(data, 0, 4096);
}
int PE_HDR_ADDR = BitConverter.ToInt32(data, PE_PTR_OFFSET);
int machineUint = BitConverter.ToUInt16(data, PE_HDR_ADDR + MACHINE_OFFSET);
return (MachineType)machineUint;
}
To find java.exe on the %PATH% variable, you can call FindOnPath("java.exe"):
public static String FindOnPath(string exeName)
{
foreach (string test in (Environment.GetEnvironmentVariable("PATH") ?? "").Split(';'))
{
string path = test.Trim();
if (!String.IsNullOrEmpty(path) && File.Exists(path = Path.Combine(path, exeName)))
return Path.GetFullPath(path);
}
return null;
}
On my machine, the following code
static void Main(string[] args)
{
String path = FindOnPath("java.exe");
Console.WriteLine(path);
Console.WriteLine(GetMachineType(path));
}
writes the following output:
C:\ProgramData\Oracle\Java\javapath\java.exe
x64
You can do it through the registry. I knocked together a quick example for you:
private string GetJavaInstallationPath()
{
string environmentPath = Environment.GetEnvironmentVariable("JAVA_HOME");
if (!string.IsNullOrEmpty(environmentPath))
{
return environmentPath;
}
string javaKey = "SOFTWARE\\JavaSoft\\Java Runtime Environment\\";
using (Microsoft.Win32.RegistryKey rk = Microsoft.Win32.Registry.LocalMachine.OpenSubKey(javaKey))
{
string currentVersion = rk.GetValue("CurrentVersion").ToString();
using (Microsoft.Win32.RegistryKey key = rk.OpenSubKey(currentVersion))
{
return key.GetValue("JavaHome").ToString();
}
}
}
Then to use it, just do the following:
string installPath = GetJavaInstallationPath();
string filePath = System.IO.Path.Combine(installPath, "bin\\Java.exe");
if (System.IO.File.Exists(filePath))
{
// We have a winner
}
I`m use this code:
public static bool CheckJavaInstallation()
{
try
{
//ProcessStartInfo procStartInfo = new ProcessStartInfo("java", " -version"); // Check that any Java installed
//ProcessStartInfo procStartInfo = new ProcessStartInfo("java", "-d32 -version"); // Check that 32 bit Java installed
ProcessStartInfo procStartInfo = new ProcessStartInfo("java", "-d64 -version"); // Check that 64 bit Java installed
procStartInfo.RedirectStandardOutput = true;
procStartInfo.RedirectStandardError = true;
procStartInfo.UseShellExecute = false;
procStartInfo.CreateNoWindow = true;
Process proc = new Process {StartInfo = procStartInfo};
proc.Start();
proc.BeginOutputReadLine();
proc.BeginErrorReadLine();
proc.WaitForExit();
return proc.ExitCode == 0;
}
catch (Exception ex)
{
return false;
}
}

android internal memory usage

I am new in Android and I want to find free memory in internal storage. I use two function to find free memory but they show me two different values in long format. I don't know why?
Here is my code:
1) Result of getTIM() function is 558628864
public String getTIM(){
File path = Environment.getDataDirectory();
StatFs stat = new StatFs(path.getPath());
long blockSize = stat.getBlockSize();
long totalBlocks = stat.getBlockCount();
String str = Long.toString(blockSize * totalBlocks);
return str;
}
2) Result of ITMStr() function is 914120704
public String ITMStr(){
StatFs statFs = new StatFs(Environment.getRootDirectory().getAbsolutePath());
long blockCount = statFs.getBlockCountLong();
long blockSize = statFs.getBlockSizeLong();
long total = blockCount * blockSize;
String str = Long.toString(total);
return str;
}
Which value is right?
According to reference:
public static File getDataDirectory ()
Added in API level 1 Return the user data directory.
_
public static File getRootDirectory ()
Added in API level 1 Return root of the "system" partition holding the
core Android OS. Always present and mounted read-only.
So sizes are different as you are getting sizes for different stuff.

Jacob Export Outlook Contact Pictures (Java, Jacob)

Good Morning,
I’am using Jacob 1.17 o read all my Outlook Contact Pictures and save them to an File. The Procedure works pretty fine for the first 199 Contatcs. After that the Dispatch.call fails and terminates with the following Exception:
Exception in thread "main" com.jacob.com.ComFailException: Invoke of: SaveAsFile
Source: Microsoft Outlook
Description: Cannot save the attachment. Cannot create file: ContactPicture.jpg.
Right-click the folder you want to create the file in, and then click Properties on
the shortcut menu to check your permissions for the folder.
at com.jacob.com.Dispatch.invokev(Native Method)
at com.jacob.com.Dispatch.invokev(Dispatch.java:625)
at com.jacob.com.Dispatch.callN(Dispatch.java:453)
at com.jacob.com.Dispatch.call(Dispatch.java:541)
at outlookStuff.ManageContactsOutlook.tmpTest(ManageContactsOutlook.java:217)
at mainPackage.Main.main(Main.java:32)
I’m really not sure way. I tested a different set of Contacts – same Error. Set all Objects to null to make shore that the Garbage Collector is involved but it doesn’t help.
The piece of Code which makes the trouble:
public void tmpTest(int intOutlookFolder, String strWorkingDir) {
Dispatch dipNamespace = this.axc.getProperty("Session").toDispatch();
Dispatch dipContactsFolder = Dispatch.call(dipNamespace, "GetDefaultFolder", (Object) new Integer(intOutlookFolder)).toDispatch();
Dispatch dipContactItems = Dispatch.get(dipContactsFolder, "items").toDispatch();
#SuppressWarnings("deprecation")
int count = Dispatch.call(dipContactItems, "Count").toInt();
for (int i=1; i<=count; i++) {
Dispatch dipContact;
dipContact = Dispatch.call(dipContactItems, "Item", new Integer(i)).toDispatch();
String strEntryID = Dispatch.get(dipContact, "EntryID").toString().trim();
//For Testing
Status.printStatusToConsole("Outlook Contact "+strEntryID+" loaded");
byte[] byteContactPicture = null;
String strPathToTmpPicture = null;
Dispatch dipAttachments = Dispatch.get(dipContact, "Attachments").toDispatch();
#SuppressWarnings("deprecation")
int countAttachements = Dispatch.call((Dispatch) dipAttachments, "Count").toInt();
for (int j=1; j<=countAttachements; j++) {
Dispatch currentAttachement;
currentAttachement = Dispatch.call(dipAttachments, "Item", new Integer(j)).toDispatch();
if (Dispatch.get(currentAttachement, "FileName").toString().equals("ContactPicture.jpg")) {
strPathToTmpPicture = strWorkingDir+strEntryID+".jpg";
//The Crashing Part
Dispatch.call(currentAttachement, "SaveAsFile", strPathToTmpPicture);
File tmpFile = new File(strPathToTmpPicture);
if (tmpFile.exists()) {
try {
byteContactPicture = org.apache.commons.io.FileUtils.readFileToByteArray(tmpFile);
} catch (IOException e) {
e.printStackTrace();
}
}
currentAttachement = null;
tmpFile = null;
}
currentAttachement = null;
}
dipAttachments = null;
}
dipContactItems = null;
dipContactsFolder = null;
dipNamespace = null;
}
May someone has an idea?
Thanks
Aviation

Categories

Resources