Connect to a Public wifi Network from Android Code? - android

I am developing an Android App that requires me to scan all available public wifi networks and connect to the one with highest signal strength. Can this be achieved is so HOW?
Right now my app just turns on wifi and connects to a saved network.

First have a look at the official help:
http://developer.android.com/reference/android/net/wifi/WifiManager.html
then look around and found something like that:
How can I get Android Wifi Scan Results into a list?
ScanResult gives the rssi (level)that can be used to select the appropriate network:
http://developer.android.com/reference/android/net/wifi/ScanResult.html
Here's a simple code to scan:
WifiManager wifi= (WifiManager) getSystemService(Context.WIFI_SERVICE);
wifi.startScan();
// get list of the results in object format ( like an array )
List<ScanResult> results = wifi.getScanResults();`
// loop that goes through list
for (ScanResult result : results) {
Toast.makeText(this, result.SSID + " " + result.level,
Toast.LENGTH_SHORT).show();
}
Remember you need permsissions in your manifest.xml:
<uses-permission android:name="android.permission.ACCESS_WIFI_STATE" />
UPDATE:
To create a network by SSID I use the following:
private boolean addNetworkAndActivate(ScanResult scanResult) {
WifiConfiguration wc = null;
List<WifiConfiguration> configs = wifiManager.getConfiguredNetworks();
for (WifiConfiguration wifiConfiguration : configs) {
try {
if (wifiConfiguration.SSID.equals("\"" + scanResult.SSID + "\"")) {
wc = wifiConfiguration;
break;
}
} catch (Exception e) {
}
}
// not configured, create new
if (wc == null) {
wc = new WifiConfiguration();
ConfigurationSecuritiesV8 conf = new ConfigurationSecuritiesV8();
conf.setupSecurity(wc, conf.getScanResultSecurity(scanResult), "7ej8e4jka9");
wc.SSID = "\"" + scanResult.SSID + "\"";
int res = wifiManager.addNetwork(wc);
if (res == -1)
return false;
if (!wifiManager.saveConfiguration())
return false;
}
boolean active = wifiManager.enableNetwork(wc.networkId, true);
return active;
}
Classes:
public class ConfigurationSecuritiesV8 extends ConfigurationSecurities {
static final int SECURITY_NONE = 0;
static final int SECURITY_WEP = 1;
static final int SECURITY_PSK = 2;
static final int SECURITY_EAP = 3;
enum PskType {
UNKNOWN, WPA, WPA2, WPA_WPA2
}
private static final String TAG = "ConfigurationSecuritiesV14";
private static int getSecurity(WifiConfiguration config) {
if (config.allowedKeyManagement.get(KeyMgmt.WPA_PSK)) {
return SECURITY_PSK;
}
if (config.allowedKeyManagement.get(KeyMgmt.WPA_EAP) || config.allowedKeyManagement.get(KeyMgmt.IEEE8021X)) {
return SECURITY_EAP;
}
return (config.wepKeys[0] != null) ? SECURITY_WEP : SECURITY_NONE;
}
private static int getSecurity(ScanResult result) {
if (result.capabilities.contains("WEP")) {
return SECURITY_WEP;
} else if (result.capabilities.contains("PSK")) {
return SECURITY_PSK;
} else if (result.capabilities.contains("EAP")) {
return SECURITY_EAP;
}
return SECURITY_NONE;
}
#Override
public String getWifiConfigurationSecurity(WifiConfiguration wifiConfig) {
return String.valueOf(getSecurity(wifiConfig));
}
#Override
public String getScanResultSecurity(ScanResult scanResult) {
return String.valueOf(getSecurity(scanResult));
}
#Override
public void setupSecurity(WifiConfiguration config, String security, String password) {
config.allowedAuthAlgorithms.clear();
config.allowedGroupCiphers.clear();
config.allowedKeyManagement.clear();
config.allowedPairwiseCiphers.clear();
config.allowedProtocols.clear();
final int sec = security == null ? SECURITY_NONE : Integer.valueOf(security);
final int passwordLen = password == null ? 0 : password.length();
switch (sec) {
case SECURITY_NONE:
config.allowedKeyManagement.set(KeyMgmt.NONE);
break;
case SECURITY_WEP:
config.allowedKeyManagement.set(KeyMgmt.NONE);
config.allowedAuthAlgorithms.set(AuthAlgorithm.OPEN);
config.allowedAuthAlgorithms.set(AuthAlgorithm.SHARED);
if (passwordLen != 0) {
// WEP-40, WEP-104, and 256-bit WEP (WEP-232?)
if ((passwordLen == 10 || passwordLen == 26 || passwordLen == 58) && password.matches("[0-9A-Fa-f]*")) {
config.wepKeys[0] = password;
} else {
config.wepKeys[0] = '"' + password + '"';
}
}
break;
case SECURITY_PSK:
config.allowedKeyManagement.set(KeyMgmt.WPA_PSK);
if (passwordLen != 0) {
if (password.matches("[0-9A-Fa-f]{64}")) {
config.preSharedKey = password;
} else {
config.preSharedKey = '"' + password + '"';
}
}
break;
case SECURITY_EAP:
config.allowedKeyManagement.set(KeyMgmt.WPA_EAP);
config.allowedKeyManagement.set(KeyMgmt.IEEE8021X);
// config.eap.setValue((String)
// mEapMethodSpinner.getSelectedItem());
//
// config.phase2.setValue((mPhase2Spinner.getSelectedItemPosition()
// == 0) ? "" :
// "auth=" + mPhase2Spinner.getSelectedItem());
// config.ca_cert.setValue((mEapCaCertSpinner.getSelectedItemPosition()
// == 0) ? "" :
// KEYSTORE_SPACE + Credentials.CA_CERTIFICATE +
// (String) mEapCaCertSpinner.getSelectedItem());
// config.client_cert.setValue((mEapUserCertSpinner.getSelectedItemPosition()
// == 0) ?
// "" : KEYSTORE_SPACE + Credentials.USER_CERTIFICATE +
// (String) mEapUserCertSpinner.getSelectedItem());
// config.private_key.setValue((mEapUserCertSpinner.getSelectedItemPosition()
// == 0) ?
// "" : KEYSTORE_SPACE + Credentials.USER_PRIVATE_KEY +
// (String) mEapUserCertSpinner.getSelectedItem());
// config.identity.setValue((mEapIdentityView.length() == 0) ? "" :
// mEapIdentityView.getText().toString());
// config.anonymous_identity.setValue((mEapAnonymousView.length() ==
// 0) ? "" :
// mEapAnonymousView.getText().toString());
// if (mPasswordView.length() != 0) {
// config.password.setValue(mPasswordView.getText().toString());
// }
break;
default:
LogBridge.d(TAG, "Invalid security type: " + sec);
}
// config.proxySettings = mProxySettings;
// config.ipAssignment = mIpAssignment;
// config.linkProperties = new LinkProperties(mLinkProperties);
}
private static PskType getPskType(ScanResult result) {
boolean wpa = result.capabilities.contains("WPA-PSK");
boolean wpa2 = result.capabilities.contains("WPA2-PSK");
if (wpa2 && wpa) {
return PskType.WPA_WPA2;
} else if (wpa2) {
return PskType.WPA2;
} else if (wpa) {
return PskType.WPA;
} else {
LogBridge.d(TAG, "Received abnormal flag string: " + result.capabilities);
return PskType.UNKNOWN;
}
}
#Override
public String getDisplaySecirityString(final ScanResult scanResult) {
final int security = getSecurity(scanResult);
if (security == SECURITY_PSK) {
switch (getPskType(scanResult)) {
case WPA:
return "WPA";
case WPA_WPA2:
case WPA2:
return "WPA2";
default:
return "?";
}
} else {
switch (security) {
case SECURITY_NONE:
return "OPEN";
case SECURITY_WEP:
return "WEP";
case SECURITY_EAP:
return "EAP";
}
}
return "?";
}
#Override
public boolean isOpenNetwork(String security) {
return String.valueOf(SECURITY_NONE).equals(security);
}
}
And
public abstract class ConfigurationSecurities {
/**
* #return The security of a given {#link WifiConfiguration}.
*/
public abstract String getWifiConfigurationSecurity(WifiConfiguration wifiConfig);
/**
* #return The security of a given {#link ScanResult}.
*/
public abstract String getScanResultSecurity(ScanResult scanResult);
/**
* Fill in the security fields of WifiConfiguration config.
*
* #param config
* The object to fill.
* #param security
* If is OPEN, password is ignored.
* #param password
* Password of the network if security is not OPEN.
*/
public abstract void setupSecurity(WifiConfiguration config, String security, final String password);
public abstract String getDisplaySecirityString(final ScanResult scanResult);
public abstract boolean isOpenNetwork(final String security);
public static ConfigurationSecurities newInstance() {
// if (Version.SDK < 8) {
// return new ConfigurationSecuritiesOld();
// } else {
return new ConfigurationSecuritiesV8();
// }
}
}

Related

How do you cloud save each level data. for unity Game Like Candy crush game

I am developing a puzzle game for Android using unity. So I want to save the score, time and stars earned for each level in the google play Cloud. But I am able to save it for one single level if I try to save it for more then 1 level. it overwrites the previous data. So how do I overcome this problem?
public class CloudSave : MonoBehaviour {
[SerializeField]
private Text message;
private int totalCoin = 20;
public int levelNumber;
public int starEarnedPerLevel;
#region Cloud_Save
private string GetSaveString() {
string data = "";
data += PlayerPrefs.GetInt("HighScore").ToString();
data += "|";
data += totalCoin.ToString();
data += "|";
data += levelNumber.ToString();
data += "|";
data += starEarnedPerLevel.ToString();
return data;
}
private void LoadSaveString(string save) {
string[] data = save.Split('|');
PlayerPrefs.SetInt("HighScore", int.Parse(data[0]));
totalCoin = int.Parse(data[1]);
levelNumber = int.Parse(data[2]);
starEarnedPerLevel = int.Parse(data[3]);
Debug.Log("LoadSaveString Function");
}
private bool isSaving = false;
public void OpenSave(bool saving) {
Debug.Log("Open Save");
if (Social.localUser.authenticated) {
isSaving = saving;
((PlayGamesPlatform)Social.Active).SavedGame
.OpenWithAutomaticConflictResolution(
"MyCloudFile",
DataSource.ReadCacheOrNetwork,
ConflictResolutionStrategy.UseLongestPlaytime, SavedGameOpen);
}
}
private void SavedGameOpen(SavedGameRequestStatus reqStatus, ISavedGameMetadata metadata) {
Debug.Log("SavedGameOpen");
if (reqStatus == SavedGameRequestStatus.Success) {
if (isSaving)// Writting
{
byte[] data = System.Text.ASCIIEncoding.ASCII.GetBytes(GetSaveString());
SavedGameMetadataUpdate update = new SavedGameMetadataUpdate.Builder().WithUpdatedDescription("Saved At :" + System.DateTime.Now.ToString()).Build();
((PlayGamesPlatform)Social.Active).SavedGame.CommitUpdate(metadata, update, data, SaveUpdate);
}
else // Reading or Loading
{
((PlayGamesPlatform)Social.Active).SavedGame.ReadBinaryData(metadata,SaveRead);
}
}
}
//success Save
private void SaveUpdate(SavedGameRequestStatus reqStatus, ISavedGameMetadata metadata) {
Debug.Log(reqStatus);
if (reqStatus == SavedGameRequestStatus.Success)
{
message.text = ("Data Saved successfully ");
}
else {
message.text = ("Data Saved failed " + reqStatus.ToString());
}
}
//Load
private void SaveRead(SavedGameRequestStatus reqStatus, byte[] data) {
if (reqStatus == SavedGameRequestStatus.Success) {
string savedData = System.Text.ASCIIEncoding.ASCII.GetString(data);
message.text = ("Data read successfully " + savedData);
LoadSaveString(savedData);
}
else
{
message.text = ("Data read Failed!" + reqStatus.ToString());
}
}
#endregion
}
Use JSON to keep the game data , splitting string is hard to maintain.
{
"currentLevel":"3",
"totalCoin":"20",
"levelData":[
{
"levelNum":1,
"starEarn":3,
"highScore":123456
},
{
"levelNum":2,
"starEarn":1,
"highScore":1234
}
]
}
//GameData.cs
[System.Serializable]
public class GameData {
public int currentLevel;
public int totalCoin;
private Dictionary<int, LevelData> levelDataList;
public GameData(){
//
// constructor
//
}
public string GetSaveString(){
string res = JsonUtility.ToJson (this);
res = res.Substring (0, res.Length - 1);
res = res + ",\"levelData\":[";
foreach (LevelData levelData in levelDataList.Values) {
res = res + JsonUtility.ToJson (levelData);
res = res + ",";
}
if(levelDataList.Count > 0)
res = res.Substring (0, res.Length - 1);
res = res + "]}";
return res;
}
}
//LevelData.cs
[System.Serializable]
public class LevelData {
public int levelNum;
public int starEarn;
public int highScore;
public LevelData(){
//
// constructor
//
}
}

getCurrentInputConnection is always null

I try to inject some keys in a text field with a InputMethodService.
In my Manifest everything seems alright.
Everytime when I call getCurrentInputConnection() I get null.
My class extends InputMethodService and I start the service.
Can anyone help me? Is there something else I need to do to get the currentInputConnection??
Here is the code:
Its from an open source project called WifiKeyboard
And I try to inject code with the function setText(String text)
package com.example.twolibs;
/**
* WiFi Keyboard - Remote Keyboard for Android.
* Copyright (C) 2011 Ivan Volosyuk
*
* This program is free software; you can redistribute it and/or
* modify it under the terms of the GNU General Public License
* as published by the Free Software Foundation; either version 2
* of the License, or (at your option) any later version.
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
* You should have received a copy of the GNU General Public License
* along with this program; if not, write to the Free Software
* Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA.
*/
import java.util.HashSet;
import android.content.ComponentName;
import android.content.Context;
import android.content.Intent;
import android.content.ServiceConnection;
import android.hardware.input.InputManager;
import android.inputmethodservice.InputMethodService;
import android.os.IBinder;
import android.os.PowerManager;
import android.os.RemoteException;
import android.text.InputType;
import android.util.Log;
import android.view.KeyEvent;
import android.view.inputmethod.EditorInfo;
import android.view.inputmethod.ExtractedText;
import android.view.inputmethod.ExtractedTextRequest;
import android.view.inputmethod.InputConnection;
import android.view.inputmethod.InputMethod;
public class WiFiInputMethod extends InputMethodService {
public static final int KEY_HOME = -1000;
public static final int KEY_END = -1001;
public static final int KEY_CONTROL = -1002;
public static final int KEY_DEL = -1003;
#Override
public void onStartInput(EditorInfo attribute, boolean restarting) {
super.onStartInput(attribute, restarting);
// boolean multiline = (attribute.inputType & InputType.TYPE_TEXT_FLAG_MULTI_LINE) != 0;
// Log.d("ivan", "onStartInput "
// + "actionId=" + attribute.actionId + " "
// + "id=" + attribute.fieldId + " "
// + "name=" + attribute.fieldName + " "
// + "opt=" + Integer.toHexString(attribute.imeOptions) + " "
// + "inputType=" + Integer.toHexString(attribute.inputType) + " "
// + "priv=" + attribute.privateImeOptions
// + "multiline=" + multiline);
try {
String text = getText();
} catch (NullPointerException e) {
}
}
ServiceConnection serviceConnection;
#Override
public void onDestroy() {
// Debug.d("WiFiInputMethod onDestroy()");
if (serviceConnection != null)
unbindService(serviceConnection);
serviceConnection = null;
super.onDestroy();
}
PowerManager.WakeLock wakeLock;
HashSet<Integer> pressedKeys = new HashSet<Integer>();
#Override
public void onCreate() {
super.onCreate();
PowerManager pm = (PowerManager) getSystemService(Context.POWER_SERVICE);
wakeLock = pm.newWakeLock(
PowerManager.SCREEN_BRIGHT_WAKE_LOCK | PowerManager.ON_AFTER_RELEASE, "wifikeyboard");
// Debug.d("WiFiInputMethod started");
serviceConnection = new ServiceConnection() {
public void onServiceConnected(ComponentName name, IBinder service) {
// Debug.d("WiFiInputMethod connected to HttpService.");
}
//#Override
public void onServiceDisconnected(ComponentName name) {
// Debug.d("WiFiInputMethod disconnected from HttpService.");
}
};
}
#Override
public boolean onEvaluateFullscreenMode() {
return false;
}
void receivedChar(int code) {
wakeLock.acquire();
wakeLock.release();
InputConnection conn = getCurrentInputConnection();
if (conn == null) {
// Debug.d("connection closed");
return;
}
if (pressedKeys.contains(KEY_CONTROL)) {
switch (code) {
case 'a':case 'A': selectAll(conn); return;
case 'x':case 'X': cut(conn); return;
case 'c':case 'C': copy(conn); return;
case 'v':case 'V': paste(conn); return;
}
}
String text = null;
if (code >= 0 && code <= 65535) {
text = new String(new char[] { (char) code } );
} else {
int HI_SURROGATE_START = 0xD800;
int LO_SURROGATE_START = 0xDC00;
int hi = ((code >> 10) & 0x3FF) - 0x040 | HI_SURROGATE_START;
int lo = LO_SURROGATE_START | (code & 0x3FF);
text = new String(new char[] { (char) hi, (char) lo } );
}
conn.commitText(text, 1);
}
#SuppressWarnings("unused")
void receivedKey(int code, boolean pressed) {
if (false) {
for (int key : pressedKeys) {
sendKey(key, false, false);
}
pressedKeys.clear();
resetModifiers();
return;
}
if (pressedKeys.contains(code) == pressed) {
if (pressed == false) return;
// ignore autorepeat on following keys
switch (code) {
case KeyEvent.KEYCODE_ALT_LEFT:
case KeyEvent.KEYCODE_SHIFT_LEFT:
case KeyEvent.KEYCODE_HOME:
case KeyEvent.KEYCODE_MENU: return;
}
}
if (pressed) {
pressedKeys.add(code);
System.out.println("one");
sendKey(code, pressed, false);
} else {
pressedKeys.remove(code);
sendKey(code, pressed, pressedKeys.isEmpty());
}
}
void resetModifiers() {
InputConnection conn = getCurrentInputConnection();
if (conn == null) {
return;
}
conn.clearMetaKeyStates(
KeyEvent.META_ALT_ON | KeyEvent.META_SHIFT_ON | KeyEvent.META_SYM_ON);
}
private long lastWake;
void sendKey(int code, boolean down, boolean resetModifiers) {
System.out.println("two");
/*
long time = System.currentTimeMillis();
if (time - lastWake > 5000) {
wakeLock.acquire();
wakeLock.release();
lastWake = time;
}
*/
InputConnection conn = getCurrentInputConnection();
System.out.println("three");
if (conn == null) {
System.out.println("kacke");
// Debug.d("connection closed");
return;
}
if (code < 0) {
if (down == false) return;
switch (code) {
case KEY_HOME: keyHome(conn); break;
case KEY_END: keyEnd(conn); break;
case KEY_DEL: keyDel(conn); break;
}
return;
}
if (pressedKeys.contains(KEY_CONTROL)) {
switch (code) {
case KeyEvent.KEYCODE_DPAD_LEFT:
if (!down) return;
wordLeft(conn);
return;
case KeyEvent.KEYCODE_DPAD_RIGHT:
if (!down) return;
wordRight(conn);
return;
case KeyEvent.KEYCODE_DEL:
if (!down) return;
deleteWordLeft(conn);
return;
case KeyEvent.KEYCODE_FORWARD_DEL:
deleteWordRight(conn);
return;
case KeyEvent.KEYCODE_DPAD_CENTER:
if (!down) return;
copy(conn);
return;
}
}
if (pressedKeys.contains(KeyEvent.KEYCODE_SHIFT_LEFT)) {
switch (code) {
case KeyEvent.KEYCODE_DPAD_CENTER:
if (!down) return;
paste(conn);
return;
}
}
if (code == KeyEvent.KEYCODE_ENTER) {
if (shouldSend()) {
if (!down) return;
Log.d("ivan", "sending submit action");
conn.performEditorAction(EditorInfo.IME_ACTION_SEND);
return;
}
}
// if (pressedKeys.contains(KEY_CONTROL)) {
// if (down == false) return;
// switch (code) {
// case KeyEvent.KEYCODE_A: selectAll(conn); break;
// case KeyEvent.KEYCODE_X: cut(conn); break;
// case KeyEvent.KEYCODE_C: copy(conn); break;
// case KeyEvent.KEYCODE_V: paste(conn); break;
// }
// return;
// }
System.out.println("four");
conn.sendKeyEvent(new KeyEvent(
android.os.SystemClock.uptimeMillis(),
android.os.SystemClock.uptimeMillis(),
down ? KeyEvent.ACTION_DOWN : KeyEvent.ACTION_UP,
code,
0,
(pressedKeys.contains(KeyEvent.KEYCODE_SHIFT_LEFT)
? KeyEvent.META_SHIFT_LEFT_ON : 0) +
(pressedKeys.contains(KEY_CONTROL)? KeyEvent.META_CTRL_ON : 0) +
(pressedKeys.contains(KeyEvent.KEYCODE_ALT_LEFT)
? KeyEvent.META_ALT_LEFT_ON : 0)
));
if (resetModifiers) {
conn.clearMetaKeyStates(
KeyEvent.META_ALT_ON | KeyEvent.META_SHIFT_ON | KeyEvent.META_SYM_ON);
}
}
private boolean shouldSend() {
if (pressedKeys.contains(KEY_CONTROL)) {
// Log.d("ivan", "Control pressed");
return true;
}
EditorInfo editorInfo = getCurrentInputEditorInfo();
if (editorInfo == null) {
// Log.d("ivan", "No editor info");
return false;
}
if ((editorInfo.inputType & InputType.TYPE_CLASS_TEXT) == 0) {
// Log.d("ivan", "Not text, sending enter");
return false;
}
if ((editorInfo.inputType & InputType.TYPE_TEXT_FLAG_MULTI_LINE) != 0) {
// Log.d("ivan", "Multi-line, sending ordinary enter");
return false;
}
int action = editorInfo.imeOptions & EditorInfo.IME_MASK_ACTION;
if (action == EditorInfo.IME_ACTION_NONE || action == EditorInfo.IME_ACTION_DONE) {
// Log.d("ivan", "No useful action, sending enter");
return false;
}
// Log.d("ivan", "Useful action to be performed");
return true;
}
private void keyDel(InputConnection conn) {
// if control key used -- delete word right
if (pressedKeys.contains(KEY_CONTROL)) {
deleteWordRight(conn);
return;
}
if (pressedKeys.contains(KeyEvent.KEYCODE_SHIFT_LEFT)) {
cut(conn);
return;
}
conn.deleteSurroundingText(0, 1);
conn.commitText("", 0);
}
private void paste(InputConnection conn) {
conn.performContextMenuAction(android.R.id.paste);
}
private void copy(InputConnection conn) {
conn.performContextMenuAction(android.R.id.copy);
}
private void cut(InputConnection conn) {
conn.performContextMenuAction(android.R.id.cut);
}
public void selectAll(InputConnection conn) {
ExtractedText text = conn.getExtractedText(req, 0);
try {
conn.setSelection(0, text.text.length());
} catch (NullPointerException e) {
// Potentially, text or text.text can be null
}
}
ExtractedTextRequest req = new ExtractedTextRequest();
{
req.hintMaxChars = 100000;
req.hintMaxLines = 10000;
}
private void deleteWordRight(InputConnection conn) {
ExtractedText text = conn.getExtractedText(req, 0);
if (text == null) return;
int end = text.selectionEnd;
String str = text.text.toString();
int len = str.length();
for (; end < len; end++) {
if (!Character.isSpace(str.charAt(end))) break;
}
for (; end < len; end++) {
if (Character.isSpace(str.charAt(end))) break;
}
conn.deleteSurroundingText(0, end - text.selectionEnd);
}
private void deleteWordLeft(InputConnection conn) {
// TODO: what is the correct word deleting policy?
// delete until next space? until next different character type?
ExtractedText text = conn.getExtractedText(req, 0);
if (text == null) return;
int end = text.selectionEnd - 1;
String str = text.text.toString();
for (; end >= 0; end--) {
if (!Character.isSpace(str.charAt(end))) break;
}
for (; end >= 0; end--) {
if (Character.isSpace(str.charAt(end))) break;
}
end++;
conn.deleteSurroundingText(text.selectionEnd - end, 0);
}
private void wordRight(InputConnection conn) {
boolean shift = pressedKeys.contains(KeyEvent.KEYCODE_SHIFT_LEFT);
ExtractedText text = conn.getExtractedText(req, 0);
if (text == null) return;
int end = text.selectionEnd;
String str = text.text.toString();
int len = str.length();
for (; end < len; end++) {
if (!Character.isSpace(str.charAt(end))) break;
}
for (; end < len; end++) {
if (Character.isSpace(str.charAt(end))) break;
}
int start = shift ? text.selectionStart : end;
Log.d("wifikeyboard", "start = " + start + " end = " + end);
conn.setSelection(start, end);
}
private void wordLeft(InputConnection conn) {
boolean shift = pressedKeys.contains(KeyEvent.KEYCODE_SHIFT_LEFT);
ExtractedText text = conn.getExtractedText(req, 0);
if (text == null) return;
int end = text.selectionEnd - 1;
String str = text.text.toString();
for (; end >= 0; end--) {
if (!Character.isSpace(str.charAt(end))) break;
}
for (; end >= 0; end--) {
if (Character.isSpace(str.charAt(end))) break;
}
end++;
int start = shift ? text.selectionStart : end;
Log.d("wifikeyboard", "start = " + start + " end = " + end);
conn.setSelection(start, end);
}
private void keyEnd(InputConnection conn) {
boolean control = pressedKeys.contains(KEY_CONTROL);
boolean shift = pressedKeys.contains(KeyEvent.KEYCODE_SHIFT_LEFT);
ExtractedText text = conn.getExtractedText(req, 0);
if (text == null) return;
int end;
if (control) {
end = text.text.length();
} else {
end = text.text.toString().indexOf('\n', text.selectionEnd);
if (end == -1) end = text.text.length();
}
int start = shift ? text.selectionStart : end;
Log.d("wifikeyboard", "start = " + start + " end = " + end);
conn.setSelection(start, end);
}
private void keyHome(InputConnection conn) {
boolean control = pressedKeys.contains(KEY_CONTROL);
boolean shift = pressedKeys.contains(KeyEvent.KEYCODE_SHIFT_LEFT);
ExtractedText text = conn.getExtractedText(req, 0);
if (text == null) return;
int end;
if (control) {
end = 0;
} else {
end = text.text.toString().lastIndexOf('\n', text.selectionEnd - 1);
end++;
}
int start = shift ? text.selectionStart : end;
Log.d("wifikeyboard", "start = " + start + " end = " + end);
conn.setSelection(start, end);
}
boolean setText(String text) {
// FIXME: need feedback if the input was lost
InputConnection conn = getCurrentInputConnection();
if (conn == null) {
// Debug.d("connection closed");
return false;
}
conn.commitText(text, text.length());
conn.beginBatchEdit();
// FIXME: hack
conn.deleteSurroundingText(100000, 100000);
conn.commitText(text, text.length());
conn.endBatchEdit();
return true;
}
String getText() {
String text = "";
try {
InputConnection conn = getCurrentInputConnection();
ExtractedTextRequest req = new ExtractedTextRequest();
req.hintMaxChars = 1000000;
req.hintMaxLines = 10000;
req.flags = 0;
req.token = 1;
text = conn.getExtractedText(req, 0).text.toString();
} catch (Throwable t) {
}
return text;
}
}
Thank you

Android: Loading large txt file(120k lines) from raw folder has delay the first time

I am using an AsyncTask to parse a very large txt file in my application and i noticed something weird: The first time this AsyncTask is called it takes very long time to finish(10-20 seconds) and the next times it's almost instantly.
So i am guessing i should somehow load the txt file into memory when the app starts and go from there.
Is there any ways to do this or is this the right thing to do in the first place?
Should some kind of cache implementation solve my problem?
Would it be a good idea to use the Android Cache system?
This is my AsyncTask for referece:
public class AnalyzeReviewsAsync extends AsyncTask<ArrayList<Place.Review>, String, String> {
private final Activity activity;
private ProgressDialog progressDialog;
private SinglePlaceCallbacks callbacks;
public AnalyzeReviewsAsync(Activity activity, SinglePlaceCallbacks callbacks) {
this.activity = activity;
this.callbacks = callbacks;
}
#Override
protected void onPreExecute() {
super.onPreExecute();
progressDialog = new ProgressDialog(activity);
progressDialog.setMessage("Analyzing...");
progressDialog.show();
}
#Override
protected String doInBackground(ArrayList<Place.Review>... params) {
try {
return parseReviews(params[0]);
} catch (IOException e) {
e.printStackTrace();
return null;
}
}
#Override
protected void onPostExecute(String s) {
super.onPostExecute(s);
progressDialog.dismiss();
String review = s == null ? "Not present" : s;
callbacks.setReviewsTxt(review);
}
private String parseReviews(ArrayList<Place.Review> reviewArrayList) throws IOException {
if(reviewArrayList!=null && reviewArrayList.size()>0) {
String reviewOutput = "";
for (Place.Review r : reviewArrayList) {
reviewOutput += "<p> <font color='" + getReviewColor(SentiWordNet.getInstance().analyzeReview(r.text)) + "'>";
reviewOutput += r.text;
reviewOutput += "</font></p>";
}
return reviewOutput;
}else{
return null;
}
}
private String getReviewColor(String review) {
if (review.equals("very positive")) {
//return Constants.getContext().getResources().getString(R.color.very_positive);
return "lime";
} else if (review.equals("positive")) {
//return Constants.getContext().getResources().getString(R.color.positive);
return "teal";
} else if (review.equals("negative")) {
//return Constants.getContext().getResources().getString(R.color.negative);
return "maroon";
} else if (review.equals("very negative")) {
//return Constants.getContext().getResources().getString(R.color.very_negative);
return "red";
} else {
//return Constants.getContext().getResources().getString(R.color.neutral);
return "grey";
}
}
}
Nothing fails the first time, so it is nothing different in code, here is my SentiWordNet class for referece:
public class SentiWordNet {
private Map<String, Double> dictionary;
private static SentiWordNet _instance = null;
private SentiWordNet(Context context) throws IOException {
// This is our main dictionary representation
dictionary = new HashMap<String, Double>();
// From String to list of doubles.
HashMap<String, HashMap<Integer, Double>> tempDictionary = new HashMap<String, HashMap<Integer, Double>>();
InputStream rawRes = context.getResources().openRawResource(R.raw.swn);
BufferedReader csv = null;
try {
csv = new BufferedReader(new InputStreamReader(rawRes, "UTF8"));
int lineNumber = 0;
String line;
while ((line = csv.readLine()) != null) {
lineNumber++;
// If it's a comment, skip this line.
if (!line.trim().startsWith("#")) {
// We use tab separation
String[] data = line.split("\t");
String wordTypeMarker = data[0];
// Example line:
// POS ID PosS NegS SynsetTerm#sensenumber Desc
// a 00009618 0.5 0.25 spartan#4 austere#3 ascetical#2
// ascetic#2 practicing great self-denial;...etc
// Is it a valid line? Otherwise, through exception.
if (data.length != 6) {
throw new IllegalArgumentException(
"Incorrect tabulation format in file, line: "
+ lineNumber
);
}
// Calculate synset score as score = PosS - NegS
Double synsetScore = Double.parseDouble(data[2])
- Double.parseDouble(data[3]);
// Get all Synset terms
String[] synTermsSplit = data[4].split(" ");
// Go through all terms of current synset.
for (String synTermSplit : synTermsSplit) {
// Get synterm and synterm rank
String[] synTermAndRank = synTermSplit.split("#");
String synTerm = synTermAndRank[0] + "#"
+ wordTypeMarker;
int synTermRank = Integer.parseInt(synTermAndRank[1]);
// What we get here is a map of the type:
// term -> {score of synset#1, score of synset#2...}
// Add map to term if it doesn't have one
if (!tempDictionary.containsKey(synTerm)) {
tempDictionary.put(synTerm,
new HashMap<Integer, Double>());
}
// Add synset link to synterm
tempDictionary.get(synTerm).put(synTermRank,
synsetScore);
}
}
}
// Go through all the terms.
for (Map.Entry<String, HashMap<Integer, Double>> entry : tempDictionary
.entrySet()) {
String word = entry.getKey();
Map<Integer, Double> synSetScoreMap = entry.getValue();
// Calculate weighted average. Weigh the synsets according to
// their rank.
// Score= 1/2*first + 1/3*second + 1/4*third ..... etc.
// Sum = 1/1 + 1/2 + 1/3 ...
double score = 0.0;
double sum = 0.0;
for (Map.Entry<Integer, Double> setScore : synSetScoreMap
.entrySet()) {
score += setScore.getValue() / (double) setScore.getKey();
sum += 1.0 / (double) setScore.getKey();
}
score /= sum;
dictionary.put(word, score);
}
} catch (Exception e) {
e.printStackTrace();
} finally {
if (csv != null) {
csv.close();
}
}
}
public static SentiWordNet getInstance() throws IOException {
if (_instance == null) {
_instance = new SentiWordNet(Constants.getContext());
}
return _instance;
}
public Double extract(String word) {
Double total = (double) 0;
if (dictionary.get(word + "#n") != null) {
total = dictionary.get(word + "#n") + total;
}
if (dictionary.get(word + "#a") != null) {
total = dictionary.get(word + "#a") + total;
}
if (dictionary.get(word + "#r") != null) {
total = dictionary.get(word + "#r") + total;
}
if (dictionary.get(word + "#v") != null) {
total = dictionary.get(word + "#v") + total;
}
return total;
}
public String analyzeReview(String review) {
String[] words = review.split("\\s+");
double totalScore = 0, averageScore;
for (String word : words) {
word = word.replaceAll("([^a-zA-Z\\s])", "");
if (_instance.extract(word) == null) {
continue;
}
Log.d("Total Score", String.valueOf(totalScore));
totalScore += _instance.extract(word);
}
averageScore = totalScore;
if (averageScore >= 0.75) {
return "very positive";
} else if (averageScore > 0.25 && averageScore < 0.5) {
return "positive";
} else if (averageScore >= 0.5) {
return "positive";
} else if (averageScore < 0 && averageScore >= -0.25) {
return "negative";
} else if (averageScore < -0.25 && averageScore >= -0.5) {
return "negative";
} else if (averageScore <= -0.75) {
return "very negative";
}
return "neutral";
}

substring check assistance with android

Can someone please help me with some code I have it is supposed to check that the string being passed is of 2 string and 3 ints which works fine, but if the 1 int is a zero it doesn't work
so if it was CM044 it won't work, CM450 will work can someone please help.
public boolean checkModule(String Module) {
if(Module.length() == 5){
boolean hasString = false;
boolean hasInt = false;
String letters = Module.substring(0, 2);
Pattern p = Pattern.compile("^[a-zA-Z]+$");
Matcher m = p.matcher(letters);
if (m.matches()) {
hasString = true;
}
String numbers=Module.substring(2,5);
try {
int num = Integer.parseInt(numbers);
String n = num + "";
if (num >0 && n.length() == 3)
hasInt = true;
} catch (Exception e) {
}
if (hasInt && hasString) {
return true;
}
}else{
return false;
}
return false;
}
Thanks
If you are going to use regular expressions you should definitely stick with them and not vary in and out.
package com.examples;
import java.util.regex.Matcher;
import java.util.regex.Pattern;
public class Main {
/**
* #param args
*/
public static void main(String[] args) {
new Main();
}
public Main() {
String[] testInputs = new String[] {"CM045", "CM450"};
for(String input : testInputs) {
System.out.println("The module " + input + " is " + (checkModule(input) ? "valid" : "invalid"));
}
}
public boolean checkModule(String Module){
Pattern p = Pattern.compile("[A-Z]{2}[0-9]{3}");
Matcher m = p.matcher(Module.toUpperCase());
return m.matches();
}
}
if the String is "045" the Integer value is 45 and so the length of num can't be 3
Use this
if(num>=0) {
hasInt = true;
}
and it has to work

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