Android UDID like IPhone? - iphone

Does Android have a UDID like IPhone? If yes, is there a way I can get it programatically?
Thanks
Chris

From the docs:
getDeviceId()
Returns the unique device ID, for
example, the IMEI for GSM and the MEID
for CDMA phones. Return null if device
ID is not available.

It's very easy to get the Android UDID - check out the following code:
public class DemoActivityActivity extends Activity {
/** Called when the activity is first created. */
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.main);
TelephonyManager tm = (TelephonyManager) this.getSystemService(Context.TELEPHONY_SERVICE);
Log.d(">>>>", "Android ID: " + Secure.getString(getContentResolver(), Secure.ANDROID_ID));
Log.d(">>>>", "Device ID : " + tm.getDeviceId());
}
For getting the Device ID you have to set following permission in AndroidManifest.xml:
<uses-permission android:name="android.permission.READ_PHONE_STATE"/>
For getting the Android ID you don't need to set any permission.

The Device ID used to only be available if you had signed up for Market by associating your phone with your Google account when you start, i.e. not available on the emulator. This seems to have changed with Android 2.2, where one is generated for the emulator as well. I don't believe it is associated with IMEI, ICC or any other phone-related token, but is rather a pseudo-unique token generated by Google web services to identify your phone.

I implemented a class to get IMEI / Wifi MAC address / deviceID, hope it useful for you ^^
public class DeviceInfo {
protected static String imeiNumber;
protected static String wifiMacAddress;
protected static String deviceID;
// This method must be called before other method
public static void init(Context context) throws Exception {
imeiNumber = getImei(context);
wifiMacAddress = getWifiMacAddress(context);
deviceID = getDeviceId(context);
}
public static String getDeviceInfo() {
return deviceID;
}
public static String getImei() {
return imeiNumber;
}
public static String getWifiMacAddress() {
return wifiMacAddress;
}
public static String getModel() {
return Build.MODEL;
}
public static String getOsVersion() {
return Build.VERSION.RELEASE;
}
protected static String getDeviceId(Context context) throws Exception {
String imei = getImei(context);
if (imei != null) return imei;
String tid = getWifiMacAddress(context);
return tid;
}
protected static String getWifiMacAddress(Context context) throws Exception {
WifiManager manager = (WifiManager) context
.getSystemService(Context.WIFI_SERVICE);
WifiInfo wifiInfo = manager.getConnectionInfo();
if (wifiInfo == null || wifiInfo.getMacAddress() == null)
return md5(UUID.randomUUID().toString());
else return wifiInfo.getMacAddress().replace(":", "").replace(".", "");
}
protected static String getImei(Context context) {
TelephonyManager m = (TelephonyManager) context
.getSystemService(Context.TELEPHONY_SERVICE);
String imei = m != null ? m.getDeviceId() : null;
return imei;
}
protected static String md5(String s) throws Exception {
MessageDigest md = MessageDigest.getInstance("MD5");
md.update(s.getBytes());
byte digest[] = md.digest();
StringBuffer result = new StringBuffer();
for (int i = 0; i < digest.length; i++) {
result.append(Integer.toHexString(0xFF & digest[i]));
}
return (result.toString());
}
}

Related

How to pass GPS (lat,lon etc) to Android services

I'm trying to build a background service which is able to log the data and save it into a SQLite database at a specific time interval without user consent.
So far:
I was able to start the services and toast current LastKnownLocation. This just to see if the variable is okay before I insert it to SQLite table.
However, if the GPS is not active the application will crash.
What's wrong with my code, and how to make it auto change when location changes?
public class SpycareServices extends Service {
/*Location Listener Declaration*/
PhoneInfo myPhone;
Util myFunction;
private LocationListener listener;
private LocationManager locationManager;
boolean gps_enabled = false;
boolean network_enabled = false;
Location net_loc = null, gps_loc = null, finalLoc = null;
public double longitude,latitude;
/*Declare SharedPref StartService*/
public SpycareServices(){
}
/*Declare constructor for location listener*/
public SpycareServices(Context context){
locationManager = (LocationManager) context.getSystemService(LOCATION_SERVICE);
}
#Nullable
#Override
public IBinder onBind(Intent intent) {
return null;
}
#Override
public void onCreate(){
/*Instantiate listener*/
locationManager = (LocationManager) getApplicationContext().getSystemService(Context.LOCATION_SERVICE);
//Check which provider active
gps_enabled = locationManager.isProviderEnabled(LocationManager.GPS_PROVIDER);
network_enabled = locationManager.isProviderEnabled(LocationManager.NETWORK_PROVIDER);
if(gps_enabled)
{
gps_loc = locationManager.getLastKnownLocation(LocationManager.GPS_PROVIDER);
}
if(network_enabled)
{
net_loc = locationManager.getLastKnownLocation(LocationManager.NETWORK_PROVIDER);
//net_loc = locationManager.requestLocationUpdates(LocationManager.NETWORK_PROVIDER,3000,0,listener);
}
/*If both gps and network has value, choose the better one*/
if (gps_loc != null && net_loc != null) {
//smaller the number more accurate result will
if (gps_loc.getAccuracy() > net_loc.getAccuracy()){
finalLoc = net_loc;
//
}
else{
finalLoc = gps_loc;
//locationManager.requestLocationUpdates(LocationManager.GPS_PROVIDER,3000,0,listener);
}
} else {
if (gps_loc != null) {
finalLoc = gps_loc;
} else if (net_loc != null) {
finalLoc = net_loc;
}
}
}
#Override
public int onStartCommand(Intent intent, int flags, int startId){
Toast.makeText(getApplicationContext(),"Services Has Been Started!",Toast.LENGTH_SHORT).show();
//Instance util to get timestamp
myFunction = new Util(this);
Toast.makeText(getApplicationContext(),"My time "+ myFunction.getTimestamp(this),Toast.LENGTH_SHORT).show();
//Instance Imei
myPhone = new PhoneInfo(this);
Toast.makeText(getApplicationContext(),"My Imei "+ myPhone.betaGetImei(this),Toast.LENGTH_SHORT).show();
Toast.makeText(getApplicationContext(),"My Location Provider is "+ finalLoc.getProvider(),Toast.LENGTH_SHORT).show();
Toast.makeText(getApplicationContext(),"My Longitude is "+ finalLoc.getLongitude(),Toast.LENGTH_SHORT).show();
Toast.makeText(getApplicationContext(),"My Latitude is "+ finalLoc.getLatitude(),Toast.LENGTH_SHORT).show();
return START_STICKY;
}
#Override
public void onDestroy(){
Toast.makeText(getApplicationContext(),"Services Has Been Destroyed!",Toast.LENGTH_SHORT).show();
//super.onDestroy();
//Prevent memory leaks by deregister listener when destroyed
if(locationManager!=null){
locationManager.removeUpdates(listener);
}
}

in signin the method gettext must be called from ui thread error

I'm trying to create a login for an application. However I have a problem.
This is my code:
in this code there is an error in the getText() in the android studio
actually m creating a login page with the help of the JSONParsing of web API, the login detail sync from the web api
public class Register extends Activity implements OnClickListener{
EditText user, pass, email, mobile;
private Button mRegister;
// Progress Dialog
private ProgressDialog pDialog;
// JSON parser class
JSONParser jsonParser = new JSONParser();
//si lo trabajan de manera local en xxx.xxx.x.x va su ip local
// private static final String REGISTER_URL = "http://xxx.xxx.x.x:1234/cas/register.php";
//testing on Emulator:
private static final String REGISTER_URL = "http://abc.demo.xxxxxxxxx.xxx/xxx";
//ids
private static final String TAG_SUCCESS = "success";
private static final String TAG_MESSAGE = "message";
#Override
protected void onCreate(Bundle savedInstanceState) {
// TODO Auto-generated method stub
super.onCreate(savedInstanceState);
setContentView(R.layout.register);
user = (EditText)findViewById(R.id.username);
pass = (EditText)findViewById(R.id.password);
email = (EditText)findViewById(R.id.Email);
mobile = (EditText)findViewById(R.id.etmobile);
mRegister = (Button)findViewById(R.id.register);
mRegister.setOnClickListener(this);
}
#Override
public void onClick(View v) {
// TODO Auto-generated method stub
new CreateUser().execute();
}
class CreateUser extends AsyncTask<String, String, String> {
#Override
protected void onPreExecute() {
super.onPreExecute();
pDialog = new ProgressDialog(Register.this);
pDialog.setMessage("Creating User...");
pDialog.setIndeterminate(false);
pDialog.setCancelable(true);
pDialog.show();
}
#Override
protected String doInBackground(String... args) {
// TODO Auto-generated method stub
// Check for success tag
int success;
String username = user.getText().toString();
String password = pass.getText().toString();
String mobile = mobile.getText().toString();
String email = email.getText().toString();
try {
// Building Parameters
List params = new ArrayList();
params.add(new BasicNameValuePair("username", username));
params.add(new BasicNameValuePair("password", password));
params.add(new BasicNameValuePair("email", email));
params.add(new BasicNameValuePair("mobile", mobile));
Log.d("request!", "starting");
//Posting user data to script
JSONObject json = jsonParser.makeHttpRequest(
REGISTER_URL, "POST", params);
// full json response
Log.d("Registering attempt", json.toString());
// json success element
success = json.getInt(TAG_SUCCESS);
if (success == 1) {
Log.d("User Created!", json.toString());
finish();
return json.getString(TAG_MESSAGE);
}else{
Log.d("Registering Failure!", json.getString(TAG_MESSAGE));
return json.getString(TAG_MESSAGE);
}
} catch (JSONException e) {
e.printStackTrace();
}
return null;
}
protected void onPostExecute(String file_url) {
// dismiss the dialog once product deleted
pDialog.dismiss();
if (file_url != null){
Toast.makeText(Register.this, file_url, Toast.LENGTH_LONG).show();
}
}
}
}
You will have to pass EditText values as args in the Async task.
String[] params = {user.getText().toString(),
pass.getText().toString(),
mobile.getText().toString(),
email.getText().toString()};
new CreateUser().execute(params);
You can play with the UI elements only in classes that run in UI thread. Activity or fragments etc.

How do i setup BroadcastReceiver to only display sms received from specific numbers?

I need help modifying a broadcastReceiver I wrote so that it only displays incoming sms message from numbers that I can specify. right now the following code displays ALL received sms, it would be nice if the app only displayed sms from 1 specific number. can anyone provide any specifics on how I could accomplish this?
code is as follows:
public class IncomingSms extends BroadcastReceiver {
final SmsManager sms = SmsManager.getDefault();
public void onReceive(Context context, Intent intent) {
// Retrieves a map of extended data from the intent.
final Bundle bundle = intent.getExtras();
try {
if (bundle != null) {
final Object[] pdusObj = (Object[]) bundle.get("pdus");
for (int i = 0; i < pdusObj.length; i++) {
SmsMessage currentMessage = SmsMessage.createFromPdu((byte[]) pdusObj[i]);
String phoneNumber = currentMessage.getDisplayOriginatingAddress();
String senderNum = phoneNumber;
String message = currentMessage.getDisplayMessageBody();
Log.i("SmsReceiver", "senderNum: "+ senderNum + "; message: " + message);
// Show Alert
int duration = Toast.LENGTH_LONG;
Toast toast = Toast.makeText(context,
"senderNum: "+ senderNum + ", message: " + message, duration);
toast.show();
} // end for loop
} // bundle is null
} catch (Exception e) {
Log.e("SmsReceiver", "Exception smsReceiver" +e);
}
}
}
thanks a bunch for any help guys.
Just put one if there :)
public class IncomingSms extends BroadcastReceiver {
private static final String MY_PHONE_NUMBER = "your number here";
final SmsManager sms = SmsManager.getDefault();
public void onReceive(Context context, Intent intent) {
// Retrieves a map of extended data from the intent.
final Bundle bundle = intent.getExtras();
try {
if (bundle != null) {
final Object[] pdusObj = (Object[]) bundle.get("pdus");
for (int i = 0; i < pdusObj.length; i++) {
SmsMessage currentMessage = SmsMessage.createFromPdu((byte[]) pdusObj[i]);
String phoneNumber = currentMessage.getDisplayOriginatingAddress();
if(!MY_PHONE_NUMBER.equals(phoneNumber)) {
return;
}
...

DataFlavor in JavaFX not recognized correctly

I'm experiencing a problem when D&D a custom object from Swing to JavaFX and I'm wondering if I'm doing something wrong or its probably a Java FX bug.
My Transferable has been defined as the following:
public class TransferableEmployee implements Transferable {
public static final DataFlavor EMPLOYEE_FLAVOR = new DataFlavor(Employee[].class, "Employee");
public static final DataFlavor DEFINITION_FLAVOR = new DataFlavor(PropertyDefinition[].class, "Definition");
private static final DataFlavor FFLAVORS [] = {EMPLOYEE_FLAVOR, DEFINITION_FLAVOR};
private Employee[] employees;
private PropertyDefinition[] propertyDefinitions;
public MintTransferableEmployee(Employee[] employees, PropertyDefinition[] propertyDefinitions) {
this.employees = employees != null ? employees.clone() : null;
this.propertyDefinitions = propertyDefinitions != null ? propertyDefinitions.clone() : null;
}
public DataFlavor[] getTransferDataFlavors() {
return FFLAVORS.clone();
}
public Object getTransferData(DataFlavor aFlavor) throws UnsupportedFlavorException {
Object returnObject = null;
if (aFlavor.equals(EMPLOYEE_FLAVOR)) {
returnObject = employees;
}
else if(aFlavor.equals(DEFINITION_FLAVOR)){
returnObject = propertyDefinitions;
}
else{
throw new UnsupportedFlavorException(aFlavor);
}
return returnObject;
}
public boolean isDataFlavorSupported(DataFlavor aFlavor) {
boolean lReturnValue = false;
for (int i=0, n=FFLAVORS.length; i<n; i++) {
if (aFlavor.equals(FFLAVORS[i])) {
lReturnValue = true;
break;
}
}
return lReturnValue;
}
}
I've created an imageView (FX Component) where I added the setOnDragOver just as the following:
employeePhotoImageView.setOnDragOver(new EventHandler<DragEvent>() {
#Override
public void handle(DragEvent event) {
System.out.println("dragOver");
event.getDragboard().getContentTypes();
event.getDragboard().getContent(DataFormat.lookupMimeType("application/x-java-serialized-object"));
}
});
The getContentTypes() returns a Map with [[application/x-java-serialized-object]], so now I try to get the Content, and this only returns the List of PropertyDefinition but no Employee at all (which in this case, is the one I need).
If I remove the data of the PropertyDefinition in the transferable, the employee is returned in the getContent(DataFormat) method.
For me, this means that JavaFX only works with 1 DataFlavor or somehow it is only returning the last flavor found in the Transferable.
Any clues on this?
Thanks in advanced...

File Upload in Android Webview - No File Chosen

I'm using the solution from Android WebView File Upload to have File Upload in Android Webview:
private WebView webView;
private ValueCallback<Uri> mUploadMessage;
private final static int FILECHOOSER_RESULTCODE = 1;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.main);
webView = (WebView) findViewById(R.id.webView);
webView.getSettings().setJavaScriptEnabled(true);
webView.setWebViewClient(new WebViewClient());
webView.setWebChromeClient(new WebChromeClient(){
public void openFileChooser(ValueCallback<Uri> uploadMsg) {
mUploadMessage = uploadMsg;
Intent i = new Intent(Intent.ACTION_GET_CONTENT);
i.addCategory(Intent.CATEGORY_OPENABLE);
i.setType("image/*");
Main.this.startActivityForResult(Intent.createChooser(i,"File Chooser"), FILECHOOSER_RESULTCODE);
}
public void openFileChooser( ValueCallback uploadMsg, String acceptType ) {
mUploadMessage = uploadMsg;
Intent i = new Intent(Intent.ACTION_GET_CONTENT);
i.addCategory(Intent.CATEGORY_OPENABLE);
i.setType("*/*");
Main.this.startActivityForResult(
Intent.createChooser(i, "File Browser"),
FILECHOOSER_RESULTCODE);
}
public void openFileChooser(ValueCallback<Uri> uploadMsg, String acceptType, String capture){
mUploadMessage = uploadMsg;
Intent i = new Intent(Intent.ACTION_GET_CONTENT);
i.addCategory(Intent.CATEGORY_OPENABLE);
i.setType("image/*");
Main.this.startActivityForResult( Intent.createChooser( i, "File Chooser" ), Main.FILECHOOSER_RESULTCODE );
}
});
webView.loadUrl( WEBSITE_URL );
}
#Override
protected void onActivityResult(int requestCode, int resultCode,
Intent intent) {
if(requestCode==FILECHOOSER_RESULTCODE){
if (null == mUploadMessage) return;
Uri result = intent == null || resultCode != RESULT_OK ? null
: intent.getData();
mUploadMessage.onReceiveValue(result);
mUploadMessage = null;
}
}
The filechooser display but after selecting photo, the input file still display No File Chosen. What I am missing on my code?
Thanks.