validate ip address using regex

The code snippet below will check if the passed string is a valid IP address or not .
An Internet Protocol address (IP address) is a numerical label assigned to each device participating in a computer network that uses the Internet Protocol for communication. Read more about IP address here. This snippet will validate IP version 4 addresses.

/**
 * validate IP address
 * @param String IP address to verify
 * @return Boolean result
 */
public static Boolean isIP(String input) {
    if (input!= null && !input.isEmpty()) {
        //Regex
        String regex = "^((25[0-5])|(2[0-4]\\d)|(1\\d\\d)|([1-9]\\d)|\\d)(\\.((25[0-5])|(2[0-4]\\d)|(1\\d\\d)|([1-9]\\d)|\\d)){3}$";
        //check if input matches the regex
        if (text.matches(regex)) {
            // valid ip
            return true;
        } else {
            // invalid ip
            return false;
        }
    }
    // invalid input
    return false;
}  

 

isOnline() check if android device has internet connectivity

What do you want?

  • If you just want to check for a connection to any network – not caring if internet is available – then most of the answers here (including the accepted), implementing isConnectedOrConnecting() will work well.
  • If you want to know if you have an internet connection (as the question title indicates) please read on

Ping for the main name servers

public boolean isOnline() {
    Runtime runtime = Runtime.getRuntime();
    try {
       Process ipProcess = runtime.exec("/system/bin/ping -c 1 8.8.8.8");
        int     exitValue = ipProcess.waitFor();
        return (exitValue == 0);
    } catch (IOException e)          { e.printStackTrace(); } 
      catch (InterruptedException e) { e.printStackTrace(); }
    return false;
}

That’s it! Yes that short, yes it is fast, no it does not need to run in background, no you don’t need root privileges.

Possible Questions

  • Is this really fast enough?Yes, very fast!
  • Is there really no reliable way to check if internet is available, other than testing something on the internet?Not as far as I know, but let me know, and I will edit my answer.
  • Couldn’t I just ping my own page, which I want to request anyways?Sure! You could even check both, if you want to differentiate between “internet connection available” and your own servers beeing reachable
  • What if the DNS is down?Google DNS (e.g. 8.8.8.8) is the largest public DNS service in the world. As of 2013 it serves 130 billion requests a day. Let ‘s just say, your app not responding would probably not be the talk of the day.
  • Which permissions are required?
    <uses-permission android:name="android.permission.INTERNET" />

    Just internet access – what surprise ^^ (BTW have you ever thought about, how some of the methods suggested here could even have a remote glue about the availability of internet, without this permission?)

 

Android: How to get MAC address of Ethernet port (not WiFi)

There are some android devices that have an ethernet (LAN) port for example Android STB, Android powered door-phone monitors, etc. The regular way of getting MAC address is as follows

WifiManager manager = (WifiManager) getSystemService(Context.WIFI_SERVICE);
WifiInfo info = manager.getConnectionInfo();
String address = info.getMacAddress();

Not to forget adding the following permission in the AndroidManifest.xml 

<uses-permission android:name="android.permission.ACCESS_WIFI_STATE"/>

The above method will give us the MAC address of WiFi. Assuming your Ethernet interface is eth0, to get the MAC address of Ethernet port we have to try opening and reading the file /sys/class/net/eth0/address. This can be Implemented as below.

public static String loadFileAsString(String filePath) throws java.io.IOException{
    StringBuffer data = new StringBuffer(1000);
    BufferedReader reader = new BufferedReader(new FileReader(filePath));
    char[] buf = new char[1024];
    int numRead=0;
    while((numRead=reader.read(buf)) != -1){
        String readData = String.valueOf(buf, 0, numRead);
        data.append(readData);
    }
    reader.close();
    return data.toString();
}

public String getMacAddress(){
    try {
        return loadFileAsString("/sys/class/net/eth0/address")
                .toUpperCase().substring(0, 17);
    } catch (IOException e) {
        e.printStackTrace();
        return null;
    }
}
 

Android snippet: validate a hex number input

This is how you can validate a hex input in android code. The regex it makes use of can be used in other languages as well.

Validation steps are :

  • check if the input is not null or zero length
  • check if the input has even numbers as hex numbers are always even
  • match the input with the validating regex.
public boolean validHexInput(String str) {

   if (str == null || str.length() == 0) {
      return false;
   }

   // length should be even number 
   // otherwise its not a valid hex 
   if (str.length() % 2 == 0) {
      String var1 = "(?i)[0-9a-f]+";
      return str.matches(var1);
 }

 return false;
}

 

Android: Call to getLayoutInflater() outside activity

Some times we need the inflater outside activities in android . To get access to the inflator we may use the following code snippet. You can use this outside activities – all you need is to provide a Context:

LayoutInflater inflater = LayoutInflater.from(context);

the from function also checks with assert that you actually get an inflater back and throws an error otherwise – which will be much easier to deal with then a null pointer exception somewhere in the code.

An Alternate way is shown below but I recommend to use the above one:

LayoutInflater inflater = (LayoutInflater) context.getSystemService( Context.LAYOUT_INFLATER_SERVICE );

Then to retrieve your different widgets, you inflate a layout:

View view = inflater.inflate( R.layout.myNewInflatedLayout, null );
Button myButton = (Button) view.findViewById( R.id.myButton );
 

Android: Updating the text of Toast message instantly

In my app,I wanted to show the number of taps to be made to accomplish a task, for this purpose i used Toast class , I used Toast.makeText to show the text. problem is that I couldn’t change the text or make it hide quickly if new text was to be shown. Android would queue all the makeText requests.

I wanted to have a solution to be able to change the text or be able to cancel the previous toast without waiting for it to finish. While Looking for solution I found this class called Boast by a StackOverFlow user Richard Le Mesurier. The Boast class accomplishes exactly what I needed.

The trick is to keep track of the last Toast that was shown, and to cancel that one.

What Richard Le Mesurier have done is to create a Toast wrapper, that contains a static reference to the last Toast displayed.

When I need to show a new one, I first cancel the static reference, before showing the new one (and saving it in the static).

Here’s full code of the Boast wrapper Richard Le Mesurier made – it mimics enough of the Toast methods for me to use it.

By default the Boast will cancel the previous one, so you don’t build up a queue of Toasts waiting to be displayed.

This should be a direct drop-in replacement for Toast in most use cases. for example

 mBoast.makeText(this,"your text",Duration).show();
import android.annotation.SuppressLint;
import android.content.Context;
import android.content.res.Resources;
import android.widget.Toast;

/**
 * {@link Toast} decorator allowing for easy cancellation of notifications. Use
 * this class if you want subsequent Toast notifications to overwrite current
 * ones. </p>
 *
 * By default, a current {@link Boast} notification will be cancelled by a
 * subsequent notification. This default behaviour can be changed by calling
 * certain methods like {@link #show(boolean)}.
 */
public class Boast
{
    /**
     * Keeps track of certain {@link Boast} notifications that may need to be cancelled.
     * This functionality is only offered by some of the methods in this class.
     */
    private volatile static Boast globalBoast = null;

    // ////////////////////////////////////////////////////////////////////////////////////////////////////////

    /**
     * Internal reference to the {@link Toast} object that will be displayed.
     */
    private Toast internalToast;

    // ////////////////////////////////////////////////////////////////////////////////////////////////////////

    /**
     * Private constructor creates a new {@link Boast} from a given
     * {@link Toast}.
     *
     * @throws NullPointerException
     *         if the parameter is <code>null</code>.
     */
    private Boast(Toast toast)
    {
        // null check
        if (toast == null)
        {
            throw new NullPointerException(
                    "Boast.Boast(Toast) requires a non-null parameter.");
        }

        internalToast = toast;
    }

    // ////////////////////////////////////////////////////////////////////////////////////////////////////////

    /**
     * Make a standard {@link Boast} that just contains a text view.
     *
     * @param context
     *        The context to use. Usually your {@link android.app.Application}
     *        or {@link android.app.Activity} object.
     * @param text
     *        The text to show. Can be formatted text.
     * @param duration
     *        How long to display the message. Either {@link #LENGTH_SHORT} or
     *        {@link #LENGTH_LONG}
     */
    @SuppressLint("ShowToast")
    public static Boast makeText(Context context, CharSequence text,
                                 int duration)
    {
        return new Boast(Toast.makeText(context, text, duration));
    }

    /**
     * Make a standard {@link Boast} that just contains a text view with the
     * text from a resource.
     *
     * @param context
     *        The context to use. Usually your {@link android.app.Application}
     *        or {@link android.app.Activity} object.
     * @param resId
     *        The resource id of the string resource to use. Can be formatted
     *        text.
     * @param duration
     *        How long to display the message. Either {@link #LENGTH_SHORT} or
     *        {@link #LENGTH_LONG}
     *
     * @throws Resources.NotFoundException
     *         if the resource can't be found.
     */
    @SuppressLint("ShowToast")
    public static Boast makeText(Context context, int resId, int duration)
            throws Resources.NotFoundException
    {
        return new Boast(Toast.makeText(context, resId, duration));
    }

    /**
     * Make a standard {@link Boast} that just contains a text view. Duration
     * defaults to {@link #LENGTH_SHORT}.
     *
     * @param context
     *        The context to use. Usually your {@link android.app.Application}
     *        or {@link android.app.Activity} object.
     * @param text
     *        The text to show. Can be formatted text.
     */
    @SuppressLint("ShowToast")
    public static Boast makeText(Context context, CharSequence text)
    {
        return new Boast(Toast.makeText(context, text, Toast.LENGTH_SHORT));
    }

    /**
     * Make a standard {@link Boast} that just contains a text view with the
     * text from a resource. Duration defaults to {@link #LENGTH_SHORT}.
     *
     * @param context
     *        The context to use. Usually your {@link android.app.Application}
     *        or {@link android.app.Activity} object.
     * @param resId
     *        The resource id of the string resource to use. Can be formatted
     *        text.
     *
     * @throws Resources.NotFoundException
     *         if the resource can't be found.
     */
    @SuppressLint("ShowToast")
    public static Boast makeText(Context context, int resId)
            throws Resources.NotFoundException
    {
        return new Boast(Toast.makeText(context, resId, Toast.LENGTH_SHORT));
    }

    // ////////////////////////////////////////////////////////////////////////////////////////////////////////

    /**
     * Show a standard {@link Boast} that just contains a text view.
     *
     * @param context
     *        The context to use. Usually your {@link android.app.Application}
     *        or {@link android.app.Activity} object.
     * @param text
     *        The text to show. Can be formatted text.
     * @param duration
     *        How long to display the message. Either {@link #LENGTH_SHORT} or
     *        {@link #LENGTH_LONG}
     */
    public static void showText(Context context, CharSequence text, int duration)
    {
        Boast.makeText(context, text, duration).show();
    }

    /**
     * Show a standard {@link Boast} that just contains a text view with the
     * text from a resource.
     *
     * @param context
     *        The context to use. Usually your {@link android.app.Application}
     *        or {@link android.app.Activity} object.
     * @param resId
     *        The resource id of the string resource to use. Can be formatted
     *        text.
     * @param duration
     *        How long to display the message. Either {@link #LENGTH_SHORT} or
     *        {@link #LENGTH_LONG}
     *
     * @throws Resources.NotFoundException
     *         if the resource can't be found.
     */
    public static void showText(Context context, int resId, int duration)
            throws Resources.NotFoundException
    {
        Boast.makeText(context, resId, duration).show();
    }

    /**
     * Show a standard {@link Boast} that just contains a text view. Duration
     * defaults to {@link #LENGTH_SHORT}.
     *
     * @param context
     *        The context to use. Usually your {@link android.app.Application}
     *        or {@link android.app.Activity} object.
     * @param text
     *        The text to show. Can be formatted text.
     */
    public static void showText(Context context, CharSequence text)
    {
        Boast.makeText(context, text, Toast.LENGTH_SHORT).show();
    }

    /**
     * Show a standard {@link Boast} that just contains a text view with the
     * text from a resource. Duration defaults to {@link #LENGTH_SHORT}.
     *
     * @param context
     *        The context to use. Usually your {@link android.app.Application}
     *        or {@link android.app.Activity} object.
     * @param resId
     *        The resource id of the string resource to use. Can be formatted
     *        text.
     *
     * @throws Resources.NotFoundException
     *         if the resource can't be found.
     */
    public static void showText(Context context, int resId)
            throws Resources.NotFoundException
    {
        Boast.makeText(context, resId, Toast.LENGTH_SHORT).show();
    }

    // ////////////////////////////////////////////////////////////////////////////////////////////////////////

    /**
     * Close the view if it's showing, or don't show it if it isn't showing yet.
     * You do not normally have to call this. Normally view will disappear on
     * its own after the appropriate duration.
     */
    public void cancel()
    {
        internalToast.cancel();
    }

    /**
     * Show the view for the specified duration. By default, this method cancels
     * any current notification to immediately display the new one. For
     * conventional {@link Toast#show()} queueing behaviour, use method
     * {@link #show(boolean)}.
     *
     * @see #show(boolean)
     */
    public void show()
    {
        show(true);
    }

    /**
     * Show the view for the specified duration. This method can be used to
     * cancel the current notification, or to queue up notifications.
     *
     * @param cancelCurrent
     *        <code>true</code> to cancel any current notification and replace
     *        it with this new one
     *
     * @see #show()
     */
    public void show(boolean cancelCurrent)
    {
        // cancel current
        if (cancelCurrent && (globalBoast != null))
        {
            globalBoast.cancel();
        }

        // save an instance of this current notification
        globalBoast = this;

        internalToast.show();
    }

}
 

MiFare Classic Detection on Android

Ever since Near Field Communication was embedded on mobile phones, loads of new ideas and business proposals made people very busy. So does the Android platform with its API’s supporting NFC. Nexus S looks like a state of the art – good starting point if one wants to get past the monotonic Nokia’s piece of the cake. I just want to share with you my experience on reading a MiFare Classic tag using the Nexus S..and the Android platform.

You need to have:

  • A MiFare Classic 1k Tag – ( hopefully you know the keys for its Blocks :=) )
  • Android SDK and IDE
  • NFC enabled Android  (Make sure if the Android version is 2.3.3 or above).

Some Basics about the card:

MiFare classic cards store data in its Sectors. In MiFare classic 1k card there are 16 of them. Each Sector contains 4 blocks. You can store 16 bytes in each block. Making about 1024 bytes of storage space..that explains the 1K part of the card. You can perform common tasks like reading, writing data on these blocks, authentification, navigating the card sectors by incrementing the blocks count. The first sector contains manufacturer’s details and a unique id for the card. This is a read only part.

Each sector on the Mifare card is secured by two 48-bit keys: A and B. The last block in the sector contains these keys, as well as a configuration that defines what each key can do with each block, i.e block 0 could be configured so that
key A could read and write, but if a reader authenticates with key B, the reader would only be able to read that block.

The rest of the memory storage can be read or written using keys A and B. Fresh, empty Mifare cards have all their sectors locked with a pair of default keys FFFFFFFFFFFF or 000000000000.

Default Keys from experiments

About the NFC part of Android

Since ever 2.3.3 Gingerbread – Android exposes an API to read a list of card technologies. To perform operations on a tag, there are three things to be noted.

  1.  The cards store data in a format,
  2.  Reading and Writing data is done using a protocol
  3.  Cards support a technology that defines what they are

hence reading and writing to these cards can be done only when the data is arranged in that format. MiFare 1K cards support the NDEF format. It also supports NFC – protocol on the communication level. Precisely – ISO 14443 – 3A specification in short NFCA and it uses the MiFare technology.

Now we need to let the Android know what kind of cards we would be using in our application. This is often defined in an XML file stored in the resource folder ( I have named the file – filter_nfc.xml and stored it in a folder named xml). This resource file contains for example,

android.nfc.tech.NfcA
 android.nfc.tech.MifareClassic

Here we have declared a tech-list. This list has to be used in the Manifest file. Imagine you would like to start an activity when a tag is touched. The Manifest file is the right place to let the launcher know what activity is to be called when a particular tag is touched.

In the Manifest file, you would have an element – activity. This would declare the name of the activity, a title for it and some metadata. Ideally you would let the system know that you want to start this activity when you touch a MiFare classic card. You can define you own filters for different activities for a variety of tag and protocol combinations.

You would then set the permissions on your Manifest file.

You can also do this in your onCreate method by using an NfcAdapter,

NfcAdapter mAdapter = NfcAdapter.getDefaultAdapter(this);

When a MiFare tag is discovered, the NFC stack would get the details of the tag and deliver it to a new Intent of this same activity. Hence to handle this, we would need an instance of the PendingIntent from the current activity.

PendingIntent mPendingIntent = PendingIntent.getActivity(this, 0,
 new Intent(this, getClass()).addFlags(Intent.FLAG_ACTIVITY_SINGLE_TOP), 0);

Then we could set up our filter which defines the data format and technology type.

IntentFilter ndef = new IntentFilter(NfcAdapter.ACTION_TECH_DISCOVERED);try {
 ndef.addDataType("*/*");
 } catch (MalformedMimeTypeException e) {
 throw new RuntimeException("fail", e);
 }

 mFilters = new IntentFilter[] {
 ndef,
 };// Setup a tech list for all NfcF tags

 mTechLists = new String[][] { new String[] { MifareClassic.class.getName() } };Intent intent = getIntent();

Finally when the pending intent calls the activity again, we like to read the tag. I have put all the steps in the method resolveIntent which would do only the reading part of the tag.

resolveIntent(intent);

Reading the tag

The method looks like

… 

 

strip non-ASCII characters from a string using RegEx (Regular expressions)

In case you have a string data which has some non ASCII characters and want to strip off all those non-ASCII characters the following regular expression will help you.

[^u0000-u007F]+

Explanation

  • [^u0000-u007F]+ match a single character not present in the list below
    Quantifier: + Between one and unlimited times, as many times as possible
  • u0000-u007F a single character in the range between the following two characters
    • u0000 the literal character u0000 (case sensitive)
    • u007F the literal character u007F (case sensitive)

^ is the not operator. It tells the regex to find everything that doesn’t match, instead of everything that does match.

The u####-u#### says which characters match.u0000-u007F is the equivilent of the first 255 characters in utf-8 or unicode, which are always the ASCII characters. So you match every non ASCII character (because of the not)

… 

 

make your android app boot at device start-up

If you want your app to start-up automatically when Android boots up you need to the following

#1: add the following to your android manifest file


<receiver android:enabled="true" android:name=".BootUpReceiver"
android:permission="android.permission.RECEIVE_BOOT_COMPLETED">
<intent-filter>
<action android:name="android.intent.action.BOOT_COMPLETED" />
<category android:name="android.intent.category.DEFAULT" />
</intent-filter>
</receiver>
<uses-permission android:name="android.permission.RECEIVE_BOOT_COMPLETED" />

view raw

gistfile1.xml

hosted with ❤ by GitHub

This will register for a boot complete receiver event and ask for its permission.

#2 Add a the following java class


public class BootUpReceiver extends BroadcastReceiver{
@Override
public void onReceive(Context context, Intent intent) {
Intent i = new Intent(context, MyActivity.class);
i.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
context.startActivity(i);
}
}

 

Converting UNIX timestamp to seconds, minutes, hours, days, weeks, month, years, decades ago

If you have UNIX time-stamps and you want convert it to show how may seconds, minutes, hours, weeks, months, years or decades ago it is from now you may use the following snippet of code. It accepts UNIX time-stamp in long format, In case you are getting UNIX time-stamps in String format you have to convert it to long. It will return a string with either seconds, minutes , hours , days, weeks, months, years , or decades ago. The code is written in java for an android app but can be ported to any language. Here is the code which is also available on github.


public static String caluculateTimeAgo(long timeStamp) {
long timeDiffernce;
long unixTime = System.currentTimeMillis() / 1000L; //get current time in seconds.
int j;
String[] periods = {"s", "m", "h", "d", "w", "m", "y", "d"};
// you may choose to write full time intervals like seconds, minutes, days and so on
double[] lengths = {60, 60, 24, 7, 4.35, 12, 10};
timeDiffernce = unixTime – timeStamp;
String tense = "ago";
for (j = 0; timeDiffernce >= lengths[j] && j < lengths.length – 1; j++) {
timeDiffernce /= lengths[j];
}
return timeDiffernce + periods[j] + " " + tense;
}