Monday, 12 January 2015

Android - Check for internet connectivity.

It's common to check for connectivity to the Internet within your Android app before you try and perform an operation. For example, if you were about to call an external REST call, you may want to check internet connectivity before performing the operation.

To perform the check I use the following utility method:

private boolean isNetworkAvailable() {
           ConnectivityManager connectivityManager
                 = (ConnectivityManager) getSystemService(Context.CONNECTIVITY_SERVICE);
           NetworkInfo activeNetworkInfo = connectivityManager.getActiveNetworkInfo();
           return activeNetworkInfo != null;

}

Remember you need the following in your AndroidManifest.xml in order for your app to connect to the Internet:

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

Sunday, 11 January 2015

[FIX: Eclipse - Android layout file] - Incorrect line ending: found carriage return (\r) without corresponding newline (\n)

I hit this annoying issue today - I think due to copy and pasting code. Within my layout file in Android I'm getting the following error:

Incorrect line ending: found carriage return (\r) without corresponding newline (\n)



Closing the layout and deleting the problematic elements did not help. However, the fix is easy:


  1. Open your layout file. 
  2. Press Ctrl + Shift + F
  3. Save the layout file. 

Hope this saves someone time in the future!

Friday, 9 January 2015

The three key factors in an effective developer desk setup

Setting up your desk for efficient working is a vital step for any software developer, whether working from their home or in an office environment. In this post I set out a few tips on how to make your environment as effective as possible.

Note: This post is slightly different to my usual content, but I've been reading a book just now - Technical Blogging by Antonio Cangiano (responsible for Zen and the Art of Programming and Math-blog) - which stresses the importance of keeping up your pace of blogging when you start out. So while I've been too busy to blog as I've been building a new desk for my developer setup, I realised it formed a great subject for a blog post. I plan on writing a review post on the book (great so far) so look out in the future. 

To my knowledge there is no known ideal setup. There are three key factors you should consider when considering your setup:
  • Cost - what equipment can you buy
  • Space - how much space do you have (not to mention are you in a corner, open space, against a wall...)
  • Hardware requirements - some developers need one laptop, some need multiple machines, some need other devices attached such as mobile phones for app developers. 
As you can see in this post there is a huge development environment setup variety even in a workplace like Google. With that in mind you should focus on the three key factors above. 

When working with cost I recommend prioritising a good chair and desk. You will spend a lot of time (most likely multiple hours per day) so comfort is key. No matter what other equipment you buy, if you aren't comfortable you'll never sit at your desk and work. 

Space is the one you can't really impact. However, a good desk can help you manage your space effectively. You want a clear working area but you want everything close. When worried about space, I find using TeamViewer to remote onto other machines can be a really good space saver. In my desk environment, I like to use only one monitor as I find additional screens distracting; however, I'm usually switching between my windows desktop, a windows laptop and a Macbook Pro (I'm looking at attempting iphone app development in addition to Android now...) so using TeamViewer to control the two laptops works great for me and keeps my desk clear. 


The problem with hardware is that it again impacts cost and space. Cluttering up your desk can lead to loss of comfort and distractions. I suggest where possible, you use remote desktop or something like TeamViewer and store the hardware elsewhere.

A few other things to consider if you are planning a new setup:
  • Remember you'll probably need multiple power sockets!
  • Some speakers are well worth it if you like to listen to music as you work.
  • Can you get rid of a desk phone and use services like Lync or Skype?
  • Can you go paperless, so you don't need space for a printer.
  • If you run your own business remember to keep receipts for all equipment (desk, mouse, keyboard, computers) so you can claim them off your tax submissions.
As always additional ideas are always welcome so please leave a comment below.

Sunday, 4 January 2015

Top 5 free tools to help publish a mobile app

You have created your app, tested it and are happy with your end product. That isn't you done though, you need to make sure you have the right icons, screenshots, feature graphics etc. This last hurdle can be a pain but here's a few free utilities I've found over the years which are a huge help.

GIMP - [FREE] Image creation and manipulation.

GIMP is a great free application for creating and touching up your images. Need to tweak your screenshots, create a feature graphic or an advertisement? GIMP is your tool. It's a great free alternative to Adobe Photoshop.



Syncfusion MetroStudio - [FREE] Icons for your app

Metro Studio comes with over 4000 pre-made icons which you can customize to meet your needs - change the colors, change the size and export them to any format you want. See my Syncfusion MetroStudio tutorial for help in getting started.




Paint - Simple image software

Paint is a great simple tool for quickly cropping images and tweaking screenshots.

Image Resizer for Windows - [FREE] Change the size of your images and icons

You'll notice each app store has different image sizes for feature graphics and screenshots which is another pain when uploading your app to the store. Image Resizer for windows however is a quick and easy tool for resizing your images - simply right click in windows and choose your new dimensions and the tool generates a copy of the file with the new dimensions.


Android Feature Graphic Generator - [FREE] Create quick feature graphics 

This great website allows you to simple enter the text you want in your feature graphic and it will generate a nice feature graphic for you. Tweak the colors, fonts and even add images. A really quick win if you want to get your app uploaded quickly and Google Play now requires you have a feature graphic. 



If you have any other tools you recommend please add a comment and I'll check them out. If you found this post useful subscribe via email using the link at the top of this site.

Integrating Google Analytics into existing Android app

Analytics are key to measuring the success of your project or application and are a great way of identifying your users trends and demographics. Have you released an app and wondered who your users actually are? Well with analytics you could find out where your users are situated, what ages they are etc. The leader in this field is Google Analytics - this can be embedded into your mobile application, website and even your blog.



After a few frustrating attempts at integrating Google Analytics into an existing app I thought I should post a guide on how to do this.

1. Download the Google play services library and add it to your project.

You can do this by right clicking on the project you want to add analytics to in eclipse, choosing properties and then the Android tab. In the Library section, select Add and choose google-play-services_lib and select Apply.

2. Add the required permissions to AndroidManifest.xml.

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

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

These are required so your app can send the analytics content.

3. Add Metadata to your application. This should be added under the application tab.

<meta-data
            android:name="com.google.android.gms.version"
            android:value="@integer/google_play_services_version" />
<meta-data
            android:name="com.google.android.gms.analytics.globalConfigResource"

            android:resource="@xml/global_tracker"/>

We'll add global_tracker later.

4. Create the analytics application helper class.

import com.google.android.gms.analytics.Logger;
import com.google.android.gms.analytics.Tracker;
import com.google.android.gms.analytics.GoogleAnalytics;

import android.app.Application;

import java.util.HashMap;

public class YourApplication extends Application {

    // The following line should be changed to include the correct property id.
    private static final String PROPERTY_ID = "YOUR_ANALYTICS_ID";

    public static int GENERAL_TRACKER = 0;

    public enum TrackerName {
        APP_TRACKER, // Tracker used only in this app.
        GLOBAL_TRACKER, // Tracker used by all the apps from a company. eg: roll-up tracking.
        ECOMMERCE_TRACKER, // Tracker used by all ecommerce transactions from a company.
    }

    HashMap<TrackerName, Tracker> mTrackers = new HashMap<TrackerName, Tracker>();

    public YourApplication () {
        super();
    }

    synchronized Tracker getTracker(TrackerName trackerId) {
        if (!mTrackers.containsKey(trackerId)) {

            GoogleAnalytics analytics = GoogleAnalytics.getInstance(this);
            analytics.getLogger().setLogLevel(Logger.LogLevel.VERBOSE);
            Tracker t = (trackerId == TrackerName.APP_TRACKER) ? analytics.newTracker(PROPERTY_ID)
                    : (trackerId == TrackerName.GLOBAL_TRACKER) ? analytics.newTracker(
                            R.xml.global_tracker)
                            : analytics.newTracker(R.xml.ecommerce_tracker);
            t.enableAdvertisingIdCollection(true);
            mTrackers.put(trackerId, t);
        }
        return mTrackers.get(trackerId);
    }

}

5. Update AndroidManfiest.xml to include your application, e.g.:

<application
        android:icon="@drawable/ic_launcher"
        android:label="@string/app_name"
        android:theme="@style/AppTheme"
        android:name=".YourApplication" >

6. Create the tracker xml files. 

Under the res section in your project create an xml folder. Create two xml files in this named ecommerce_tracker.xml and one called global_tracker.xml. Contents below - remember to substitute in your analytics tracking ids. These can be created following instructions here

ecommerce_tracker.xml

<?xml version="1.0" encoding="utf-8"?>
<resources>
    <integer name="ga_sessionTimeout">60</integer>
    <!--  The following value should be replaced with correct property id. -->
    <string name="ga_trackingId">**INSERT TRACKING CODE HERE**</string>
</resources>

global_tracker.xml

<?xml version="1.0" encoding="utf-8"?>
<resources>
    <integer name="ga_sessionTimeout">300</integer>
    <bool name="ga_autoActivityTracking">true</bool>
    <screenName name="**Path to Your Application e.g. com.company.YourApplication**">**YOUR NAME**</screenName>
    <!--  The following value should be replaced with correct property id. -->
    <string name="ga_trackingId">** INSERT TRACKING CODE HERE ** </string>
</resources>

Note the trackers are described as follows by Google 

APP_TRACKER, // Tracker used only in this app.
GLOBAL_TRACKER
, // Tracker used by all the apps from a company. eg: roll-up tracking.
ECOMMERCE_TRACKER
, // Tracker used by all ecommerce transactions from a company.

7. Send the screens

Add the following code to your onCreate method in your activity. This will send the screen views to Google Analytics.

// Get tracker.
Tracker t = ((YourApplication) getApplication()).getTracker(TrackerName.APP_TRACKER);

// Enable Display Features so you can see demographics in Google Analytics
t.enableAdvertisingIdCollection(true);

// Set screen name.
t.setScreenName("** YOUR SCREEN NAME  **");
       
// Send a screen view.
t.send(new HitBuilders.AppViewBuilder().build());

8. Update onStart and onStop

Add the following:

@Override
protected void onStart() {
super.onStart();
GoogleAnalytics.getInstance(this).reportActivityStart(this);
}

@Override
protected void onStop() {
super.onStop();
GoogleAnalytics.getInstance(this).reportActivityStop(this);
}

9. View results in Google Analytics.

You are now done and once users start using your app you should be able to see real time updates in Google Analytics. Note that the analytics aren't exactly real time - but it's good enough! 


Let me know if this helps you out or if you have any further questions and I'll try and help where I can.

EDIT: 11/01/2015 - updated section 7 to allow you to display demographics in Google Analytics.

Allow Android app to install on SD card

A common problem which can turn users off your app is not having the option to transfer the app to their SD card hence clogging up their phone. Chances are they'll uninstall as soon as they can. Users may have apps such as AppMgr III (App 2 SD) installed which will automatically try and move any installed apps to their SD card.

Luckily as a developer enabling this is incredibly simple - it's one line in the AndroidManfiest.xml.

<manifest xmlns:android="http://schemas.android.com/apk/res/android"
    package="com.your.package.name"
    android:versionCode="1"
    android:versionName="1.0"

    android:installLocation="auto" >

The section highlighted in green is all you need to add. You have two options here:

  1. auto - this enables the app to be installed on the SD card, but you don't have a preference and you leave it up to the user. This is the option I always go for. Once installed the app can freely move between internal and external.
  2. preferExternal - this also enables the app to be installed on the SD card but you also try and install it there by default if there is available space. If there isn't it will default to internal phone storage. Once installed the app can freely move between internal and external.
That is all there is to it - a one line change which makes a massive difference to your user retention rates. The full documentation can be found here.

Friday, 2 January 2015

Update eclipse Android Development Toolkit to version 23.0.0

I hit the following irritating issue when I started eclipse up recently.

"This Android SDK requires Android Developer Toolkit version 23.0.0 or above. 

Current Version is 22.6.3.v201404151837-1123206. 

Please update ADT to the latest version." 



The really irritating thing was that clicking on Check for Updates found no updates! After a lot of different attempts, here's the steps I used to resolve this.

1. In Eclipse go to Help -> About Eclipse SDK


2. Click on "Installation Details".



3. Select Android Development Tools and click the uninstall button. You will need to restart once this is finished.


4. Now select Help-> Install new software.


5. Expand Developer Tools and select Android Development Tools and select next


6. Click next a few times and then finish.The installation will then begin. Accept any warnings about unsigned content. 

7. You'll be asked for another restart. Restart now.

  
Eclipse should now open with no errors. I hope this helps. I tried following others steps from stackoverflow  but had no success but these steps worked a treat. 

NOTE: At step 2 and 3 you can choose to uninstall all of these options and update all. In this article I focused on only the Android development tools.

Covid-19 impact on mobile applications - a quick case study

Amidst everything that's been going on over the last few months, checking on how my apps have been doing has been low down my priorities...