2016-09-20

Android: Locating classes to import

I'm not a particular fan of Eclipse or Android Studio, and prefer using the command line tools for building android projects. Eclipse does have a nice feature though for easily adding import-lines with the context menu.

Well, with this simple bash-script android-finder, it's quite easy to locate classes needed to be imported:

#!/usr/bin/env bash
#
# Run:
# $ android-finder <class>
#
if [ $# -lt 1 ]; then
    echo "$0 <class>"
    exit 1;
fi

CLASS=$1
VERSION=24
CLASS_DIRS=$ANDROID_HOME/sources/android-$VERSION 

find $CLASS_DIRS -name "$CLASS.java" -type f | \
  sed -r "s/(^.*?\/android-$VERSION\/|\.java$)//g" | \
  sed 's/\//./g'

The java sources for android must be downloaded, otherwise they can't be searched. This is done in the Android SDK Manager. Run android sdk, and check "Sourced for Android SDK" for the particular API version you're working with, in my case 24, and press "Install packages...".

To make this script global, I've placed it in directory ~/.local/bin/ and of course changed ~/.bashrc and added the line (which requires a restart of the terminal):

export PATH=${PATH}:~/.local/bin

Unless you have already done so, ANDROID_HOME should be included in ~/.bashrc:

export ANDROID_HOME=~/.android/sdk
export ANDROID_BUILD_TOOLS=$ANDROID_HOME/build-tools/24.0.2
export PATH=${PATH}:$ANDROID_HOME/tools
export PATH=${PATH}:$ANDROID_HOME/platform-tools

Now, whenever you wonder where a specific class is located, just run in terminal: android-finder [class]

$ android-finder AppCompatActivity
android.support.v7.app.AppCompatActivity

Not a very complicated thing, but a bit quicker than Google.

No comments:

Post a Comment