Here there is an issue in getting the IP Address. I have seen every possible way to remove deprecated formatIpAddress but nothing is giving me right solution I had used MAC address exact same way and I got Mac Address But when I am using Ip Address the output is 0.0.0.0.
The Code is:
WifiManager wifiManager = (WifiManager) getActivity().getSystemService(Context.WIFI_SERVICE);
WifiInfo wifiInfo = wifiManager.getConnectionInfo();
//Ip Address
int ipAddress = wifiInfo.getIpAddress();
String ip = Formatter.formatIpAddress(wifiManager.getConnectionInfo().getIpAddress());
TextView ip_address= (TextView) v.findViewById(R.id.ip_address_mobfragment);
ip_address.setText(""+ip);
did you added the permissions to your manifest (not quite sure if you need them tbh)?
<uses-permission android:name="android.permission.INTERNET" />
<uses-permission android:name="android.permission.ACCESS_NETWORK_STATE" />
try this work for me
WifiManager wm = (WifiManager)getActivity().getSystemService(getActivity().WIFI_SERVICE);
String ip = Formatter.formatIpAddress(wm.getConnectionInfo().getIpAddress());
Log.d("ipaddress",""+ip);
AndroidManifest.xml
<uses-permission android:name="android.permission.ACCESS_WIFI_STATE" />
<uses-permission android:name="android.permission.INTERNET"/>
<uses-permission android:name="android.permission.ACCESS_NETWORK_STATE"/>
Well I got the solution from my own problem.I had used this method to print IP
Here is my code:
public class Utils {
/**
* Convert byte array to hex string
* #param bytes
* #return
*/
public static String bytesToHex(byte[] bytes) {
StringBuilder sbuf = new StringBuilder();
for(int idx=0; idx < bytes.length; idx++) {
int intVal = bytes[idx] & 0xff;
if (intVal < 0x10) sbuf.append("0");
sbuf.append(Integer.toHexString(intVal).toUpperCase());
}
return sbuf.toString();
}
/**
* Get utf8 byte array.
* #param str
* #return array of NULL if error was found
*/
public static byte[] getUTF8Bytes(String str) {
try { return str.getBytes("UTF-8"); } catch (Exception ex) { return null; }
}
/**
* Load UTF8withBOM or any ansi text file.
* #param filename
* #return
* #throws java.io.IOException
*/
public static String loadFileAsString(String filename) throws java.io.IOException {
final int BUFLEN=1024;
BufferedInputStream is = new BufferedInputStream(new FileInputStream(filename), BUFLEN);
try {
ByteArrayOutputStream baos = new ByteArrayOutputStream(BUFLEN);
byte[] bytes = new byte[BUFLEN];
boolean isUTF8=false;
int read,count=0;
while((read=is.read(bytes)) != -1) {
if (count==0 && bytes[0]==(byte)0xEF && bytes[1]==(byte)0xBB && bytes[2]==(byte)0xBF ) {
isUTF8=true;
baos.write(bytes, 3, read-3); // drop UTF8 bom marker
} else {
baos.write(bytes, 0, read);
}
count+=read;
}
return isUTF8 ? new String(baos.toByteArray(), "UTF-8") : new String(baos.toByteArray());
} finally {
try{ is.close(); } catch(Exception ex){}
}
}
/**
* Returns MAC address of the given interface name.
* #param interfaceName eth0, wlan0 or NULL=use first interface
* #return mac address or empty string
*/
public static String getMACAddress(String interfaceName) {
try {
List<NetworkInterface> interfaces = Collections.list(NetworkInterface.getNetworkInterfaces());
for (NetworkInterface intf : interfaces) {
if (interfaceName != null) {
if (!intf.getName().equalsIgnoreCase(interfaceName)) continue;
}
byte[] mac = intf.getHardwareAddress();
if (mac==null) return "";
StringBuilder buf = new StringBuilder();
for (int idx=0; idx<mac.length; idx++)
buf.append(String.format("%02X:", mac[idx]));
if (buf.length()>0) buf.deleteCharAt(buf.length()-1);
return buf.toString();
}
} catch (Exception ex) { } // for now eat exceptions
return "";
/*try {
// this is so Linux hack
return loadFileAsString("/sys/class/net/" +interfaceName + "/address").toUpperCase().trim();
} catch (IOException ex) {
return null;
}*/
}
public static String getIPAddress(boolean useIPv4) {
try {
List<NetworkInterface> interfaces = Collections.list(NetworkInterface.getNetworkInterfaces());
for (NetworkInterface intf : interfaces) {
List<InetAddress> addrs = Collections.list(intf.getInetAddresses());
for (InetAddress addr : addrs) {
if (!addr.isLoopbackAddress()) {
String sAddr = addr.getHostAddress();
//boolean isIPv4 = InetAddressUtils.isIPv4Address(sAddr);
boolean isIPv4 = sAddr.indexOf(':')<0;
if (useIPv4) {
if (isIPv4)
return sAddr;
} else {
if (!isIPv4) {
int delim = sAddr.indexOf('%'); // drop ip6 zone suffix
return delim<0 ? sAddr.toUpperCase() : sAddr.substring(0, delim).toUpperCase();
}
}
}
}
}
} catch (Exception ex) { } // for now eat exceptions
return "";
}
and in the activity where I have to use is:
String ip=Utils.getIPAddress(true);
Related
I am learning to make dictionary app. And I have a little database with 20 words in one table and 20 definitions to that words in another table. But the definitions are in BLOB type. And I can not get its normal string type. Here is the code I tried :
public byte[] word_value(int a) throws UnsupportedEncodingException {
c = database.rawQuery("select body from items A inner join items_info B on A.id = B.id where B.id = '" + a + "';" , null);
while (c.moveToNext()){
byte[] blob = c.getBlob(0);
String s = new String(blob, StandardCharsets.UTF_8);
Toast.makeText(this, s, Toast.LENGTH_SHORT).show();
}
return null;
}
It gets the value but don't converts to string
Any help is appreciated
blew methods will help you
/**
* #param data
* #return
*/
public static String byteToHex(byte[] data) {
StringBuilder buf = new StringBuilder();
for (byte b : data) {
int halfbyte = (b >>> 4) & 0x0F;
int two_halfs = 0;
do {
buf.append((0 <= halfbyte) && (halfbyte <= 9) ? (char) ('0' + halfbyte) : (char) ('a' + (halfbyte - 10)));
halfbyte = b & 0x0F;
} while (two_halfs++ < 1);
}
return buf.toString();
}
/**
* #param str
* #return
*/
public static byte[] hexToBytes(String str) {
if (str == null) {
return null;
} else if (str.length() < 2) {
return null;
} else {
int len = str.length() / 2;
byte[] buffer = new byte[len];
for (int i = 0; i < len; i++) {
buffer[i] = (byte) Integer.parseInt(
str.substring(i * 2, i * 2 + 2), 16);
}
return buffer;
}
}
/**
* #param data
* #return
*/
public static String byteToString(byte[] data) {
String string = null;
try {
string = new String(data, "UTF-8");
} catch (UnsupportedEncodingException e) {
Logger.w(TAG, e);
}
return string;
}
/**
* #param data
* #return
*/
public static byte[] stringToByte(String data) {
byte[] bytes = null;
try {
bytes = data.getBytes("UTF-8");
} catch (UnsupportedEncodingException e) {
Logger.w(TAG, e);
}
return bytes;
}
/**
* #param input
* #return
*/
public static byte[] hexStringToByteArray(String input) {
int len = input.length();
byte[] data = new byte[len / 2];
for (int i = 0; i < len; i += 2) {
data[i / 2] = (byte) ((Character.digit(input.charAt(i), 16) << 4)
+ Character.digit(input.charAt(i + 1), 16));
}
return data;
}
I use the common tcp client to receive string messages through TCP.
I want after the reception of a specific message e.g. "XXX" my client to be ready to receive a bmp image.
My server in C++ sends the messages but the client does not receive the image...
After some suggestions .. se below I udated the code...
Here is my code:
TCP client:
public class TCPClient {
private String serverMessage;
public static final String SERVERIP = "192.168.1.88"; //your computer IP
public static final int SERVERPORT = 80;
private OnMessageReceived mMessageListener = null;
private boolean mRun = false;
private PrintWriter out;
private BufferedReader input;
private DataInputStream dis;
/**
* Constructor of the class. OnMessagedReceived listens for the messages received from server
*/
public TCPClient(OnMessageReceived listener) {
mMessageListener = listener;
}
/**
* Sends the message entered by client to the serveraddress
* #param message text entered by client
*/
public void sendMessage(String message){
if (out != null && !out.checkError()) {
out.println(message);
out.flush();
}
}
public void stopClient(){
mRun = false;
if (out != null) {
out.flush();
out.close();
}
mMessageListener = null;
input = null;
input = null;
input = null;
serverMessage = null;
}
public void run() {
mRun = true;
try {
//here you must put your computer's IP address.
InetAddress serverAddr = InetAddress.getByName(SERVERIP);
Log.e("TCP Client", "C: Connecting...");
//create a socket to make the connection with the server
Socket socket = new Socket(serverAddr, SERVERPORT);
try {
//send the message to the server
out = new PrintWriter(new BufferedWriter(new OutputStreamWriter(socket.getOutputStream())), true);
Log.e("TCP Client", "C: Sent.");
Log.e("TCP Client", "C: Done.");
//receive the message which the server sends back
dis = new DataInputStream(socket.getInputStream());
// The buffer reader cannot can't wrap an InputStream directly. It wraps another Reader.
// So inputstreamreader is used.
input = new BufferedReader(new InputStreamReader(dis, "UTF-8"));
Log.d("MyApp","We are here");
//this.input = new DataInputStream(in);
//in this while the client listens for the messages sent by the server
while (mRun) {
Log.d("MyApp", "We are here 2");
serverMessage = input.readLine();
if (serverMessage != null && mMessageListener != null) {
//call the method messageReceived from MyActivity class
mMessageListener.messageReceived(serverMessage);
Log.d("RESPONSE FROM SERVER", "S: Received Message: '" + serverMessage + "'");
}
if ("XXX".equals(serverMessage)) {
Log.d("MyApp", "We are here 3");
serverMessage = null;
while (mRun) {
WriteSDCard writeSDCard = new WriteSDCard();
writeSDCard.writeToSDFile(serverMessage);
}
}
}
} finally {
socket.close();
}
Log.e("RESPONSE FROM SERVER", "S: Received Message: '" + serverMessage + "'");
} catch (Exception e) {
Log.e("TCP", "S: Error", e);
} finally {
//the socket must be closed. It is not possible to reconnect to this socket
// after it is closed, which means a new socket instance has to be created.
}
}
//Declare the interface. The method messageReceived(String message) will must be implemented in the MyActivity
//class at on asynckTask doInBackground
public interface OnMessageReceived {
public void messageReceived(String message);
}
}
public class WriteSDCard extends Activity {
private static final String TAG = "MEDIA";
private TextView tv;
/** Called when the activity is first created. */
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
//(not needed) setContentView(R.layout.main);
//(not needed) tv = (TextView) findViewById(R.id.TextView01);
checkExternalMedia();
String message =null;
}
/** Method to check whether external media available and writable. This is adapted from
http://developer.android.com/guide/topics/data/data-storage.html#filesExternal */
private void checkExternalMedia(){
boolean mExternalStorageAvailable = false;
boolean mExternalStorageWriteable = false;
String state = Environment.getExternalStorageState();
if (Environment.MEDIA_MOUNTED.equals(state)) {
// Can read and write the media
mExternalStorageAvailable = mExternalStorageWriteable = true;
} else if (Environment.MEDIA_MOUNTED_READ_ONLY.equals(state)) {
// Can only read the media
mExternalStorageAvailable = true;
mExternalStorageWriteable = false;
} else {
// Can't read or write
mExternalStorageAvailable = mExternalStorageWriteable = false;
}
tv.append("\n\nExternal Media: readable="
+mExternalStorageAvailable+" writable="+mExternalStorageWriteable);
}
/** Method to write ascii text characters to file on SD card. Note that you must add a
WRITE_EXTERNAL_STORAGE permission to the manifest file or this method will throw
a FileNotFound Exception because you won't have write permission. */
void writeToSDFile(String inputMsg){
// Find the root of the external storage.
// See http://developer.android.com/guide/topics/data/data- storage.html#filesExternal
File root = android.os.Environment.getExternalStorageDirectory();
tv.append("\nExternal file system root: "+root);
// See http://stackoverflow.com/questions/3551821/android-write-to-sd-card-folder
File dir = new File (root.getAbsolutePath() + "/download");
dir.mkdirs();
Log.d("WriteSDCard", "Start writing");
File file = new File(dir, "myData.txt");
try {
FileOutputStream f = new FileOutputStream(file);
PrintWriter pw = new PrintWriter(f);
pw.println(inputMsg);
pw.flush();
pw.close();
f.close();
} catch (FileNotFoundException e) {
e.printStackTrace();
Log.i(TAG, "******* File not found. Did you" +
" add a WRITE_EXTERNAL_STORAGE permission to the manifest?");
} catch (IOException e) {
e.printStackTrace();
}
tv.append("\n\nFile written to "+file);
}
/** Method to read in a text file placed in the res/raw directory of the application. The
method reads in all lines of the file sequentially. */
}
And the server side:
Code:
void sendBMP( int cs, int xs, int ys)
{
int imgdataoffset = 14 + 40; // file header size + bitmap header size
int rowsz = ((xs) + 3) & -4; // size of one padded row of pixels
int imgdatasize = (((xs*3) + 3) & -4) * ys; // size of image data
int filesize = imgdataoffset + imgdatasize;
int i, y;
HTLM_bmp_H HTLM_bmp_h;
HTLM_bmp_h.bmfh.bfSize = filesize;
HTLM_bmp_h.bmfh.bfReserved1 = 0;
HTLM_bmp_h.bmfh.bfReserved2 = 0;
HTLM_bmp_h.bmfh.bfOffBits = imgdataoffset;
HTLM_bmp_h.bmih.biSize = 40;
HTLM_bmp_h.bmih.biWidth = xs;
HTLM_bmp_h.bmih.biHeight = ys;
HTLM_bmp_h.bmih.biPlanes = 1;
HTLM_bmp_h.bmih.biBitCount = 24;
HTLM_bmp_h.bmih.biCompression = 0;
HTLM_bmp_h.bmih.biSizeImage = imgdatasize;
HTLM_bmp_h.bmih.biXPelsPerMeter = 1000;
HTLM_bmp_h.bmih.biYPelsPerMeter = 1000;
HTLM_bmp_h.bmih.biClrUsed = 1 << 24;
HTLM_bmp_h.bmih.biClrImportant = 0;
printf("Start Sending BMP.\n");
send(cs,(unsigned char *)"BM",2,0);
send(cs,(unsigned char *)&HTLM_bmp_h,sizeof(HTLM_bmp_h),0);
printf("Sending...\n");
Buff_ptr = 0;
send(cs, (unsigned char *)Rbuffer, BUFF_SIZE,0 );
send(cs, (unsigned char *)Gbuffer, BUFF_SIZE,0 );
send(cs, (unsigned char *)Bbuffer, BUFF_SIZE,0 );
send(cs, (unsigned char *)"\n",1,0);
send(cs, (unsigned char *)"END\n",4,0);
printf("Done\n\n");
}
typedef struct {
// char bfType1;
// char bfType2;
int bfSize;
short bfReserved1;
short bfReserved2;
int bfOffBits;
} BMFH;
typedef struct {
unsigned int biSize;
int biWidth;
int biHeight;
short biPlanes;
short biBitCount;
unsigned int biCompression;
unsigned int biSizeImage;
int biXPelsPerMeter;
int biYPelsPerMeter;
unsigned int biClrUsed;
unsigned int biClrImportant;
} BMIH;
typedef struct {
BMFH bmfh;
BMIH bmih;
} HTLM_bmp_H;
main()
{
TSK_Handle tsk_cam;
tsk_cam=TSK_create( (Fxn)TSK_webview, NULL);
TSK_setpri(tsk_cam, 8);
}
char buffer[2048];
Void TSK_webview()
{
int s,cs;
struct sockaddr_in addr; /* generic socket name */
struct sockaddr client_addr;
int sock_len = sizeof(struct sockaddr);
int frame = 0;
LgUns i=0;
int len;
int x = DSKeye_SXGA_WIDTH, y = DSKeye_SXGA_HEIGHT;
DSKeye_params CAM_params = {
....
};
lwIP_NetStart();
/**************************************************************
* Main loop.
***************************************************************/
s = socket( AF_INET, SOCK_STREAM, 0 );
addr.sin_port = htons(80);
addr.sin_addr.s_addr = 0;
memset(&(addr.sin_zero), 0, sizeof(addr.sin_zero));
printf("start\n");
if( bind(s, (struct sockaddr*)&addr, sizeof(struct sockaddr)))
{
printf("error binding to port\n");
return ;
}
printf("xx1\n");
if(DSKeye_open(&CAM_params)) {
printf("xx2\n");
SYS_abort("DSKcam_CAMopen");
printf("xx3\n"); fflush(stdout);}
printf("xx4\n");
while(1==1) {
printf("Waiting for client to be connected ... \n");
listen(s, 10);
cs = accept(s, &client_addr, &sock_len);
printf("Client connected.\n");
send(cs,(unsigned char *)"Server connected\n",17,0);
recv(cs, (unsigned char*)buffer, 17, 0);
switch (*(buffer)){
case 'A' :
...
case 'B' :
...
}
REG32(0xA0000080)=REG32(0xA0000080) - 0x800000; ///Disable stepper controller vhdl Quartus Block
for(frame = 0; frame < 4; frame++){ // Allow AEC etc to settle
SrcFrame=DSKeye_getFrame();
}
printf("Demosaicing of %d x %d image is ongoing \n", x, y);
demosaic(SrcFrame, x, y);
break;
}
printf("Demosaicing completed ...\n");
send(cs,(unsigned char *)"Demosaicing completed\n",22,0);
send(cs,(unsigned char *)"XXX\n",4,0);
sendBMP(cs, x, y);
fflush(stdout);
lwip_close(cs);
}
the send : lwip_send
int lwip_send(int s, void *data, int size, unsigned int flags)
{
struct lwip_socket *sock;
struct netbuf *buf;
err_t err;
LWIP_DEBUGF(SOCKETS_DEBUG, ("lwip_send(%d, data=%p, size=%d, flags=0x%x)\n", s, data, size, flags));
sock = get_socket(s);
if (!sock) {
set_errno(EBADF);
return -1;
}
switch (netconn_type(sock->conn)) {
case NETCONN_RAW:
case NETCONN_UDP:
case NETCONN_UDPLITE:
case NETCONN_UDPNOCHKSUM:
/* create a buffer */
buf = netbuf_new();
if (!buf) {
LWIP_DEBUGF(SOCKETS_DEBUG, ("lwip_send(%d) ENOBUFS\n", s));
sock_set_errno(sock, ENOBUFS);
return -1;
}
/* make the buffer point to the data that should
be sent */
netbuf_ref(buf, data, size);
/* send the data */
err = netconn_send(sock->conn, buf);
/* deallocated the buffer */
netbuf_delete(buf);
break;
case NETCONN_TCP:
err = netconn_write(sock->conn, data, size, NETCONN_COPY);
break;
default:
err = ERR_ARG;
break;
}
if (err != ERR_OK) {
LWIP_DEBUGF(SOCKETS_DEBUG, ("lwip_send(%d) err=%d\n", s, err));
sock_set_errno(sock, err_to_errno(err));
return -1;
}
LWIP_DEBUGF(SOCKETS_DEBUG, ("lwip_send(%d) ok size=%d\n", s, size));
sock_set_errno(sock, 0);
return size;
}
You can't mix a buffered reader and a data input stream on the same socket. The buffered reader will read-ahead and steal data you expect to read via the data input stream. You will have to use the data input stream for everything. And correspondingly at the sender.
You're doing incorrect comparison for string equality.
In Java, string comparison for equality is done using String.equals(Object anObject)
You're using if (serverMessage == "XXX") {....
You should use if ("XXX".equals(serverMessage)) {....
How can I ping some web server in Android to test if I've Internet connection?
So I need the method which pings the given site and returns false if I've no Internet and true if I have.
See this method, it's the best way to check for connectivity to a given server:
http://developer.android.com/reference/java/net/InetAddress.html#isReachable(int)
Use these methods to ping the server
public static void inSomeWhere()
{
String pingResult = getPingResult("168.126.63.1");
boolean isNetOk = true;
if (pingResult == null) {
// not reachable!!!!!
isNetOk = false;
}
}
public static String getPingResult(String a) {
String str = "";
String result = "";
BufferedReader reader = null;
char[] buffer = new char[4096];
StringBuffer output = new StringBuffer();
try {
Runtime r = Runtime.getRuntime();
Process process = r.exec("/system/bin/ping -c 3 " + a);
reader = new BufferedReader(new InputStreamReader(process.getInputStream()));
int i;
while ((i = reader.read(buffer)) > 0)
output.append(buffer, 0, i);
str = output.toString();
final String[] b = str.split("---");
final String[] c = b[2].split("rtt");
if (b.length == 0 || c.length == 0)
return null;
if(b.length == 1 || c.length == 1)
return null;
result = b[1].substring(1, b[1].length()) + c[0] + c[1].substring(1, c[1].length());
} catch (IOException e) {
return null;
} catch (Exception e) {
return null;
}
finally
{
if(reader != null)
{
try{reader.close();}catch(IOException ie){}
}
}
return result;
}
So i have this code here;
myIntent.putExtra("schedule",serializableClass);
and this intent goes to my Broadcast Reciever and i did get that serializable as below,
public void onRecieve(Context context, Intent intent)
{
Schedule s = (Schedule) intent.getSerializableExtra("schedule");
}
but it always returns even though when i put the Extras its not null, even checked before passing it on myIntent.putExtra() i really don't know what happen returns, why does it always returns null?.. anyone knows this problem?
The cast is wrong, i would be more easier to pass the serialized string and do deserialization. I' m using this class.
public final class ObjectSerializer {
private ObjectSerializer() {
}
public static String serialize(Serializable obj) throws IOException {
if (obj == null)
return "";
try {
ByteArrayOutputStream serialObj = new ByteArrayOutputStream();
ObjectOutputStream objStream = new ObjectOutputStream(serialObj);
objStream.writeObject(obj);
objStream.close();
return encodeBytes(serialObj.toByteArray());
} catch (Exception e) {
throw new IOException("Serialization error: " + e.getMessage(), e);
}
}
public static Object deserialize(String str) throws IOException {
if (str == null || str.length() == 0)
return null;
try {
ByteArrayInputStream serialObj = new ByteArrayInputStream(
decodeBytes(str));
ObjectInputStream objStream = new ObjectInputStream(serialObj);
return objStream.readObject();
} catch (Exception e) {
throw new IOException("Serialization error: " + e.getMessage(), e);
}
}
public static String encodeBytes(byte[] bytes) {
StringBuffer strBuf = new StringBuffer();
for (int i = 0; i < bytes.length; i++) {
strBuf.append((char) (((bytes[i] >> 4) & 0xF) + ('a')));
strBuf.append((char) (((bytes[i]) & 0xF) + ('a')));
}
return strBuf.toString();
}
public static byte[] decodeBytes(String str) {
byte[] bytes = new byte[str.length() / 2];
for (int i = 0; i < str.length(); i += 2) {
char c = str.charAt(i);
bytes[i / 2] = (byte) ((c - 'a') << 4);
c = str.charAt(i + 1);
bytes[i / 2] += (c - 'a');
}
return bytes;
}
}
after that use like this:
String scheduleSerialization = ObjectSerializer.serialize(schedule);
myIntent.putExtra("schedule",scheduleSerialization);
the last thing to do is:
public void onRecieve(Context context, Intent intent)
{
String serial = intent.getStringExtra("schedule");
if(serial!=null)
Schedule s = (Schedule) ObjectSerializer.deserialize(serial) ;
}
Using Serializable on Android is discouraged because it is slow. If you look at the android source code you will see that
the usually break down the information into multiple keys and send them as primitive types (Integer, String, etc..)
when that can't be done, the will use a Parcelable object
The most important things I want to know are the device type, the OS version, if it has a hardware keyboard and maybe the screen resolution. but if you know other useful debug information please add them :)
I found this for the OS version:
string += "OS Version: " + System.getProperty("os.version");
How do I get the other properties?
edit: to get a complete overview of useful attributes, I combined them all together in my ErrorHandler activity (start to read at line 56): https://github.com/simon-heinen/SimpleUi/blob/master/SimpleUI/srcAndroid/simpleui/util/DeviceInformation.java#L56
Windowsize and keyboard presence were a good idea, i added some more infos for debug purpose:
String s="Debug-infos:";
s += "\n OS Version: " + System.getProperty("os.version") + "(" + android.os.Build.VERSION.INCREMENTAL + ")";
s += "\n OS API Level: " + android.os.Build.VERSION.SDK_INT;
s += "\n Device: " + android.os.Build.DEVICE;
s += "\n Model (and Product): " + android.os.Build.MODEL + " ("+ android.os.Build.PRODUCT + ")";
Here is all device informations that is possible in android using below enum and utility class
public enum Device {
DEVICE_TYPE, DEVICE_SYSTEM_NAME, DEVICE_VERSION, DEVICE_SYSTEM_VERSION, DEVICE_TOKEN,
/**
*
*/
DEVICE_NAME, DEVICE_UUID, DEVICE_MANUFACTURE, IPHONE_TYPE,
/**
*
*/
CONTACT_ID, DEVICE_LANGUAGE, DEVICE_TIME_ZONE, DEVICE_LOCAL_COUNTRY_CODE,
/**
*
*/
DEVICE_CURRENT_YEAR, DEVICE_CURRENT_DATE_TIME, DEVICE_CURRENT_DATE_TIME_ZERO_GMT,
/**
*
*/
DEVICE_HARDWARE_MODEL, DEVICE_NUMBER_OF_PROCESSORS, DEVICE_LOCALE, DEVICE_NETWORK, DEVICE_NETWORK_TYPE,
/**
*
*/
DEVICE_IP_ADDRESS_IPV4, DEVICE_IP_ADDRESS_IPV6, DEVICE_MAC_ADDRESS, DEVICE_TOTAL_CPU_USAGE,
/**
*
*/
DEVICE_TOTAL_MEMORY, DEVICE_FREE_MEMORY, DEVICE_USED_MEMORY,
/**
*
*/
DEVICE_TOTAL_CPU_USAGE_USER, DEVICE_TOTAL_CPU_USAGE_SYSTEM,
/**
*
*/
DEVICE_TOTAL_CPU_IDLE, DEVICE_IN_INCH;
}
--> Utility class :
public class DeviceInfo {
public static String getDeviceInfo(Context activity, Device device) {
try {
switch (device) {
case DEVICE_LANGUAGE:
return Locale.getDefault().getDisplayLanguage();
case DEVICE_TIME_ZONE:
return TimeZone.getDefault().getID();//(false, TimeZone.SHORT);
case DEVICE_LOCAL_COUNTRY_CODE:
return activity.getResources().getConfiguration().locale.getCountry();
case DEVICE_CURRENT_YEAR:
return "" + (Calendar.getInstance().get(Calendar.YEAR));
case DEVICE_CURRENT_DATE_TIME:
Calendar calendarTime = Calendar.getInstance(TimeZone.getDefault(), Locale.getDefault());
long time = (calendarTime.getTimeInMillis() / 1000);
return String.valueOf(time);
// return DateFormat.getDateTimeInstance().format(new Date());
case DEVICE_CURRENT_DATE_TIME_ZERO_GMT:
Calendar calendarTime_zero = Calendar.getInstance(TimeZone.getTimeZone("GMT+0"), Locale.getDefault());
return String.valueOf((calendarTime_zero.getTimeInMillis() / 1000));
// DateFormat df = DateFormat.getDateTimeInstance();
// df.setTimeZone(TimeZone.getTimeZone("GMT+0"));
// return df.format(new Date());
case DEVICE_HARDWARE_MODEL:
return getDeviceName();
case DEVICE_NUMBER_OF_PROCESSORS:
return Runtime.getRuntime().availableProcessors() + "";
case DEVICE_LOCALE:
return Locale.getDefault().getISO3Country();
case DEVICE_IP_ADDRESS_IPV4:
return getIPAddress(true);
case DEVICE_IP_ADDRESS_IPV6:
return getIPAddress(false);
case DEVICE_MAC_ADDRESS:
String mac = getMACAddress("wlan0");
if (TextUtils.isEmpty(mac)) {
mac = getMACAddress("eth0");
}
if (TextUtils.isEmpty(mac)) {
mac = "DU:MM:YA:DD:RE:SS";
}
return mac;
case DEVICE_TOTAL_MEMORY:
if (Build.VERSION.SDK_INT >= 16)
return String.valueOf(getTotalMemory(activity));
case DEVICE_FREE_MEMORY:
return String.valueOf(getFreeMemory(activity));
case DEVICE_USED_MEMORY:
if (Build.VERSION.SDK_INT >= 16) {
long freeMem = getTotalMemory(activity) - getFreeMemory(activity);
return String.valueOf(freeMem);
}
return "";
case DEVICE_TOTAL_CPU_USAGE:
int[] cpu = getCpuUsageStatistic();
if (cpu != null) {
int total = cpu[0] + cpu[1] + cpu[2] + cpu[3];
return String.valueOf(total);
}
return "";
case DEVICE_TOTAL_CPU_USAGE_SYSTEM:
int[] cpu_sys = getCpuUsageStatistic();
if (cpu_sys != null) {
int total = cpu_sys[1];
return String.valueOf(total);
}
return "";
case DEVICE_TOTAL_CPU_USAGE_USER:
int[] cpu_usage = getCpuUsageStatistic();
if (cpu_usage != null) {
int total = cpu_usage[0];
return String.valueOf(total);
}
return "";
case DEVICE_MANUFACTURE:
return android.os.Build.MANUFACTURER;
case DEVICE_SYSTEM_VERSION:
return String.valueOf(getDeviceName());
case DEVICE_VERSION:
return String.valueOf(android.os.Build.VERSION.SDK_INT);
case DEVICE_IN_INCH:
return getDeviceInch(activity);
case DEVICE_TOTAL_CPU_IDLE:
int[] cpu_idle = getCpuUsageStatistic();
if (cpu_idle != null) {
int total = cpu_idle[2];
return String.valueOf(total);
}
return "";
case DEVICE_NETWORK_TYPE:
return getNetworkType(activity);
case DEVICE_NETWORK:
return checkNetworkStatus(activity);
case DEVICE_TYPE:
if (isTablet(activity)) {
if (getDeviceMoreThan5Inch(activity)) {
return "Tablet";
} else
return "Mobile";
} else {
return "Mobile";
}
case DEVICE_SYSTEM_NAME:
return "Android OS";
default:
break;
}
} catch (Exception e) {
e.printStackTrace();
}
return "";
}
public static String getDeviceId(Context context) {
String device_uuid = Secure.getString(context.getContentResolver(), Secure.ANDROID_ID);
if (device_uuid == null) {
device_uuid = "12356789"; // for emulator testing
} else {
try {
byte[] _data = device_uuid.getBytes();
MessageDigest _digest = java.security.MessageDigest.getInstance("MD5");
_digest.update(_data);
_data = _digest.digest();
BigInteger _bi = new BigInteger(_data).abs();
device_uuid = _bi.toString(36);
} catch (Exception e) {
if (e != null) {
e.printStackTrace();
}
}
}
return device_uuid;
}
#SuppressLint("NewApi")
private static long getTotalMemory(Context activity) {
try {
MemoryInfo mi = new MemoryInfo();
ActivityManager activityManager = (ActivityManager) activity.getSystemService(Context.ACTIVITY_SERVICE);
activityManager.getMemoryInfo(mi);
long availableMegs = mi.totalMem / 1048576L; // in megabyte (mb)
return availableMegs;
} catch (Exception e) {
e.printStackTrace();
return 0;
}
}
private static long getFreeMemory(Context activity) {
try {
MemoryInfo mi = new MemoryInfo();
ActivityManager activityManager = (ActivityManager) activity.getSystemService(Context.ACTIVITY_SERVICE);
activityManager.getMemoryInfo(mi);
long availableMegs = mi.availMem / 1048576L; // in megabyte (mb)
return availableMegs;
} catch (Exception e) {
e.printStackTrace();
return 0;
}
}
private static String getDeviceName() {
String manufacturer = Build.MANUFACTURER;
String model = Build.MODEL;
if (model.startsWith(manufacturer)) {
return capitalize(model);
} else {
return capitalize(manufacturer) + " " + model;
}
}
private static String capitalize(String s) {
if (s == null || s.length() == 0) {
return "";
}
char first = s.charAt(0);
if (Character.isUpperCase(first)) {
return s;
} else {
return Character.toUpperCase(first) + s.substring(1);
}
}
/**
* Convert byte array to hex string
*
* #param bytes
* #return
*/
private static String bytesToHex(byte[] bytes) {
StringBuilder sbuf = new StringBuilder();
for (int idx = 0; idx < bytes.length; idx++) {
int intVal = bytes[idx] & 0xff;
if (intVal < 0x10)
sbuf.append("0");
sbuf.append(Integer.toHexString(intVal).toUpperCase());
}
return sbuf.toString();
}
/**
* Returns MAC address of the given interface name.
*
* #param interfaceName eth0, wlan0 or NULL=use first interface
* #return mac address or empty string
*/
#SuppressLint("NewApi")
private static String getMACAddress(String interfaceName) {
try {
List<NetworkInterface> interfaces = Collections.list(NetworkInterface.getNetworkInterfaces());
for (NetworkInterface intf : interfaces) {
if (interfaceName != null) {
if (!intf.getName().equalsIgnoreCase(interfaceName))
continue;
}
byte[] mac = intf.getHardwareAddress();
if (mac == null)
return "";
StringBuilder buf = new StringBuilder();
for (int idx = 0; idx < mac.length; idx++)
buf.append(String.format("%02X:", mac[idx]));
if (buf.length() > 0)
buf.deleteCharAt(buf.length() - 1);
return buf.toString();
}
} catch (Exception ex) {
return "";
} // for now eat exceptions
return "";
/*
* try { // this is so Linux hack return
* loadFileAsString("/sys/class/net/" +interfaceName +
* "/address").toUpperCase().trim(); } catch (IOException ex) { return
* null; }
*/
}
/**
* Get IP address from first non-localhost interface
*
* #return address or empty string
*/
private static String getIPAddress(boolean useIPv4) {
try {
List<NetworkInterface> interfaces = Collections.list(NetworkInterface.getNetworkInterfaces());
for (NetworkInterface intf : interfaces) {
List<InetAddress> addrs = Collections.list(intf.getInetAddresses());
for (InetAddress addr : addrs) {
if (!addr.isLoopbackAddress()) {
String sAddr = addr.getHostAddress().toUpperCase();
boolean isIPv4 = InetAddressUtils.isIPv4Address(sAddr);
if (useIPv4) {
if (isIPv4)
return sAddr;
} else {
if (!isIPv4) {
int delim = sAddr.indexOf('%'); // drop ip6 port
// suffix
return delim < 0 ? sAddr : sAddr.substring(0, delim);
}
}
}
}
}
} catch (Exception ex) {
} // for now eat exceptions
return "";
}
/*
*
* #return integer Array with 4 elements: user, system, idle and other cpu
* usage in percentage.
*/
private static int[] getCpuUsageStatistic() {
try {
String tempString = executeTop();
tempString = tempString.replaceAll(",", "");
tempString = tempString.replaceAll("User", "");
tempString = tempString.replaceAll("System", "");
tempString = tempString.replaceAll("IOW", "");
tempString = tempString.replaceAll("IRQ", "");
tempString = tempString.replaceAll("%", "");
for (int i = 0; i < 10; i++) {
tempString = tempString.replaceAll(" ", " ");
}
tempString = tempString.trim();
String[] myString = tempString.split(" ");
int[] cpuUsageAsInt = new int[myString.length];
for (int i = 0; i < myString.length; i++) {
myString[i] = myString[i].trim();
cpuUsageAsInt[i] = Integer.parseInt(myString[i]);
}
return cpuUsageAsInt;
} catch (Exception e) {
e.printStackTrace();
Log.e("executeTop", "error in getting cpu statics");
return null;
}
}
private static String executeTop() {
java.lang.Process p = null;
BufferedReader in = null;
String returnString = null;
try {
p = Runtime.getRuntime().exec("top -n 1");
in = new BufferedReader(new InputStreamReader(p.getInputStream()));
while (returnString == null || returnString.contentEquals("")) {
returnString = in.readLine();
}
} catch (IOException e) {
Log.e("executeTop", "error in getting first line of top");
e.printStackTrace();
} finally {
try {
in.close();
p.destroy();
} catch (IOException e) {
Log.e("executeTop", "error in closing and destroying top process");
e.printStackTrace();
}
}
return returnString;
}
public static String getNetworkType(final Context activity) {
String networkStatus = "";
final ConnectivityManager connMgr = (ConnectivityManager)
activity.getSystemService(Context.CONNECTIVITY_SERVICE);
// check for wifi
final android.net.NetworkInfo wifi =
connMgr.getNetworkInfo(ConnectivityManager.TYPE_WIFI);
// check for mobile data
final android.net.NetworkInfo mobile =
connMgr.getNetworkInfo(ConnectivityManager.TYPE_MOBILE);
if (wifi.isAvailable()) {
networkStatus = "Wifi";
} else if (mobile.isAvailable()) {
networkStatus = getDataType(activity);
} else {
networkStatus = "noNetwork";
}
return networkStatus;
}
public static String checkNetworkStatus(final Context activity) {
String networkStatus = "";
try {
// Get connect mangaer
final ConnectivityManager connMgr = (ConnectivityManager)
activity.getSystemService(Context.CONNECTIVITY_SERVICE);
// // check for wifi
final android.net.NetworkInfo wifi =
connMgr.getNetworkInfo(ConnectivityManager.TYPE_WIFI);
// // check for mobile data
final android.net.NetworkInfo mobile =
connMgr.getNetworkInfo(ConnectivityManager.TYPE_MOBILE);
if (wifi.isAvailable()) {
networkStatus = "Wifi";
} else if (mobile.isAvailable()) {
networkStatus = getDataType(activity);
} else {
networkStatus = "noNetwork";
networkStatus = "0";
}
} catch (Exception e) {
e.printStackTrace();
networkStatus = "0";
}
return networkStatus;
}
public static boolean isTablet(Context context) {
return (context.getResources().getConfiguration().screenLayout & Configuration.SCREENLAYOUT_SIZE_MASK) >= Configuration.SCREENLAYOUT_SIZE_LARGE;
}
public static boolean getDeviceMoreThan5Inch(Context activity) {
try {
DisplayMetrics displayMetrics = activity.getResources().getDisplayMetrics();
// int width = displayMetrics.widthPixels;
// int height = displayMetrics.heightPixels;
float yInches = displayMetrics.heightPixels / displayMetrics.ydpi;
float xInches = displayMetrics.widthPixels / displayMetrics.xdpi;
double diagonalInches = Math.sqrt(xInches * xInches + yInches * yInches);
if (diagonalInches >= 7) {
// 5inch device or bigger
return true;
} else {
// smaller device
return false;
}
} catch (Exception e) {
return false;
}
}
public static String getDeviceInch(Context activity) {
try {
DisplayMetrics displayMetrics = activity.getResources().getDisplayMetrics();
float yInches = displayMetrics.heightPixels / displayMetrics.ydpi;
float xInches = displayMetrics.widthPixels / displayMetrics.xdpi;
double diagonalInches = Math.sqrt(xInches * xInches + yInches * yInches);
return String.valueOf(diagonalInches);
} catch (Exception e) {
return "-1";
}
}
public static String getDataType(Context activity) {
String type = "Mobile Data";
TelephonyManager tm = (TelephonyManager) activity.getSystemService(Context.TELEPHONY_SERVICE);
switch (tm.getNetworkType()) {
case TelephonyManager.NETWORK_TYPE_HSDPA:
type = "Mobile Data 3G";
Log.d("Type", "3g");
// for 3g HSDPA networktype will be return as
// per testing(real) in device with 3g enable
// data
// and speed will also matters to decide 3g network type
break;
case TelephonyManager.NETWORK_TYPE_HSPAP:
type = "Mobile Data 4G";
Log.d("Type", "4g");
// No specification for the 4g but from wiki
// i found(HSPAP used in 4g)
break;
case TelephonyManager.NETWORK_TYPE_GPRS:
type = "Mobile Data GPRS";
Log.d("Type", "GPRS");
break;
case TelephonyManager.NETWORK_TYPE_EDGE:
type = "Mobile Data EDGE 2G";
Log.d("Type", "EDGE 2g");
break;
}
return type;
}
}
-- Get IP Address without using InetAddressUtils class
private static final String IPV4_BASIC_PATTERN_STRING =
"(([0-9]|[1-9][0-9]|1[0-9]{2}|2[0-4][0-9]|25[0-5])\\.){3}" + // initial 3 fields, 0-255 followed by .
"([0-9]|[1-9][0-9]|1[0-9]{2}|2[0-4][0-9]|25[0-5])"; // final field, 0-255
private static final Pattern IPV4_PATTERN =
Pattern.compile("^" + IPV4_BASIC_PATTERN_STRING + "$");
public static boolean isIPv4Address(final String input) {
return IPV4_PATTERN.matcher(input).matches();
}
/**
* Get IP address from first non-localhost interface
*
* #return address or empty string
*/
private static String getIPAddress(boolean useIPv4) {
try {
List<NetworkInterface> interfaces = Collections.list(NetworkInterface.getNetworkInterfaces());
for (NetworkInterface intf : interfaces) {
List<InetAddress> addrs = Collections.list(intf.getInetAddresses());
for (InetAddress addr : addrs) {
if (!addr.isLoopbackAddress()) {
String sAddr = addr.getHostAddress().toUpperCase();
//TODO 3.0.0
boolean isIPv4 = isIPv4Address(sAddr);
if (useIPv4) {
if (isIPv4)
return sAddr;
} else {
if (!isIPv4) {
int delim = sAddr.indexOf('%'); // drop ip6 port
// suffix
return delim < 0 ? sAddr : sAddr.substring(0, delim);
}
}
}
}
}
} catch (Exception ex) {
} // for now eat exceptions
return "";
}
For screen resolution:
getWindow().getWindowManager().getDefaultDisplay().getWidth();
getWindow().getWindowManager().getDefaultDisplay().getHeight();
For hardware keyboard presence:
boolean keyboardPresent = (getResources().getConfiguration().keyboard != Configuration.KEYBOARD_NOKEYS);
you can try this >
import android.os.Build;
import android.os.StrictMode;
import android.provider.Settings;
import java.io.BufferedReader;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.util.regex.Matcher;
import java.util.regex.Pattern;
public class Utilies {
public static String android_id = Settings.Secure.getString(App.getContext().getContentResolver(), Settings.Secure.ANDROID_ID);
public static void getInternet() {
StrictMode.ThreadPolicy policy = new StrictMode.ThreadPolicy.Builder().permitAll().build();
StrictMode.setThreadPolicy(policy);
}
public static String readKernelVersion() {
try {
Process p = Runtime.getRuntime().exec("uname -a");
InputStream is = null;
if (p.waitFor() == 0) {
is = p.getInputStream();
} else {
is = p.getErrorStream();
}
BufferedReader br = new BufferedReader(new InputStreamReader(is), 1024);
String line = br.readLine();
br.close();
return line;
} catch (Exception ex) {
return "ERROR: " + ex.getMessage();
}
}
public static String getDeviceModelNumber() {
String manufacturer = Build.VERSION.CODENAME;
String model = Build.MODEL;
if (model.startsWith(manufacturer)) {
return capitalize(model);
} else {
return capitalize(manufacturer) + " " + model;
}
}
private static String capitalize(String s) {
if (s == null || s.length() == 0) {
return "";
}
char first = s.charAt(0);
if (Character.isUpperCase(first)) {
return s;
} else {
return Character.toUpperCase(first) + s.substring(1);
}
}
// get System info.
public static String OSNAME = System.getProperty("os.name");
public static String OSVERSION = System.getProperty("os.version");
public static String RELEASE = android.os.Build.VERSION.RELEASE;
public static String DEVICE = android.os.Build.DEVICE;
public static String MODEL = android.os.Build.MODEL;
public static String PRODUCT = android.os.Build.PRODUCT;
public static String BRAND = android.os.Build.BRAND;
public static String DISPLAY = android.os.Build.DISPLAY;
public static String CPU_ABI = android.os.Build.CPU_ABI;
public static String CPU_ABI2 = android.os.Build.CPU_ABI2;
public static String UNKNOWN = android.os.Build.UNKNOWN;
public static String HARDWARE = android.os.Build.HARDWARE;
public static String ID = android.os.Build.ID;
public static String MANUFACTURER = android.os.Build.MANUFACTURER;
public static String SERIAL = android.os.Build.SERIAL;
public static String USER = android.os.Build.USER;
public static String HOST = android.os.Build.HOST;
}
Update on screen resolution:
getHeight() and getWidth deprecated in API level 13 - HONEYCOMB_MR2; use getSize(Point) instead.
More info at:
http://developer.android.com/reference/android/view/Display.html
Try this to get Device Information.
String serviceType = Context.TELEPHONY_SERVICE;
TelephonyManager m_telephonyManager = (TelephonyManager) getActivity().getSystemService(serviceType);
String DeviceId, SubscriberId, NetworkOperator, OsVersion,SimOperatorName;
DeviceId = m_telephonyManager.getDeviceId();
SubscriberId = m_telephonyManager.getSubscriberId();
NetworkOperator = m_telephonyManager.getNetworkOperator();
OsVersion = m_telephonyManager.getDeviceSoftwareVersion();
SimOperatorName = m_telephonyManager.getSimOperatorName();
Show Output
Log.d("Device Information :", "\n DeviceId : " + DeviceId +
"\n SubscriberId : " + SubscriberId
+ "\n NetworkOperator : " + NetworkOperator +
"\n SoftwareVersion : " + OsVersion+
"\n SimOperatorName : " + SimOperatorName);
Try this
Log.i(TAG, "Device Info: " + System.getProperty("http.agent"));