Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

android - how to create a reusable function?

Tags:

android

In my android project, I have many activities and some of them already extend other stuff like map activity or BroadcastReceiver.

How do I create a function that I can call from any activity, because I don't want to have to repeat any code in multiple activities.

thanks.

like image 265
omega Avatar asked Jul 22 '12 19:07

omega


2 Answers

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.

like image 101
Sparky Avatar answered Sep 17 '22 17:09

Sparky


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

like image 45
Dimse Avatar answered Sep 20 '22 17:09

Dimse