Showing posts with label Android. Show all posts
Showing posts with label Android. Show all posts

Wednesday, June 15, 2016

Custom Font(s) for TextView in Android (Java)

Using customized fonts in Android OS is not supported by default. You have to essentially put your fonts in an assets folder in TTF or OTF format, then reference it in an extended widget of EditText/TextView or whichever widget you'd want to use.

First copy your ttf to your /assets/ directory in your project root.

The next thing you need to do is create a helper class, mine is called TextViewHelper.java ->

package com.yourdomain.yourapp.helper;

import android.content.Context;
import android.content.res.TypedArray;
import android.graphics.Typeface;
import android.util.AttributeSet;
import android.util.Log;
import android.widget.TextView;
import com.yourdomain.yourapp.R;

public class TextViewHelper extends TextView {
    private static final String TAG = "TextViewHelper";
    private static final String fontname = "SourceSansPro-Semibold.ttf";

    public TextViewHelper(Context context) {
        super(context);
    }

    public TextViewHelper(Context context, AttributeSet attrs) {
        super(context, attrs);
        setCustomFont(context, attrs);
    }

    public TextViewHelper(Context context, AttributeSet attrs, int defStyle) {
        super(context, attrs, defStyle);
        setCustomFont(context, attrs);
    }

    private void setCustomFont(Context ctx, AttributeSet attrs) {
        TypedArray a = ctx.obtainStyledAttributes(attrs, R.styleable.TextViewHelper);
        String customFont = a.getString(R.styleable.TextViewHelper_customFont);
        setCustomFont(ctx);
        a.recycle();
    }
    /* force custom font */
    public boolean setCustomFont(Context ctx) {
        Typeface tf = null;
        try {
        tf = Typeface.createFromAsset(ctx.getAssets(), fontname);  
        } catch (Exception e) {
            Log.e(TAG, "Could not get typeface: "+e.getMessage());
            return false;
        }

        setTypeface(tf);  
        return true;
    }

    public boolean setCustomFont(Context ctx, String asset) {
        Typeface tf = null;
        try {
        tf = Typeface.createFromAsset(ctx.getAssets(), asset);  
        } catch (Exception e) {
            Log.e(TAG, "Could not get typeface: "+e.getMessage());
            return false;
        }

        setTypeface(tf);  
        return true;
    }

}

Mine forces a custom font programmatically. Though there are many ways to skin this cat, this way I am assuming all fonts need to be the same, and I am using only one. You could theoretically expose and use numerous fonts instead of just one, but this simply does only one, SourceSansPro-Semibold.ttf.

The next and final step is you have to reference it from your layout.xml(s). See below sample:

Wherever you have <TextView /> tags referenced change it to:

            <com.yourdomain.yourapp.helper.TextViewHelper
                android:id="@+id/hm_vpn_txt"
                android:layout_width="wrap_content"
                android:layout_height="wrap_content"
                android:layout_centerVertical="true"
                android:layout_alignParentLeft="true"
                android:textColor="@color/test_color"
                android:textSize="16sp"
                android:text="@string/yourstring" />

And voila! You have custom fonts.

Thursday, May 12, 2016

Determine if device is an Amazon/Fire TV in Unity 3D

Often when you use the same apk for google play and amazon stores and you need to determine at run time whether your device is running Android OS or a Kindle on Fire OS. You may need to even further determine if the device is an Amazon Fire TV or Android TV app.

In Unity3D you can often use SystemInfo.deviceModel, and put it into if/then or case and set appropriate flags. Then you can implement google play, game circle, forward to the appropriate store for rating an app, etc.:

public static string getDevice() {
if (  SystemInfo.deviceModel.ToLower().Contains("aftb")) {
isAmazon = true;
return "Fire TV";
}
        if (  SystemInfo.deviceModel.ToLower().Contains("amazon")) {
isAmazon = true;
return SystemInfo.deviceModel;
}
isAmazon = false;
return SystemInfo.deviceModel;
}

Wednesday, April 22, 2015

Check for Palindromes (Java)

Palindromes are words that are the same forward and reverse. For example Boob is a palindrome since bo is the mirror of ob. This code checks to see if two strings are palindromes of each other, etc. This segment of code can be helpful when checking password quality. 



    private boolean isPalindrome () {
       if (compareIgnoreCase(newPassword, reverse(newPassword)))
            return true;
       else
            return false;
    }

    private boolean compareIgnoreCase(char[] string1, char[] string2) {
        if (string1 == null || string1.length == 0) return false;
        if (string2 == null || string2.length == 0) return false;
        if (string1.length != string2.length) return false;

        for (int i = 0; i < string1.length; i++) {
            if (Character.toLowerCase(string1[i]) !=         Character.toLowerCase(string2[i])) return false;
        }

        return true;
    }

    private char[] reverse(char[] password) {
        char[] r = new char[password.length];

        int x = password.length - 1;
        int y = 0;
        while (x >= 0)
            r[y++] = password[x--];

        return r;
    }

Friday, March 13, 2015

How to combine transparent Bitmaps into one Bitmap in Android (JAVA)

This process is pretty straight forward. You create a Bitmap Array[] then you combine all the individual parts together via this function.

First you declare your type:

Bitmap[] parts = new Bitmap[2];

Then you assign each element in the array:

parts[0] = Bitmap.createScaledBitmap(icon1, 120, 120, false);
parts[1] = Bitmap.createScaledBitmap(icon2, 120, 120, false);

Then you stack them together using stackBitmaps(parts):

               finalIcon = stackBitmaps(parts);

Here is the function you need to use:

private static Bitmap stackBitmaps (Bitmap[] parts) {
Bitmap mutableBitmap = parts[0].copy(Bitmap.Config.ARGB_8888, true);
Canvas comboImage = new Canvas(mutableBitmap);
for (int i = 1; i < parts.length; i++)
comboImage.drawBitmap(parts[i], 0f, 0f, null);
return mutableBitmap;
}

How to encode base64 Strings from Bitmaps in Android (JAVA)

This is a relatively easy process. See the function below. It takes a Bitmap variable and outputs a string. 

private static String endcodeBase64 (Bitmap ico) {
ByteArrayOutputStream stream = new ByteArrayOutputStream();
ico.compress(Bitmap.CompressFormat.PNG, 100, stream);
byte[] byteArray = stream.toByteArray();
return Base64.encodeToString(byteArray, Base64.DEFAULT);
}

Monday, April 21, 2014

Haversine Algorithm Implementation in Java

This is to calculate from two sets of points (Latitude, and Longitude) and distance based on the Earth's diameter/radius.

Here is the Haversine Formula followed by the java code. I've added Miles, KM, Meters, CM, Feet and Yards methods as well.

Haversine
formula:
a = sin²(Δφ/2) + cos(φ1).cos(φ2).sin²(Δλ/2)
c = 2.atan2(√a, √(1−a))
d = R.c
whereφ is latitude, λ is longitude, R is earth’s radius (mean radius = 6,371km)
 note that angles need to be in radians to pass to trig functions!

/**
 * This is the implementation Haversine Distance Algorithm between two places
 * @author amitapollo
 *  R = earth’s radius (mean radius = 6372.8km)
    Δlat = lat2 − lat1
    Δlong = long2 − long1
    a = sin²(Δlat/2) + cos(lat1).cos(lat2).sin²(Δlong/2)
    c = 2.atan2(√a, √(1−a))
    d = R.c * (distance converstion factor*)
 * 
 * * - km, mi, m, yds
 */

import java.lang.Math.*;

public class Haversine {
    /**
     * @param args
     * arg 1- latitude 1
     * arg 2 - longitude 1
     * arg 3 - latitude 2
     * arg 4 - longitude 2
     */

    public static final double RKilometers = 6372.8; // In kilometers
    public static final double RMiles = 10256.0; // In miles

    //returns kilometers between two sets of points (lat, lon)
    public static double haversineKilometers(double lat1, double lon1, double lat2, double lon2) {
        double dLat = Math.toRadians(lat2 - lat1);
        double dLon = Math.toRadians(lon2 - lon1);
        lat1 = Math.toRadians(lat1);
        lat2 = Math.toRadians(lat2);
 
        double a = Math.sin(dLat / 2) * Math.sin(dLat / 2) + Math.sin(dLon / 2) * Math.sin(dLon / 2) * Math.cos(lat1) * Math.cos(lat2);
        double c = 2 * Math.asin(Math.sqrt(a));
        return RKilometers * c;
    }

//returns meters between two sets of points (lat, lon)
    public static double haversineMeters(double lat1, double lon1, double lat2, double lon2) {
        double dLat = Math.toRadians(lat2 - lat1);
        double dLon = Math.toRadians(lon2 - lon1);
        lat1 = Math.toRadians(lat1);
        lat2 = Math.toRadians(lat2);
 
        double a = Math.sin(dLat / 2) * Math.sin(dLat / 2) + Math.sin(dLon / 2) * Math.sin(dLon / 2) * Math.cos(lat1) * Math.cos(lat2);
        double c = 2 * Math.asin(Math.sqrt(a));
        return RKilometers * c * 1000;
    }

    //returns centimeters between two sets of points (lat, lon)
    public static double haversineCentimeters(double lat1, double lon1, double lat2, double lon2) {
        double dLat = Math.toRadians(lat2 - lat1);
        double dLon = Math.toRadians(lon2 - lon1);
        lat1 = Math.toRadians(lat1);
        lat2 = Math.toRadians(lat2);
 
        double a = Math.sin(dLat / 2) * Math.sin(dLat / 2) + Math.sin(dLon / 2) * Math.sin(dLon / 2) * Math.cos(lat1) * Math.cos(lat2);
        double c = 2 * Math.asin(Math.sqrt(a));
        return RKilometers * c * 1000 * 100;
    }

    //returns miles between two sets of points (lat, lon)
    public static double haversineMiles(double lat1, double lon1, double lat2, double lon2) {
        double dLat = Math.toRadians(lat2 - lat1);
        double dLon = Math.toRadians(lon2 - lon1);
        lat1 = Math.toRadians(lat1);
        lat2 = Math.toRadians(lat2);
 
        double a = Math.sin(dLat / 2) * Math.sin(dLat / 2) + Math.sin(dLon / 2) * Math.sin(dLon / 2) * Math.cos(lat1) * Math.cos(lat2);
        double c = 2 * Math.asin(Math.sqrt(a));
        return RMiles * c;
    }

    //returns feet between two sets of points (lat, lon)
    public static double haversineFeet(double lat1, double lon1, double lat2, double lon2) {
        double dLat = Math.toRadians(lat2 - lat1);
        double dLon = Math.toRadians(lon2 - lon1);
        lat1 = Math.toRadians(lat1);
        lat2 = Math.toRadians(lat2);
 
        double a = Math.sin(dLat / 2) * Math.sin(dLat / 2) + Math.sin(dLon / 2) * Math.sin(dLon / 2) * Math.cos(lat1) * Math.cos(lat2);
        double c = 2 * Math.asin(Math.sqrt(a));
        return RMiles * c * 5280;
    }

    //returns inches between two sets of points (lat, lon)
    public static double haversineInches(double lat1, double lon1, double lat2, double lon2) {
        double dLat = Math.toRadians(lat2 - lat1);
        double dLon = Math.toRadians(lon2 - lon1);
        lat1 = Math.toRadians(lat1);
        lat2 = Math.toRadians(lat2);
 
        double a = Math.sin(dLat / 2) * Math.sin(dLat / 2) + Math.sin(dLon / 2) * Math.sin(dLon / 2) * Math.cos(lat1) * Math.cos(lat2);
        double c = 2 * Math.asin(Math.sqrt(a));
        return RMiles * c * 5280 * 12;
    }

    //returns yards between two sets of points (lat, lon)
    public static double haversineYards(double lat1, double lon1, double lat2, double lon2) {
        double dLat = Math.toRadians(lat2 - lat1);
        double dLon = Math.toRadians(lon2 - lon1);
        lat1 = Math.toRadians(lat1);
        lat2 = Math.toRadians(lat2);
 
        double a = Math.sin(dLat / 2) * Math.sin(dLat / 2) + Math.sin(dLon / 2) * Math.sin(dLon / 2) * Math.cos(lat1) * Math.cos(lat2);
        double c = 2 * Math.asin(Math.sqrt(a));
        return RMiles * c * 1760;
    }

    //CONVERTS value to Radians
    private static Double toRad(Double value) {
        return value * Math.PI / 180;
    }
}

Thursday, January 16, 2014

How to Save URL Image as JPEG and MMS on Android (java)

This takes a static image URL from the internet, saves it as a JPEG on your internal memory, then composes an MMS message and attached it. I've taken the URLs from Google Maps API, Mapquest, and Bing Maps API. Please take a look at the java code below. This of course has to be on an Async Task running on it's own thread (Network Exception on main thread):

 try {
        try
    {   
          String lat = String.valueOf(latitude);
          String lon = String.valueOf(longitude);
          URL url = new URL("http://dev.virtualearth.net/REST/v1/Imagery/Map/AerialWithLabels/" + lat 
      + "," + lon +"/18?mapSize=480,840&pp="+ lat +"," + lon + ";21;U&key=AsDTsMUE7Rr9oqizyP434eZR9L7UULMuuVZ4Qd-d0K3rqcBz");
   
          switch (API_Mode) {
          default
          url = new URL("http://dev.virtualearth.net/REST/v1/Imagery/Map/AerialWithLabels/" + lat 
      + "," + lon +"/18?mapSize=480,840&pp="+ lat +"," + lon + ";21;U&key=AsDTsMUE7Rr9oqizyPuGA8eGNgCUalK9TOTuVZ4Qd-d0K3rqcBz");
    break;  
          case GOOGLE
          url = new URL("http://maps.googleapis.com/maps/api/staticmap?center="
          lat +"," + lon + "&zoom=18&size=480x840&markers=color:red|color:red|label:U|"
          lat +"," + lon + "&sensor=false&maptype=hybrid");
    break;  
          case MAPQUEST
            url = new URL("http://www.mapquestapi.com/staticmap/v3/getmap?key=Fmjtd|luua29uanl,rw=o5-hwtsd&center="
                lat + ","+ lon +"&zoom=15&size=480,840&type=hyb&imagetype=jpg&pois=U,"
            lat + "," + lon +",-20,-20|mcenter," + lat + "," + lon + "");
          break;  
          }
      HttpURLConnection urlConnection = (HttpURLConnection) url.openConnection();
      urlConnection.setRequestMethod("GET");
      urlConnection.setDoOutput(true);                   
      urlConnection.connect();                  
      File SDCardRoot = Environment.getExternalStorageDirectory().getAbsoluteFile();
      SimpleDateFormat dateFormat = new SimpleDateFormat("yyyyMMdd'T'HHmmss");
      String timeStamp = dateFormat.format(new Date());
      String filename="currentLocation_" + timeStamp + ".jpeg";   
      Log.i("Local filename:",""+filename);
      File file = new File(SDCardRoot,filename);
      if(file.createNewFile())
      {
        file.createNewFile();
      }                 
      FileOutputStream fileOutput = new FileOutputStream(file);
      InputStream inputStream = urlConnection.getInputStream();
      int totalSize = urlConnection.getContentLength();
      int downloadedSize = 0;   
      byte[] buffer = new byte[2048];
      int bufferLength = 0;
      while ( (bufferLength = inputStream.read(buffer)) > 0 ) 
      {                 
        fileOutput.write(buffer, 0, bufferLength);                  
        downloadedSize += bufferLength;                 
        Log.i("Progress:","downloadedSize:"+downloadedSize+"totalSize:"+ totalSize) ;
      }             
      fileOutput.close();
      Intent sendIntent = new Intent(Intent.ACTION_SEND); 
      sendIntent.putExtra("address", Number);
            //sendIntent.setClassName("com.android.mms", "com.android.mms.ui.ComposeMessageActivity");
            sendIntent.putExtra("sms_body", "My Current Location: " + lat + "," + lon); 
            sendIntent.putExtra(Intent.EXTRA_STREAM, Uri.parse("file:///sdcard/" + filename));
            sendIntent.setType("image/jpg");
            startActivity(sendIntent);
   
    catch (MalformedURLException e) 
    {
      e.printStackTrace();
   
    catch (IOException e)
    {
      e.printStackTrace();
    }
            return true;
        } catch (Exception e) {
            e.printStackTrace();
            return false;

        }

Friday, September 20, 2013

Downloading a file remotely hosted on HTTP for Android in Java

This script downloads a file from a remote http location, and places the contents of the file on your device (external or internal directory downloads). The file will appear in your notifications and actually utilize the built-in download manager (as long as you have ANDROID HONEYCOMB BUILD).

public void downloadFile() {
Log.v(TAG, "Downloading File...");
String url = "http://www.apolloss.com/myFile.zip";
DownloadManager.Request request = new DownloadManager.Request(Uri.parse(url));
request.setDescription("This is the Zip file to download");
request.setTitle("update zip file");
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.HONEYCOMB) {
    request.allowScanningByMediaScanner();
    request.setNotificationVisibility(DownloadManager.Request.VISIBILITY_VISIBLE_NOTIFY_COMPLETED);
}
request.setDestinationInExternalPublicDir(Environment.DIRECTORY_DOWNLOADS, "myFile.zip");

// get download service and enqueue file
DownloadManager manager = (DownloadManager) getSystemService(Context.DOWNLOAD_SERVICE);
manager.enqueue(request);

}

Tuesday, March 12, 2013

Vibrate Handheld in Unity3D

This simple script tells the Game/App from Unity to shake/vibrate the Device if iOS/Android. If the device doesn't support vibrate, it'll simply do nothing!:

#if UNITY_IPHONE | UNITY_ANDROID

      Handheld.Vibrate();

#endif

Friday, January 18, 2013

Player Movement for Simple Air Hockey Game

This segment is for simple movement for a player in an Air Hockey Game on a 3D plane. You move mouse x and y and the y corresponds on the z plane.  This is from my Air Hockey 3D game available currently in the Android, iOS and Mac App Stores.

var other : GameObject ;
var dist : float;
var hitSound : AudioClip;
var spark : Transform;
var offset : Vector2 = Vector2.zero;
function spark1()
{
Instantiate (spark, transform.position, transform.rotation);
yield WaitForSeconds(0.5);
Destroy(GameObject.Find("Sparks(clone)"));
}
function Update () {
if (Time.timeScale != 0) {
other = GameObject.Find ("Sphere");
var Menu = GameObject.Find("Menu");
var script : menu = Menu.GetComponent(menu);
  var hit : RaycastHit;  
    var up = Vector3 ((transform.position.x - other.transform.position.x) * -1 , 0,
    (transform.position.z - other.transform.position.z) * -1 );
 
    if (Input.GetAxis("Mouse Y") > 0)     dist = 0.3 +  (Input.GetAxis("Mouse Y") / 8 ) + other.rigidbody.velocity.magnitude / 80;   else
    dist = 0.15 + other.rigidbody.velocity.magnitude / 80;
 
   Debug.DrawRay(transform.position, up , Color.green);
 
    if(Physics.Raycast(transform.position, up , hit, dist)){
       
      if(hit.collider.gameObject.name == "Sphere"){
      spark1();
      AudioSource.PlayClipAtPoint(hitSound, transform.position);
      other.rigidbody.AddForce(  up * (other.rigidbody.velocity.magnitude + 20 ),  ForceMode.Impulse);
      }
    }
if (script.singlePlayer) {
Screen.showCursor = false; #if UNITY_EDITOR
if (Input.mousePosition.x >  0  &&  Input.mousePosition.x < Screen.width)
transform.position.x = Input.mousePosition.x / (Screen.width / 2.4);
if (Input.mousePosition.y >  0 && Input.mousePosition.y < (Screen.height * 0.7)) {
if (transform.position.z < 2.194 && transform.position.z > 0) {
transform.position.z =  (Input.mousePosition.y * 0.7) / ((Screen.height * 0.7) / (3.18));
}
else if (transform.position.z >= 2.194) transform.position.z = 2.193;
 else if (transform.position.z <= 0) transform.position.z = 0.0001;
}
//Debug.Log(transform.position.z);
#elif UNITY_IPHONE || UNITY_ANDROID
if(Input.touchCount > 0 && Input.GetTouch(0).phase == TouchPhase.Moved) {
if (Input.mousePosition.x >  0  &&  Input.mousePosition.x < Screen.width)
transform.position.x = Input.mousePosition.x / (Screen.width / 2.4);
if (Input.mousePosition.y >  0 && Input.mousePosition.y < (Screen.height * 0.7)) {
if (transform.position.z < 2.194 && transform.position.z > 0) {
transform.position.z =  (Input.mousePosition.y * 0.7) / ((Screen.height * 0.7) / (3.18));
}
else if (transform.position.z >= 2.194) transform.position.z = 2.193;
 else if (transform.position.z <= 0) transform.position.z = 0.0001;
}
}
#endif
}
}
}

 



Generating "Always On Top" NSWindow in macOS across all detected displays

Also: Using UIKit & Cocoa Frameworks using Objective-C In m acOS or OS X , written in either Objective-C or Swift  Langues, you m...