Getting Mac Address on Marshmallow In Xamarin - android

I've been trying several things to get the MAC on Android 6.0 with no success ):
I already have this permissions:
<uses-permission android:name="android.permission.INTERNET" />
<uses-permission android:name="android.permission.ACCESS_COARSE_LOCATION" />
<uses-permission android:name="android.permission.ACCESS_FINE_LOCATION" />
<uses-permission android:name="android.permission.ACCESS_NETWORK_STATE" />
<uses-permission android:name="android.permission.ACCESS_WIFI_STATE" />
And this is my code:
public string GetMacAdress(Context context)
{
string mac = GetMacAddressLegacy(context);
if (mac == "02:00:00:00:00:00")
{
NetworkInterface[] interfaces = NetworkInterface.GetAllNetworkInterfaces();
foreach (NetworkInterface nif in interfaces)
{
if (!nif.Name.ToLower().Contains("wlan")) continue;
var physicalAddress = nif.GetPhysicalAddress();
byte[] macBytes = physicalAddress.GetAddressBytes();
if (macBytes == null) continue;
string macString = BitConverter.ToString(macBytes);
if (!string.IsNullOrWhiteSpace(macString)) mac = macString.Trim().ToUpper().Replace("-", ":");
}
}
return mac;
}
[Obsolete]
public string GetMacAddressLegacy(Context context)
{
string toReturn = "02:00:00:00:00:00";
if (DetectWifiNetwork())
{
isConected = true;
var telephonyMgr = (WifiManager)context.GetSystemService(Context.WifiService);
toReturn = telephonyMgr.ConnectionInfo.MacAddress;
if (!string.IsNullOrWhiteSpace(toReturn)) toReturn = toReturn.Trim().ToUpper();
}
else
{
isConected = false;
}
return toReturn;
}
But this line: byte[] macBytes = physicalAddress.GetAddressBytes(); returns an empty array.
Anyone could solve this?

Try to use this method
public static string getMacAddress()
{
string macAddress = string.Empty;
var all = Collections.List(Java.Net.NetworkInterface.NetworkInterfaces);
foreach (var interfaces in all)
{
if (!(interfaces as Java.Net.NetworkInterface).Name.Contains("wlan0")) continue;
var macBytes = (interfaces as
Java.Net.NetworkInterface).GetHardwareAddress();
if (macBytes == null) continue;
var sb = new System.Text.StringBuilder();
foreach (var b in macBytes)
{
string convertedByte = string.Empty;
convertedByte = (b & 0xFF).ToString("X2") + ":";
if(convertedByte.Length == 1)
{
convertedByte.Insert(0, "0");
}
sb.Append(convertedByte);
}
macAddress = sb.ToString().Remove(sb.Length - 1);
return macAddress;
}
return "02:00:00:00:00:00";
}

Try using this code:
public string GetMacAdress(Context context)
{
string mac = GetMacAddressLegacy(context);
if (mac == "02:00:00:00:00:00")
{
var interfaces = Java.Net.NetworkInterface.NetworkInterfaces;
foreach (var nif in interfaces)
{
if (!nif.Name.ToLower().Contains("wlan")) continue;
byte[] macBytes = nif.GetHardwareAddress();
string macString = BitConverter.ToString(macBytes);
if (!string.IsNullOrWhiteSpace(macString))
mac = macString.Trim().ToUpper().Replace("-", ":");
}
}
return mac;
}

Well using this is enough to make it work:
Permissions:
<uses-permission android:name="android.permission.ACCESS_WIFI_STATE" />
Code:
WifiManager wManager = (WifiManager)GetSystemService(Context.WifiService);
WifiInfo wInfo = wManager.ConnectionInfo;
button.Text = wInfo.MacAddress;
Are you testing on a real device or on a simulator?

Related

Issue in IP Address

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);

How do I build an app that scans QR codes and uses their data on Android? [closed]

Closed. This question needs to be more focused. It is not currently accepting answers.
Want to improve this question? Update the question so it focuses on one problem only by editing this post.
Closed 7 years ago.
Improve this question
Please be advised I am a total novice at Android development, and have only progressed as far as "Hello world".
I don't actually want to build a QR code scanner, I would rather use a third party component, but I need an app that will scan a QR code, display some data from the code, and send some data to a web service.
Please can someone give me a real beginner's outline on the process and structure U should use in my application. I am an experienced C# developer, so the actual Java coding won't be a problem, and I'm certainly not asking how to do that, just how to set up the basic app architecture and process flow, e.g. how to show a dialogue, contact a web service, and use a third party component.
What I need is to scan a QR code, extract some text code from it, send those codes to a web service.
ZXing is a pretty good library which you can integrate in your application.Refer this class CaptureActivity
first you need zxing library for creating QR Codes and an installed application for reading QR codes like BarcodeScanner and a Encoder class like:
import java.util.Collection;
import java.util.HashSet;
import java.util.Hashtable;
import android.graphics.Bitmap;
import android.os.Bundle;
import android.provider.ContactsContract;
import android.telephony.PhoneNumberUtils;
import com.google.zxing.BarcodeFormat;
import com.google.zxing.EncodeHintType;
import com.google.zxing.MultiFormatWriter;
import com.google.zxing.WriterException;
import com.google.zxing.common.ByteMatrix;
public final class QRCodeEncoder {
private static final int WHITE = 0xFFFFFFFF;
private static final int BLACK = 0xFF000000;
private int dimension = Integer.MIN_VALUE;
private String contents = null;
private String displayContents = null;
private String title = null;
private BarcodeFormat format = null;
private boolean encoded = false;
public QRCodeEncoder(String data, Bundle bundle, String type, String format, int dimension) {
this.dimension = dimension;
encoded = encodeContents(data, bundle, type, format);
}
public String getContents() {
return contents;
}
public String getDisplayContents() {
return displayContents;
}
public String getTitle() {
return title;
}
private boolean encodeContents(String data, Bundle bundle, String type, String formatString) {
// Default to QR_CODE if no format given.
format = null;
if (formatString != null) {
try {
format = BarcodeFormat.valueOf(formatString);
} catch (IllegalArgumentException iae) {
// Ignore it then
}
}
if (format == null || format == BarcodeFormat.QR_CODE) {
this.format = BarcodeFormat.QR_CODE;
encodeQRCodeContents(data, bundle, type);
} else if (data != null && data.length() > 0) {
contents = data;
displayContents = data;
title = "Text";
}
return contents != null && contents.length() > 0;
}
private void encodeQRCodeContents(String data, Bundle bundle, String type) {
if (type.equals(Contents.Type.TEXT)) {
if (data != null && data.length() > 0) {
contents = data;
displayContents = data;
title = "Text";
}
} else if (type.equals(Contents.Type.EMAIL)) {
data = trim(data);
if (data != null) {
contents = "mailto:" + data;
displayContents = data;
title = "E-Mail";
}
} else if (type.equals(Contents.Type.PHONE)) {
data = trim(data);
if (data != null) {
contents = "tel:" + data;
displayContents = PhoneNumberUtils.formatNumber(data);
title = "Phone";
}
} else if (type.equals(Contents.Type.SMS)) {
data = trim(data);
if (data != null) {
contents = "sms:" + data;
displayContents = PhoneNumberUtils.formatNumber(data);
title = "SMS";
}
} else if (type.equals(Contents.Type.CONTACT)) {
if (bundle != null) {
StringBuilder newContents = new StringBuilder(100);
StringBuilder newDisplayContents = new StringBuilder(100);
newContents.append("MECARD:");
String name = trim(bundle.getString(ContactsContract.Intents.Insert.NAME));
if (name != null) {
newContents.append("N:").append(escapeMECARD(name)).append(';');
newDisplayContents.append(name);
}
String address = trim(bundle.getString(ContactsContract.Intents.Insert.POSTAL));
if (address != null) {
newContents.append("ADR:").append(escapeMECARD(address)).append(';');
newDisplayContents.append('\n').append(address);
}
Collection<String> uniquePhones = new HashSet<String>(Contents.PHONE_KEYS.length);
for (int x = 0; x < Contents.PHONE_KEYS.length; x++) {
String phone = trim(bundle.getString(Contents.PHONE_KEYS[x]));
if (phone != null) {
uniquePhones.add(phone);
}
}
for (String phone : uniquePhones) {
newContents.append("TEL:").append(escapeMECARD(phone)).append(';');
newDisplayContents.append('\n').append(PhoneNumberUtils.formatNumber(phone));
}
Collection<String> uniqueEmails = new HashSet<String>(Contents.EMAIL_KEYS.length);
for (int x = 0; x < Contents.EMAIL_KEYS.length; x++) {
String email = trim(bundle.getString(Contents.EMAIL_KEYS[x]));
if (email != null) {
uniqueEmails.add(email);
}
}
for (String email : uniqueEmails) {
newContents.append("EMAIL:").append(escapeMECARD(email)).append(';');
newDisplayContents.append('\n').append(email);
}
String url = trim(bundle.getString(Contents.URL_KEY));
if (url != null) {
// escapeMECARD(url) -> wrong escape e.g. http\://zxing.google.com
newContents.append("URL:").append(url).append(';');
newDisplayContents.append('\n').append(url);
}
String note = trim(bundle.getString(Contents.NOTE_KEY));
if (note != null) {
newContents.append("NOTE:").append(escapeMECARD(note)).append(';');
newDisplayContents.append('\n').append(note);
}
// Make sure we've encoded at least one field.
if (newDisplayContents.length() > 0) {
newContents.append(';');
contents = newContents.toString();
displayContents = newDisplayContents.toString();
title = "Contact";
} else {
contents = null;
displayContents = null;
}
}
} else if (type.equals(Contents.Type.LOCATION)) {
if (bundle != null) {
// These must use Bundle.getFloat(), not getDouble(), it's part of the API.
float latitude = bundle.getFloat("LAT", Float.MAX_VALUE);
float longitude = bundle.getFloat("LONG", Float.MAX_VALUE);
if (latitude != Float.MAX_VALUE && longitude != Float.MAX_VALUE) {
contents = "geo:" + latitude + ',' + longitude;
displayContents = latitude + "," + longitude;
title = "Location";
}
}
}
}
public Bitmap encodeAsBitmap() throws WriterException {
if (!encoded) return null;
Hashtable hints = null;
String encoding = guessAppropriateEncoding(contents);
if (encoding != null) {
hints = new Hashtable();
hints.put(EncodeHintType.CHARACTER_SET, encoding);
}
MultiFormatWriter writer = new MultiFormatWriter();
ByteMatrix result =writer.encode(contents, format, dimension, dimension, hints);
int width = result.getWidth();
int height =result.getHeight();
int[] pixels = new int[width * height];
// All are 0, or black, by default
for (int y = 0; y < height; y++) {
int offset = y * width;
for (int x = 0; x < width; x++) {
if(result.get(x, y)== 0)
{
pixels[offset + x] = BLACK ;
}
else
pixels[offset + x] = WHITE ;
}
}
Bitmap bitmap = Bitmap.createBitmap(width, height, Bitmap.Config.ARGB_8888);
bitmap.setPixels(pixels, 0, width, 0, 0, width, height);
return bitmap;
}
private static String guessAppropriateEncoding(CharSequence contents) {
// Very crude at the moment
for (int i = 0; i < contents.length(); i++) {
if (contents.charAt(i) > 0xFF) { return "UTF-8"; }
}
return null;
}
private static String trim(String s) {
if (s == null) { return null; }
String result = s.trim();
return result.length() == 0 ? null : result;
}
private static String escapeMECARD(String input) {
if (input == null || (input.indexOf(':') < 0 && input.indexOf(';') < 0)) { return input; }
int length = input.length();
StringBuilder result = new StringBuilder(length);
for (int i = 0; i < length; i++) {
char c = input.charAt(i);
if (c == ':' || c == ';') {
result.append('\\');
}
result.append(c);
}
return result.toString();
}
}
hope this help you:)
You can also consider using manateework sdk which is very fast, cost effective. I has SDK available for mobile applications which supports different platform ie. iOS, Android etc and code symbology. Pl. refer to https://manateeworks.com/ for more details on this sdk

Haxe, OpenFL android debug giving error in for cpp

I'm developing an app in FlashDevelop, using Haxe and OpenFl
When I test my app in flash target, it works fine. But when I compile for android, it comes up with this error during the compilation:
./src/ReaderView2.cpp: In member function 'virtual Void ReaderView2_obj::setZoom()':
./src/ReaderView2.cpp:653: error: base operand of '->' has non-pointer type 'String'
Build halted with errors (haxelib.exe).
...Which is obviously something to do with cpp, which I'm not really an expert.
Does any body know what the error means?
Here's the setZooom function: (the whole file is quite large)
public function setZoom()
{
hideOptions();
while (numChildren > 0)
{
Main.remove(getChildAt(0));
}
if (image != null) if (image.parent != null) image.parent.removeChild(image);
images = new Array();
field = new TextField();
var fieldFont = Assets.getFont("fonts/Kreon-Regular.ttf");
var format:TextFormat = new TextFormat(fieldFont.fontName, currentZoom, 0x4F4F4F);
format.align = TextFormatAlign.LEFT;
field.defaultTextFormat = format;
field.embedFonts = true;
field.text = fullText;
field.selectable = false;
field.wordWrap = true;
field.border = false;
field.autoSize = TextFieldAutoSize.LEFT;
field.width = displayWidth;
//field.x = 0;
//split string into words
var allParas:Array<String> = fullText.split("\r\n");
var words:Array<String>;
var fields:Array<TextField> = new Array();
var tempField:TextField = null;
var contentHeight:Float = displayHeight;
var wordI:Int;
var paraI:Int = 0;
var tempArr2:Array<String>;
while (paraI < allParas.length)
{
if (false) //check img tag
{
}
else //if para is words
{
wordI = 0;
words = allParas[paraI].split(" ");
while (wordI < words.length)
{
if (tempField == null || tempField.textHeight > contentHeight)
{
if (tempField != null) {
wordI--;
tempArr2 = tempField.text.toString().split(" ");
for (i in 0... tempArr2.length)
{
tempArr2.remove("");
}
tempArr2.pop();
tempField.text = tempArr2.join(" ");
}
tempField = new TextField();
tempField.defaultTextFormat = field.getTextFormat();
tempField.embedFonts = true;
tempField.text = "";
tempField.border = false;
tempField.selectable = false;
tempField.wordWrap = true;
tempField.autoSize = TextFieldAutoSize.LEFT;
tempField.width = displayWidth-2;
tempField.x = 0;
fields.push(tempField);
}
else
{
tempField.appendText(words[wordI] + (wordI == words.length - 1? "\n": " "));
wordI++;
}
}
}
paraI++;
}
var bd:BitmapData;
for (i in 0... fields.length)
{
bd = new BitmapData(Std.int(fields[i].width), Std.int(fields[i].height));
bd.draw(fields[i]);
images.push(new Bitmap(bd, PixelSnapping.AUTO, true));
}
//addChild(fields[0]);
images[0].x = 10;
addChild(images[0]);
currentPageInstance = images[0];
currentPage = 0;
drawScrollBar();
if (optionsBtn!=null)addChild(optionsBtn);
}
So apparently using the toString() funcion gives problems for a cpp target.

Android - decryption issues with AES encrypted string in QR code

I've built a QR code generator and a QR code scanner for passing data about phones and their users between phones (the phones are being loaned out so there will be a master phone with the scanner app and the rest with the generator app). The QR code generated is a JSON format string containing a persons name/number/imei of their phone but for security I have tried to encrypt the string before encoding to QR, but the scanned QR code throws up a 'pad block corrupted' error.
The JSON data encodes into QR/decodes from QR fine as plain text, and I checked the encryption/decryption before encoding to QR and the data encrypts/decrypts fine, so it's something to do with when the encrypted text is encoded into QR but I've no idea where to begin with it!
Does anyone know how i can sort the issue? Or if theres any QR friendly encryption methods?!!
I took the QRCodeEncoder straight from ZXings source and placed it into my activity:
/**QR ENCODER CLASS****************************************************/
public class QRCodeEncoder
{
private final String TAG = QRCodeEncoder.class.getSimpleName();
private static final int WHITE = 0xFFFFFFFF;
private static final int BLACK = 0xFF000000;
private final Activity activity;
private String contents;
private String displayContents;
private String title;
private BarcodeFormat format;
private final int dimension;
QRCodeEncoder(Activity activity, Intent intent, int dimension) {
this.activity = activity;
if (intent == null) {
throw new IllegalArgumentException("No valid data to encode. intent is null");
}
String action = intent.getAction();
if (action.equals(Intents.Encode.ACTION)) {
if (!encodeContentsFromZXingIntent(intent)) {
throw new IllegalArgumentException("No valid data to encode. Zxing intent returned false");
}
} else if (action.equals(Intent.ACTION_SEND)) {
if (!encodeContentsFromShareIntent(intent)) {
throw new IllegalArgumentException("No valid data to encode. Share Intent returned false");
}
}
this.dimension = dimension;
}
public String getContents() {
return contents;
}
public String getDisplayContents() {
return displayContents;
}
public String getTitle() {
return title;
}
// It would be nice if the string encoding lived in the core ZXing library,
// but we use platform specific code like PhoneNumberUtils, so it can't.
private boolean encodeContentsFromZXingIntent(Intent intent) {
// Default to QR_CODE if no format given.
String formatString = intent.getStringExtra(Intents.Encode.FORMAT);
try {
format = BarcodeFormat.valueOf(formatString);
} catch (IllegalArgumentException iae) {
// Ignore it then
format = null;
}
if (format == null || BarcodeFormat.QR_CODE.equals(format)) {
String type = intent.getStringExtra(Intents.Encode.TYPE);
if (type == null || type.length() == 0) {
return false;
}
this.format = BarcodeFormat.QR_CODE;
encodeQRCodeContents(intent, type);
} else {
String data = intent.getStringExtra(Intents.Encode.DATA);
if (data != null && data.length() > 0) {
contents = data;
displayContents = data;
title = "QR Encoder";
}
}
return contents != null && contents.length() > 0;
}
// Handles send intents from multitude of Android applications
private boolean encodeContentsFromShareIntent(Intent intent) {
// Check if this is a plain text encoding, or contact
if (intent.hasExtra(Intent.EXTRA_TEXT)) {
return encodeContentsFromShareIntentPlainText(intent);
}
// Attempt default sharing.
return encodeContentsFromShareIntentDefault(intent);
}
private boolean encodeContentsFromShareIntentPlainText(Intent intent) {
// Notice: Google Maps shares both URL and details in one text, bummer!
contents = intent.getStringExtra(Intent.EXTRA_TEXT);
Toast.makeText(getApplicationContext(),"contents read = "+contents,Toast.LENGTH_SHORT).show();
// We only support non-empty and non-blank texts.
// Trim text to avoid URL breaking.
if (contents == null) {
return false;
}
contents = contents.trim();
if (contents.length() == 0) {
return false;
}
// We only do QR code.
format = BarcodeFormat.QR_CODE;
if (intent.hasExtra(Intent.EXTRA_SUBJECT)) {
displayContents = intent.getStringExtra(Intent.EXTRA_SUBJECT);
} else if (intent.hasExtra(Intent.EXTRA_TITLE)) {
displayContents = intent.getStringExtra(Intent.EXTRA_TITLE);
} else {
displayContents = contents;
}
title = "QR Encoder";
return true;
}
// Handles send intents from the Contacts app, retrieving a contact as a VCARD.
// Note: Does not work on HTC devices due to broken custom Contacts application.
private boolean encodeContentsFromShareIntentDefault(Intent intent) {
format = BarcodeFormat.QR_CODE;
try {
Uri uri = (Uri)intent.getExtras().getParcelable(Intent.EXTRA_STREAM);
InputStream stream = activity.getContentResolver().openInputStream(uri);
int length = stream.available();
if (length <= 0) {
Log.w(TAG, "Content stream is empty");
return false;
}
byte[] vcard = new byte[length];
int bytesRead = stream.read(vcard, 0, length);
if (bytesRead < length) {
Log.w(TAG, "Unable to fully read available bytes from content stream");
return false;
}
String vcardString = new String(vcard, 0, bytesRead, "UTF-8");
Log.d(TAG, "Encoding share intent content:");
Log.d(TAG, vcardString);
Result result = new Result(vcardString, vcard, null, BarcodeFormat.QR_CODE);
ParsedResult parsedResult = ResultParser.parseResult(result);
if (!(parsedResult instanceof AddressBookParsedResult)) {
Log.d(TAG, "Result was not an address");
return false;
}
if (!encodeQRCodeContents((AddressBookParsedResult) parsedResult)) {
Log.d(TAG, "Unable to encode contents");
return false;
}
} catch (IOException e) {
Log.w(TAG, e);
return false;
} catch (NullPointerException e) {
Log.w(TAG, e);
// In case the uri was not found in the Intent.
return false;
}
return contents != null && contents.length() > 0;
}
private void encodeQRCodeContents(Intent intent, String type) {
if (type.equals(Contents.Type.TEXT)) {
String data = intent.getStringExtra(Intents.Encode.DATA);
if (data != null && data.length() > 0) {
contents = data;
displayContents = data;
title = "QR Encoder";
}
} else if (type.equals(Contents.Type.EMAIL)) {
String data = trim(intent.getStringExtra(Intents.Encode.DATA));
if (data != null) {
contents = "mailto:" + data;
displayContents = data;
title = "QR Encoder";
}
} else if (type.equals(Contents.Type.PHONE)) {
String data = trim(intent.getStringExtra(Intents.Encode.DATA));
if (data != null) {
contents = "tel:" + data;
displayContents = PhoneNumberUtils.formatNumber(data);
title = "QR Encoder";
}
} else if (type.equals(Contents.Type.SMS)) {
String data = trim(intent.getStringExtra(Intents.Encode.DATA));
if (data != null) {
contents = "sms:" + data;
displayContents = PhoneNumberUtils.formatNumber(data);
title = "QR Encoder";
}
} else if (type.equals(Contents.Type.CONTACT)) {
Bundle bundle = intent.getBundleExtra(Intents.Encode.DATA);
if (bundle != null) {
StringBuilder newContents = new StringBuilder(100);
StringBuilder newDisplayContents = new StringBuilder(100);
newContents.append("MECARD:");
String name = trim(bundle.getString(Contacts.Intents.Insert.NAME));
if (name != null) {
newContents.append("N:").append(escapeMECARD(name)).append(';');
newDisplayContents.append(name);
}
String address = trim(bundle.getString(Contacts.Intents.Insert.POSTAL));
if (address != null) {
newContents.append("ADR:").append(escapeMECARD(address)).append(';');
newDisplayContents.append('\n').append(address);
}
for (int x = 0; x < Contents.PHONE_KEYS.length; x++) {
String phone = trim(bundle.getString(Contents.PHONE_KEYS[x]));
if (phone != null) {
newContents.append("TEL:").append(escapeMECARD(phone)).append(';');
newDisplayContents.append('\n').append(PhoneNumberUtils.formatNumber(phone));
}
}
for (int x = 0; x < Contents.EMAIL_KEYS.length; x++) {
String email = trim(bundle.getString(Contents.EMAIL_KEYS[x]));
if (email != null) {
newContents.append("EMAIL:").append(escapeMECARD(email)).append(';');
newDisplayContents.append('\n').append(email);
}
}
// Make sure we've encoded at least one field.
if (newDisplayContents.length() > 0) {
newContents.append(';');
contents = newContents.toString();
displayContents = newDisplayContents.toString();
title = "QR Encoder";
} else {
contents = null;
displayContents = null;
}
}
} else if (type.equals(Contents.Type.LOCATION)) {
Bundle bundle = intent.getBundleExtra(Intents.Encode.DATA);
if (bundle != null) {
// These must use Bundle.getFloat(), not getDouble(), it's part of the API.
float latitude = bundle.getFloat("LAT", Float.MAX_VALUE);
float longitude = bundle.getFloat("LONG", Float.MAX_VALUE);
if (latitude != Float.MAX_VALUE && longitude != Float.MAX_VALUE) {
contents = "geo:" + latitude + ',' + longitude;
displayContents = latitude + "," + longitude;
title = "QR Encoder";
}
}
}
}
private boolean encodeQRCodeContents(AddressBookParsedResult contact) {
StringBuilder newContents = new StringBuilder(100);
StringBuilder newDisplayContents = new StringBuilder(100);
newContents.append("MECARD:");
String[] names = contact.getNames();
if (names != null && names.length > 0) {
String name = trim(names[0]);
if (name != null) {
newContents.append("N:").append(escapeMECARD(name)).append(';');
newDisplayContents.append(name);
}
}
String[] addresses = contact.getAddresses();
if (addresses != null) {
for (String address : addresses) {
address = trim(address);
if (address != null) {
newContents.append("ADR:").append(escapeMECARD(address)).append(';');
newDisplayContents.append('\n').append(address);
}
}
}
String[] phoneNumbers = contact.getPhoneNumbers();
if (phoneNumbers != null) {
for (String phone : phoneNumbers) {
phone = trim(phone);
if (phone != null) {
newContents.append("TEL:").append(escapeMECARD(phone)).append(';');
newDisplayContents.append('\n').append(PhoneNumberUtils.formatNumber(phone));
}
}
}
String[] emails = contact.getEmails();
if (emails != null) {
for (String email : emails) {
email = trim(email);
if (email != null) {
newContents.append("EMAIL:").append(escapeMECARD(email)).append(';');
newDisplayContents.append('\n').append(email);
}
}
}
String url = trim(contact.getURL());
if (url != null) {
newContents.append("URL:").append(escapeMECARD(url)).append(';');
newDisplayContents.append('\n').append(url);
}
// Make sure we've encoded at least one field.
if (newDisplayContents.length() > 0) {
newContents.append(';');
contents = newContents.toString();
displayContents = newDisplayContents.toString();
title = "QR Encoder";
return true;
} else {
contents = null;
displayContents = null;
return false;
}
}
Bitmap encodeAsBitmap() throws WriterException {
Hashtable<EncodeHintType,Object> hints = null;
String encoding = guessAppropriateEncoding(contents);
if (encoding != null) {
hints = new Hashtable<EncodeHintType,Object>(2);
hints.put(EncodeHintType.CHARACTER_SET, encoding);
}
MultiFormatWriter writer = new MultiFormatWriter();
BitMatrix result = writer.encode(contents, format, dimension, dimension, hints);
int width = result.getWidth();
int height = result.getHeight();
int[] pixels = new int[width * height];
// All are 0, or black, by default
for (int y = 0; y < height; y++) {
int offset = y * width;
for (int x = 0; x < width; x++) {
pixels[offset + x] = result.get(x, y) ? BLACK : WHITE;
}
}
Bitmap bitmap = Bitmap.createBitmap(width, height, Bitmap.Config.ARGB_8888);
bitmap.setPixels(pixels, 0, width, 0, 0, width, height);
return bitmap;
}
private String guessAppropriateEncoding(CharSequence contents) {
// Very crude at the moment
for (int i = 0; i < contents.length(); i++) {
if (contents.charAt(i) > 0xFF) {
return "UTF-8";
}
}
return null;
}
private String trim(String s) {
if (s == null) {
return null;
}
s = s.trim();
return s.length() == 0 ? null : s;
}
private String escapeMECARD(String input) {
if (input == null || (input.indexOf(':') < 0 && input.indexOf(';') < 0)) {
return input;
}
int length = input.length();
StringBuilder result = new StringBuilder(length);
for (int i = 0; i < length; i++) {
char c = input.charAt(i);
if (c == ':' || c == ';') {
result.append('\\');
}
result.append(c);
}
return result.toString();
}
}
And the encryption/decryption class from this website (unedited)
Here's a snippet of the onCreate() method in my activity:
QRCodeEncoder myQRCodeEncoder;
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.qr_view);
ImageView imageView = (ImageView)findViewById(R.id.qr_image);
extStorageDirectory = Environment.getExternalStorageDirectory().toString();
try
{
//JSON data is passed from another activity to this one
qrMessage = getIntent().getStringExtra("QR_JSON");
Intent encode = new Intent(Intents.Encode.ACTION);
encode.putExtra(Intents.Encode.TYPE, Contents.Type.TEXT);
encode.putExtra(Intents.Encode.FORMAT, "QR_CODE");
//This is the original plain text way that works:
//encode.putExtra(Intents.Encode.DATA, qrMessage);
//This is the encyption way
String encMessage = SimpleCrypto.encrypt("my s3cr3t k3y", qrMessage);
encode.putExtra(Intents.Encode.DATA,encMessage);
myQRCodeEncoder = new QRCodeEncoder(this, encode, 200);
}
catch(Exception e)
{
Toast.makeText(getApplicationContext(),"Could not encode:"+e.getMessage(),Toast.LENGTH_SHORT).show();
}
catch(Error e)
{
Toast.makeText(getApplicationContext(),"Could not encode:"+e.getMessage(),Toast.LENGTH_SHORT).show();
}
try {
Bitmap qrBitmap = myQRCodeEncoder.encodeAsBitmap();
imageView.setImageBitmap(qrBitmap);
} catch (Exception e) {
Toast.makeText(getApplicationContext(),"Could not set image:"+e.getMessage(),Toast.LENGTH_SHORT).show();
}
}
And here's the onActivityResult method from the scanner (I use ZXing's barcode scanner to retrieve the data)
public void onActivityResult(int requestCode, int resultCode, Intent intent) {
if (requestCode == 0) {
if (resultCode == RESULT_OK) {
String contents = intent.getStringExtra("SCAN_RESULT");//contents of the scan
String format = intent.getStringExtra("SCAN_RESULT_FORMAT");
// Handle successful scan
/* display the scanned persons info*/
try {
String decryptedcontents = SimpleCrypto.decrypt("my s3cr3t k3y",contents);
String result = getJSONFromScanData(decryptedcontents);
} catch (Exception e) {
// TODO Auto-generated catch block
Toast.makeText(this, "Scanned data could not be decrypted:"+e.getMessage(), Toast.LENGTH_SHORT).show();//says 'pad block corrupted' as the message
}
} else if (resultCode == RESULT_CANCELED) {
// Handle cancel
Toast.makeText(this, "Scan cancelled", Toast.LENGTH_SHORT).show();
}
}
}
EDIT: after some further investigation it seems that the encyption/decyption process seems to 'shave off' part of the data:
JSONObject example = new JSONObject("{\"user_firstname\":\"Ben\",\"user_lastname\":\" Ten\",\"user_login\":\"benten\",\"user_pass\":\"password\",\"user_email\":\"benten#domain.com\"}");
String mess = SimpleCrypto.encrypt("my s3cr3t k3y",example.toString());
String decrmess = SimpleCrypto.decrypt("my s3cr3t k3y",mess));
//decypts as:{"user_pass":"password","user_email":"benten#domain.com","user_login":"benten","user_lastname":"
as you can see only 96 characters are decrypted, theres no user_firstname or the users actual last name, the data is missing, but this number is inconsistent, I changed the user_email to "benbenten#domain.com" and the user_firstname to "benben" and 112 characters were decrypted...I am completely stumped
EDIT 2: Yngve Ã…dlandsvik has kindly pointed me in the right direction (many thanks again!) that the string length needed to be a multiple of 16, so I set the Cipher.getInstance in both the encrypt and decrypt methods to:
Cipher cipher = Cipher.getInstance("AES/ECB/NoPadding","BC");
and in my main activity set a loop to add 0's on the end of my string as custom padding before encrypting:
boolean carryOn = true;
while(carryOn)
{
int paddedLength = qrMessage.getBytes().length;
int checkMultiple16 = paddedLength%16;
if(checkMultiple16==0)
{
carryOn = false;
}
else
qrMessage+="0";
}
EDIT 3: It looks like QR encoding still screws with the encryption, I can't decrypt the scanned in data properly, looks like QR encoding does something with strings before it encodes to QR which seems to break the thing, guess I'll have to stick to unencrypted text in the QR...
I haven't read the code closely, but I assume this happens because AES only operates on blocks of 16 bytes at once. So my guess is you need to manually apply some form of reversible padding to your string before encryption so it becomes a multiple of 16, and then reverse the padding after decryption.
You could also change the Cipher.getInstance() strings in the crypto code so the encryption will support padding natively, though I don't know which padding types and cipher modes are available on Android.

How to detect system information like os or device type

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"));

Categories

Resources