How to create annotated Git tags

Annotated Git tags keep the information of related with tag and permanent in nature. It can be created using this command:
git tag -a <tagname>
An already existing tag can be modified using flag "-f" like this:
git tag -a -f <existing_tag_name>
A specific tag can be pushed to remote like this:
git push origin <tagname> 
Deleting tags:

  • Deleting remote tag:
git push origin :<tagname> OR git push --delete origin <tagname>
  • Deleting local tag
git tag -d <tagname>

General guidelines: 
  •  git push where-to-push source-refs:destination-refs
  • git push <remote> <local-branch>:<remote-branch>
  • git push origin refs/head/master:refs/heads/master
  • git push origin master:master



How to change author for a GIT commit


  • First fix up the author details in .git/config file for the given repo by adding this block
[user]
                  name = <new name>
                  email = <new email>
   
  • Now execute following command to amend the commit:
git commit --amend --reset-author

Creating remote GIT branch

You can create a new local branch like this:
git checkout -b <branch_name>

If you want to make it a remote branch, then it can be pushed to remote like this (make sure that you're in this new branch):
git push origin <branch_name>

But sometimes, this newly pushed branch to remote doesn't get updated on remote location. Remote branches could be forced refreshed like this:
git remote update origin --prune 
If you want to delete a local branch:
git branch -d <branch_name>
If you want to delete this branch in remote too, then:
git push origin :<branch_name> 
 

Updating Android SDK tools from commandline

  • View all available downloads for build tools:
android list sdk --all 
  •  Updating packages
 android update sdk --no-ui --all --filter <package_number1, packager_number2, ...>
  •  Updating packages (without alias)
android update sdk -u -a -t <package_number1, packager_number2, ...>

To see the list of AVDs created/available :
android list targets 

SigningConfig for Gradle - Android

Add following code snippet in your build.gradle:

signingConfigs {
   debug {
      storeFile file('<full-path-to-keystore>/.android/debug.keystore')
      storePassword 'android'      keyAlias 'androiddebugkey'      keyPassword 'android'   } 
}
Add More variants for each flavor like release.

PackageManager.getInstalledPackages() vs PackageManger.getInstalledApplications()

PackageManager.getInstalledPackages()
Lists all the packages installed on the device including services, providers etc.

 PackageManger.getInstalledApplications()
Lists only applications installed on the device. Excludes services, providers etc.

Setting up Unit Testing in AndroidStudio - 1.5 with Robolectric

AndroidStudio Version: 1.5 - Preview2
Robolectric: robolectric:3.0-rc2


  • Choose "Unit Tests" in "Build Variants" as "Test Artifact". 
  • Create a Unit Test under "src/test" folder.
  • Run the test !


Configuration details:

build.gradle additions related with unit tests:

dependencies {
    
    testCompile 'junit:junit:4.12'    testCompile('org.robolectric:robolectric:3.0-rc2') {
        exclude group: 'commons-logging', module: 'commons-logging'        exclude group: 'org.apache.httpcomponents', module: 'httpclient'    }
}

Sample Test class:
import org.junit.Before;
import org.junit.Test;
import org.junit.runner.RunWith;
import org.robolectric.RobolectricGradleTestRunner;
import org.robolectric.annotation.Config;

@RunWith(RobolectricGradleTestRunner.class)
@Config(constants = BuildConfig.class, emulateSdk = 21)
public class MyTest {

    @Before    public void setUp() throws Exception {
        // setup    }

    @Test    public void testSomething() throws Exception {
        // test        assert(true);
    }
}




Pro-guard in Android


  • Pro-guard can only be enabled in release builds, which is a good thing. Otherwise you would have to debug through obfuscated code.
  • Pro-guard can shrink, optimize and obfuscate code.
  • Obfuscated stack traces could be decoded using tool "retrace".
  • Enabling pro-guard in gradle based builds: set "minifyEnabled" to true.
  • Default pro-guard settings are available in <sdk>/tools/proguard/
    proguard-android.txt
  • Optimization can be enabled by using <sdk>/tools/proguard/proguard-android-optimize.txt file. But testing have to be thorough because these optimization rules may not be applicable to all versions of dalvik.
  •  Custom pro-guard rules can be added in proguard-rules.pro
  • While building with gradle build system, particular pro-guard rules can be applied to a targeted flavor

Running gradle as daemon (Mac)

How to know if gradle daemon is running or not ? Run "gradle --stop" on commandline. It should spit out that gradle is not running as daemon.
$ gradle --stop
No Gradle daemons are running.

Follow these steps to make gradle run as daemon:

Navigate to /Users/<your user name>/.gradle
cd /Users/<your user name>/.gradle
Create a file name gradle.properties
vi gradle.properties
Add a line in "gradle.properties"
org.gradle.daemon=true

Done !

Note: Execute any gradle task to kick start daemon.

Verify
$ gradle --stop
Stopping daemon(s).
Gradle daemon stopped.


 
 

Adding JAVA_HOME env variable to bash (Mac)

On your terminal, execute this command all together:
echo "# Java environment variables
export JAVA_HOME=$(/usr/libexec/java_home)
export JDK_HOME=$(/usr/libexec/java_home)
" >> ~/.bash_profile&&\
source ~/.bash_profile

Installing gradle using commandline (Mac)

Simple ! Just execute this command on your terminal :

brew install gradle

Pre-req: you should have Homebrew for Mac already installed. 

Installing gradle on Mac (using gradle wrapper)

The simplest way to install gradle from commandline is to simply execute this script that comes with gradle wrapper.

All you have to do is to execute this command on terminal:
./gradlew
Output:

Downloading https://services.gradle.org/distributions/gradle-2.3-bin.zip
...........................................................................................................................................................................................................................................................................................................................................................................................................................................................................................................................................................................................................................................................................................................................................................................................................................................................................................................................................................................................................................................................................................................................................................................................................................................................................................................................................................................................................................................................................................................................................................................................................................................................................................................................................................................................................................................................................................................................................................................................................................................................................................................................................................................................................
Unzipping /Users/PTyagi/.gradle/wrapper/dists/gradle-2.3-bin/a48v6zq5mdp1uyn9rwlj56945/gradle-2.3-bin.zip to /Users/PTyagi/.gradle/wrapper/dists/gradle-2.3-bin/a48v6zq5mdp1uyn9rwlj56945
Set executable permissions for: /Users/PTyagi/.gradle/wrapper/dists/gradle-2.3-bin/a48v6zq5mdp1uyn9rwlj56945/gradle-2.3/bin/gradle 

Keep trying out ideas !

This is not a technical post, but worth giving a though into !

The best way to invent something Great in life, is to keep trying out Silly ideas :)

"And yet the best way to have a good idea is to have as many bad ones as you can. The best way to write good poetry is to write a whole lot of stuff, and find the diamonds in the rough. The best way to set goals is to set 45 of them and see which ones stick around that are really the most interesting to us. And the best way to keep loving people we love is to keep the air clear with honest feedback." ~ David Allen

Android Dev Tools

Here's casual list for Android developer tools that could be really useful when developing complex applications:

  • StrictMode: A tool for identifying long running operations on Main UI Thread.
  • @UiThread/@WorkerThread : Useful support annotations for static analysis for catching Threading bugs.

Android Fragments using RxJava and Dagger

This is really cool introduction on Android Fragments using RxJava and Dagger dependency injection framework.

How to keep github fork repo in sync with main repo

This is how I keep my forked repo in sync with their main repos:

Create fork of the main repo.

Clone forked repo to your local machine:
git clone https://github.com/<username>/somerepo.git

Add main repo as another remote:

git remote add mainrepo https://github.com/<someurl>/somerepo.git

Fetch all the branches from mainrepo :
 git fetch mainrepo

Make sure that you're on your master (origin/master) :
git checkout master

Rebase your copy of master with main repo's master like this:
git rebase mainrepo/master

How to fix "Plugin with id 'com.android.library' not found." issue with Android Libraries

Normal structure of build.gradle for an Android library looks like this:
apply plugin: 'com.android.library'
android {
    compileSdkVersion 23 
    buildToolsVersion '23.0.0'
    defaultConfig {
        minSdkVersion 11 
       targetSdkVersion 23 
       versionCode 1 
       versionName "1.0" 
    }
    buildTypes {
        release {
            /runProguard false 
           proguardFiles getDefaultProguardFile('proguard-android.txt'), 'proguard-rules.pro'        }
    }
}

You might encounter dreaded "Plugin with id 'com.android.library' not found." error while importing this library project as an independent project in Android Studio.

After researching for a while around the web, I figured out what was missing. Actually, a way to tell your library project's gradle file to source to get the plug-in. Pretty straight forward, but may not occur when needed.

So, don't forget to add these lines at the beginning of the build.gradle for your Android library:

buildscript {
    repositories {
        mavenCentral()
    }
    dependencies {
        classpath 'com.android.tools.build:gradle:1.3.0'    }
}

apply plugin: 'com.android.library'
....

 

Finding tech work online ?

Are you interested in taking up projects online and work from wherever you like to ?  Your home...Your favorite coffee shop or may be your beautiful patio ! Yes ??? Read on ...


I've compiled few websites that you may want to look at:

  • Topcoder : You can take up a challenge and work thru it in order to get paid ! Perfect for hobbyists !
  • Upwork : An upcoming company coming up to connect talent with companies. Its a freelancers paradise.
  • ....More are coming up!




Developing Hybrid mobile applications for iOS and Android

Today I found out a promising open source project or better say a SDK to build hybrid apps for iOS and Android. Its called Ionic.

I'm looking forward to play around with it a little bit and will be posting my findings on this very blog. Stay Tuned !

When/Why to use Android DownloadManager to download remote files

DownloadManager should be used when your app is not dependent on downloaded data to show as a first thing. It queues requested download in device wide download queue, and download data in background. You may not get your data downloaded immediately to display in your app.

If the dependency of your app on remote data is synchronous, then you may want to download data using AsyncTask, and possibly using code like this in it:

InputStream inputStream = new URL(url).openStream();
//Copy input stream to to output stream now. 

But if you don't care about the timing of data download, then you should use DownloadManager like this:

String url = "http://url_to_your_remote-data";
DownloadManager  dm = (DownloadManager) getSystemService(Context.DOWNLOAD_SERVICE);
Request request = new Request(Uri.parse(url));
request.setDestinationInExternalFilesDir(getApplicationContext(),
        Environment.DIRECTORY_DOWNLOADS, "downloaded_data_filename");
enqueue = dm.enqueue(request);

And don't forget to register broadcast receiver in onCreate() method. That's where you'll receive callback once download is finished. Example:

BroadcastReceiver receiver = new BroadcastReceiver() {
    @Override    public void onReceive(Context context, Intent intent) {
        String action = intent.getAction();
        if (DownloadManager.ACTION_DOWNLOAD_COMPLETE.equals(action)) {
            long downloadId = intent.getLongExtra(
                    DownloadManager.EXTRA_DOWNLOAD_ID, 0);

            Uri localUri = dm.getUriForDownloadedFile(enqueue);
            //Do something with your download here...OR query useful params like below. 

            Query query = new Query();
            query.setFilterById(enqueue);
            Cursor c = dm.query(query);
            if (c.moveToFirst()) {
                int columnIndex = c
                        .getColumnIndex(DownloadManager.COLUMN_STATUS);
                if (DownloadManager.STATUS_SUCCESSFUL == c
                        .getInt(columnIndex)) {

                    String uriString = c
                            .getString(c
                                    .getColumnIndex(DownloadManager.COLUMN_LOCAL_URI));
                    Log.d("TAG", uriString);
                    
                }
            }
        }
    }
};

registerReceiver(receiver, new IntentFilter(
        DownloadManager.ACTION_DOWNLOAD_COMPLETE));



Sharing Code in Android Studio using "AAR"

Believe it or not, but Android Studio was launched with absolute no support to share code across several projects. You would need to keep a separate copy of "shared library" with in each project that uses it ! I was sarcastically impressed (or rather depressed) by Google's product owner for Android Studio who dared to give out that kinda IDE to developers.

Finally, they gave out some way to share code through "AAR" files. Thank you !

However, adding ".aar" files is not recommended locally as per this article. AAR files should be referenced from maven repos. You can always publish them to local maven repos for development purposes.

Other easy way is to put the ".aar" files in "libs" or any other newly created folder of your choice and refer it from build.gradle like this:

repositories {
    flatDir {
        dirs 'libs'    }
}

dependencies {
    compile fileTree(dir: 'libs', include: ['*.jar'])
    compile (name:'yourAwesomeAndroidLibraryName', ext:'aar')
}

VideoView vs MediaPlayer vs YouTube player API

I was looking into streaming videos in one of my app.

VideoView is nothing but a wrapper around MediaPlayer. VideoView adds control buttons around MediaPlayer. If you want to do more customization, the MediaPlayer is way to go. VideoView is a quicker way to get started with streaming videos. VideoView and MediaPlayer needs a video url or path ending with mp4, mp3 etc extensions. They can't play videos from Youtube Urls (at least when I tried playing them the way I did for videos with mp4 extension)

YouTube API is useful when you want to play videos based on YouTube urls.  You can embed a Youtube video in your app. But this could be little tricky when positioning it in your app. Also, it comes with API calls quota limits. There is only a certain amount of calls can be made for free by your app, and have to pay going forward.

Conclusion: Its better to use VideoView for offline videos which don't have piracy issues associated with them. I would NOT recommend downloading Youtube videos and bundling with your apps.

Online tool to generate mocked HTTP responses

Mocky is a wonderful tool to generate mocked HTTP Response on the fly. You don't have to spin a full server just to generate that very first mocked data. Its very helpful for client end development to quickly test the different data formats.

2015 Android Latest features


  1. Android Lollipop 5.0
  2. Gradle
  3. Android Studio
  4. NFC
  5. Android Wear
  6. ViewGroup, WebView, TextView, RecyclerView
  7. Material Design
  8. Memory Management
  9. Battery Consumption
  10. Android Runtime (ART)
  11. Concurrency and Android Thread Communications
  12. Animation
  13. Android Security
  14. Testing and Debugging (Tools)
  15. Enterprise Android Apps
  16. Bluetooth LE
  17. Android TV
  18. Automative Android
  19. Push Messaging
  20. Notifications
  21. Camera 2 APIs
  22. High-Performance Android Apps
  23. HTML Hybrid Apps
  24. Android Emulator
  25. Deep Linking
  26. Google Cast
  27. Retrofit
  28. App Indexing
  29. Location Services for Android
  30. App Search Optimization
  31. Project Ara
  32. Host Card Emulation (HCE)
  33. Cloud-Powered Android Apps
  34. Brillo 
  35. Weave

Android Networking library

I found a very nice article about using Android networking library Volley along with OkHttp and Gson here.

OkHttp deals with connection pooling, caching and gzipping etc, while Volley is a networking library manages network requests in an app and makes sure that networking calls are executed in background most efficiently.

Sample source code is on Github.

RecyclerView Animations !

I've come across this wonderful post about what RecyclerView widget is and how it works. A must read for someone who is looking for to add more flexibility which are not easy to implement in ListView widgets.

Updating Android SDK from commandline

Android SDK can be updated from command line by following these steps:


  • cd to directory where Android SDK is installed
  • cd <path-to-sdk-installation>
  • execute this command:
  • android update sdk --no-ui

Note: You'll be asked to accept few licenses. Type 'y' or 'n' to accept or reject.

You can see all the available packages using this command:

android list sdk --all

A particular package can be updated and installed using this command:
android update sdk -u --all --filter <number-listed-on-the-list> 

How to share code across projects using Android Studio

1. Create a Test application project : MyTestApplication

2. Add a module under MyTestApplication : MyLibrary 






3. Close Android Studio.
4. Go to folder location for MyTestApplication.
5. Locate MyLibrary directory.
6. Move MyLibrary directory to desired location. I'm using one level above to store my library.
7. Make a symlink to the library. 

8. Open Android Studio. 

9.

[Git] Re-setting user name and email and amending commit

User name and email can be modified using following command:

git config --global user.name "My user name"
git config --global user.email "me@example.com"

Already done commit can be modified using this command :
git commit --amend --reset-author 
Editing a specific commit for a commit history of a1-a2-a3-a4, where a4 is the HEAD. Lets say you want to edit a3 and a4. Run theses commands:

  1. git rebase -i a2
  2. This will open the commit message window/terminal. 
  3. Replace "pick" with "edit" for the commits that you want to change author info of.
  4. It will pause at a3, and would give you chance to edit your author for a3 commit.
  5. Now edit the commit:  git commit --amend --author="authorname <user@email.com>"
  6. Execute : git rebase continue --
  7. It will pause at a4, and would give you chance to edit your author for a4 commit.
  8. Execute: git commit --amend --author="authorname <user@email.com>"
  9. Execute: git rebase continue --
  10. You're done !

Scheduling Repeating Local Notifications using Alarm Manager

Learn about Scheduling Repeating Local Notifications using Alarm Manager in this post .