Tag: java

Understanding Battery Usage in your Android App

Understanding Battery Usage in your Android App

Developing an android app can be a difficult and daunting task. There is so much to think about and a lot of the time battery usage is not very high on the list of things to remember. However, it is one of the most important things you need to consider. If your app is draining your user’s battery leaving them with a dead phone, the chances of them uninstalling and never using it again are VERY high. Take this guy for example:

Battery Historian - Understanding battery usage in your android app - App Reviews

 

He is clearly not happy with this app. In this blog post, we will take a look at Battery Historian and also provide some tips on how to avoid draining a user’s battery.

What is Battery Historian?

Battery Historian is a tool that displays information about your phone’s battery usage in HTML form. It provides a way to analyse the battery usage by showing you information like:

  • What app is in the foreground
  • What apps requested a wake lock and how long the phone was awake for
  • When the mobile radio was in use
  • When the GPS is active

How do I use Battery Historian?

  1. Download and install Go
  2. Follow the instructions on the Github page to set up the battery historian.
  3. Plug in your device and run adb bugreport > bugreport.txt in terminal. This will take a couple of minutes.
  4. Run battery historian. Open localhost:9999 in a browser and select the bugreport.txt. You will then see the battery historian output.
Battery Historian - Understanding battery usage in your android app
Battery Historian 2.0 Graph

You can see from this graph that it shows the battery level and the time. The graph also highlights information like if the phone was in Doze Mode, the charging status and lots of other information. This graph shows my device going from 100% at 7AM to about 10% at 12PM.

Battery Historian - Understanding battery usage in your android app - App Stats
App Stats Tab

There is also information regarding specific apps if you want to select your app and see how it is performing. Navigate to “App Stats” and then select your app from the drop down. You can see some useful information such as how much time the app was running for, the data usage and a lot more information.

This tool is very useful for figuring out what resources the apps are using and figuring out how much time they spend in the background even if you don’t use them.

Some tips for improving Battery Usage in your Android App

  • Avoid wake locks if possible.
  • Batch up cellular operations so as to avoid waking up the device every few seconds.
  • Schedule unimportant operations until the user has plugged into a charger and on WiFi. Things like analytics and logging don’t need to happen in real time.
  • Don’t download data if you don’t need to. Try adjust the queries required when using mobile data vs WiFi.
  • Use the system’s built-in options for background processing – such as the JobScheduler API or the SyncAdapters to sync content only when needed.
  • Remove unnecessary background processes if they are not needed.
  • Test your app on a really low end device for a day and see how/if it runs the battery down.
  • Be careful with location updates. The more you request, the more battery you will use. See more here.
  • Join the Android Performance Patterns Google Plus community and read the official docs about improving battery life.

What tips do you have for reducing the amount of battery usage in your application?

Android SQLite Database – How to use onUpgrade() correctly

Android SQLite Database – How to use onUpgrade() correctly

After reading this blog post (and a few others) on how to use the onUpgrade() method for your Android SQLite Database, I thought I should share my experience about how to correctly upgrade your database. It will also be beneficial to highlight why the final solution listed in that blog post would also fail at some point for some scenarios. The post explains quite well the drawbacks of some of the solutions that I also went through, but their final solution can also leave you in trouble.

Read More Read More

Android – Reduce the size of your APK files

Android – Reduce the size of your APK files

If it is one thing that I hate – it is apps that are HUGE downloads for really simplistic functionality.

40MB for an app that just accesses some messages and has hardly any images, what is it doing??

313

I have recently had quite an obsession trying to reduce my app size and have managed to shave off 6MB with a few optimisations (Yay right?!!!! 😃). I thought I would share some tips on how to reduce your Android APK file size:

  1. Use ProGuard: this will obfuscate your code and reduce the app size. [1]
  2. Enable the following with gradle:
    • minifyEnabled – this will get rid of unused code.
    • shrinkResources – this will get rid of unused resources such as layouts or strings that are not referenced in your app.
      buildTypes {
      
              release {
                  shrinkResources true
                  minifyEnabled true
                  proguardFiles getDefaultProguardFile('proguard-android-optimize.txt'),'proguard-project.txt'
                  signingConfig signingConfigs.config
      
              }
          }
      
  3. Make use of split APKs. This is especially useful if you are using native libraries. The native libraries can be quite large and making a user download an x86 library when their device is ARMv7 is pointless. Strip that out. [2]
  4. Check your images. If there are any large bitmaps, chances are you can reduce the size without losing much detail in the image. If possible, use JPEGs instead of PNGs as they are generally smaller.[3]
  5. Consider using Vector Drawables instead of PNGs for every density bucket. This will reduce the number of files needed and the images won’t degrade in quality.[4]
  6. Don’t use images if you don’t need to. Gradient backgrounds, shapes or colours can be achieved with XML instead.[5]
  7. Consider the libraries you use. If a library is massive and you are only using one or two functions you should find an alternative smaller option. Look through your code to see if there are any unused JAR files or unused code and remove that too.

Be careful when doing the things listed above, make sure you test thoroughly after applying these changes as it could break parts of your app. It could get rid of resources or code that might be used.

What do you do to reduce the size of your APKs?

Links:
  1. ProGuard Documentation
  2. Split APKs
  3. PNG vs JPG vs SVG
  4. Vector Asset Studio
  5. Drawable Resources
Getting Started: The Android Data Binding Library Part 1

Getting Started: The Android Data Binding Library Part 1

Anyone who has dabbled a bit in Android Development will know that Android is lacking a key component of MVVM: The ability to bind data without a couple of lines of code. 

For instance, setting a TextView to some value retrieved from a server is pretty complex, considering the simplicity of the task:

TextView textView = (TextView)v.findViewById(R.id.text_view);
if (TextUtils.isEmpty(mText)){
   textView.setText(mText);
   textView.setVisibility(View.VISIBLE);
} else {
   textView.setVisibility(View.INVISIBLE);
}

Doing everything this way can become a bit cumbersome and leads to very cluttered code. I don’t think anyone needs much convincing that this process of manually binding data is not ideal.

Cue: Android Data Binding Library (It’s like someone heard our cries? :-)). The 6 lines above can be converted into 2:

android:visibility="@{TextUtils.isEmpty(page.text) ? View.GONE : View.VISIBLE}"
android:text="@{page.htmlText}"

I decided to take a look and try it out, and see how well it would work for my applications.

Initial Impressions:

  • Very powerful library 
  • Less cluttered code
  • Less view logic in Activity and Fragment classes (yay!?!)
  • Compatible from API version 7+ (2.1)
  • Not recommended for use in production yet (It’s currently in Public Beta Phase but you are welcome to ship your app using it, it’s just not advised)
  • No support in Android Studio for syntax highlighting or code completion 

How to get started with the Android Data Binding Library:

  1. To get started with the Data Binding Framework, you need to include a couple of Gradle Dependencies in your top level build.gradle file in the dependencies section:
    classpath "com.android.tools.build:gradle:1.3.0"
    classpath "com.android.databinding:dataBinder:1.0-rc1"

     

  2. In the Top Level build.gradle make sure the following is defined (It probably is already):
    allprojects {
       repositories {
           jcenter()
       }
    }
  3. In each module of your project make sure to include the following right after the android plugin is applied:
    apply plugin: 'com.android.application'
    apply plugin: 'com.android.databinding'
  4. Create your object that you wish to represent in your view. In our case we have a Page object which contains a number, image link and some text.
    public class Page {
    
        private Integer pageNumber;
        private String image;
        private String text;
    
        public Integer getPageNumber() {
            return pageNumber;
        }
    
        public void setPageNumber(Integer pageNumber) {
            this.pageNumber = pageNumber;
        }
    
        public String getImage() {
            return image;
        }
    
        public void setImage(String image) {
            this.image = image;
        }
    
        public String getText() {
            return text;
        }
    
        public void setText(String text) {
            this.text = text;
        }
    
        public Page() {
        }
    
        public Spanned getHtmlText() {
            if (TextUtils.isEmpty(getText())){
                return SpannedString.valueOf("");
            }
            return Html.fromHtml(getText());
        }
    }
  5. Create Layout XML as per usual.  We have a ImageView  and a TextView  in our layout. At the start of the layout we will define what objects and methods will be used in this page.
    <?xml version="1.0" encoding="utf-8"?>
    <layout xmlns:android="http://schemas.android.com/apk/res/android"
            xmlns:app="http://schemas.android.com/apk/res-auto">
        <data>
            <import type="android.view.View"/>
            <import type="android.text.TextUtils"/>
    
            <variable
                name="page"
                type="org.company.pojo.Page"/>
        </data>
    
        <LinearLayout
            android:layout_width="50dp"
            android:layout_height="match_parent"
            android:visibility="@{page == null ? View.INVISIBLE : View.VISIBLE}"
            android:orientation="vertical">
            <ImageView
                android:id="@+id/image_view_page"
                android:layout_width="match_parent"
                android:layout_height="50dp"
                android:visibility="@{TextUtils.isEmpty(page.image) ? View.GONE : View.VISIBLE}"
                app:imageUrl="@{page.image}"/>
            <TextView
                android:id="@+id/text_view_page"
                android:layout_width="match_parent"
                android:layout_height="wrap_content"
                android:layout_below="@id/image_view_page"
                android:text="@{page.htmlText}"
                android:visibility="@{TextUtils.isEmpty(page.text) ? View.GONE : View.VISIBLE}"/>
    </LinearLayout>
       ...
    </layout>

    Let’s go through the new changes in this XML:

    • As you can see we no longer use a LinearLayout as the start tag, instead we use <layout> with the namespace declarations.
    • There is now a <data> section at the top of the file, which will include your imports to the different libraries you require. In this case, I required the TextUtils class. You can access any static methods define in a class. In this example I use the method TextUtils.isEmpty() to do different view logic.
    • <variable> tag defined, this allows you to define objects within the XML that will be used on the View itself.
    • Accessing a variable and some of its properties is simple:
    android:text="@{page2.htmlText}"
    android:visibility="@{TextUtils.isEmpty(page2.text) ? View.GONE : View.VISIBLE}"

    The words @{page2.htmlText}  will run the method getHtmlText()  on the page object.  One thing to note: Android Studio looks as if the method getHtmlText()  is unused, since it hasn’t found the usage in the XML but after deleting it, the project will fail to compile.

  6. After creating the Page object and the XML that will use the object, how do we go about putting the two together? Android will generate the object FragmentPageBinding (this name will change depending on your layout, eg. activity_book.xml  will create the object ActivityBookBinding ) which contains all the objects that you define in the <data> section of your corresponding XML file. From then, you just set the variables and your view will contain the correct values. As you can see, no view logic is sitting in my Fragment or Activity. Yay!
    @Nullable
    @Override
    public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
            FragmentPageBinding binding = DataBindingUtil.inflate(inflater, R.layout.fragment_page, container, false);
            binding.setPage(page);
            return binding.getRoot();
    
    }
  7. In the above code, you may also notice that on the ImageView we have the attribute app:imageUrl=”@{page.image}” . I like to load images from the web, in a background thread – using a library like Glide or Picasso . Create a Utils class called BindingUtils and pop this method in there. Now your ImageView will call this section of code with the url that we passed to it. We can then do what we like with it. In this case, we load the image into the view.
    @BindingAdapter({"bind:imageUrl"})
    public static void loadImage(ImageView view, String url) {
            Glide.with(view.getContext()).load(url).into(view);
    }
    

In Part 2 we will look at Two Way Binding and Binding Adapters.

South African Lotto Results & Checker {ANDROID APP} – DEPRECATED

South African Lotto Results & Checker {ANDROID APP} – DEPRECATED

UPDATE : 11 September 2015 : Unfortunately I had to discontinue this service as the official Lottery Provider changed, and the results are not published in the same manner. Sorry!

After searching the Google Play store for a Lotto app, I realised they were all pretty revolting, so I decided to create my own one – and here it is!

The application provides the latest South African National Lottery results for Lotto, Lotto Plus and PowerBall.

South African Lotto Results

 

Features of the application:

– View Latest Results for PowerBall, Lotto and Lotto Plus
– Generate Quick picks for Lotto and PowerBall which can be easily shared.
– Check tickets for Lotto, Lotto Plus and Powerball for any draw date.

 

 

 

 

You can download the app here: https://play.google.com/store/apps/details?id=za.co.riggaroo.lottoscan 

Below are some screenshots of the application.

Application Screenshot   Application Screenshot

If you have any ideas for improvements or suggestions I would appreciate them. I have a few more ideas up my sleeve for the application, so watch this space!