android - how to create a reusable function?

If I have useful functions that perform little helpful tasks that I want to invoke from several Activities, I create a class called Util and park them in there. I make them static so that I don't need to allocate any objects.

Here is an example of part of one such class I wrote:

public final class Util {
    public final static int KIBI = 1024;
    public final static int BYTE = 1;
    public final static int KIBIBYTE = KIBI * BYTE;

    /**
     * Private constructor to prevent instantiation
     */
    private Util() {}

    public static String getTimeStampNow() {
        Time time = new Time();
        time.setToNow();
        return time.format3339(false);
    }
}

To use these constants and methods, I can access them from the class name, rather than any object:

int fileSize = 10 * Util.KIBIBYTE;
String timestamp = Util.getTimeStampNow();

There's more to the class than this, but you get the idea.


You could create a static method or an object that contains this method.


You can create a class extending Activity, and then make sure your real activities are subclasses of that activity, instead of the usual built-in one. Simply define your common code in this parent activity.

Shachar


You can extend the Application class, then in your activities call the getApplication method and cast it to your application class in order to call the method.

You do this by creating a class that extends android.app.Application:

package your.package.name.here;

import android.app.Application;

public class MyApplication extends Application {

    public void doSomething(){
        //Do something here
    }
}

In your manifest you must then find the tag and add the android:name="MyApplication" attribute.

In your activity class you can then call the function by doing:

((MyApplication)getApplication()).doSomething();

There are other ways of doing something similar, but this is one of the ways. The documentation even states that a static singleton is a better choice in most cases. The Application documentation is available at: http://developer.android.com/reference/android/app/Application.html

Tags:

Android