Creating a utillity class which extends activity

When developing an app, i came across many times when i needed to perform some action (that requires context to be of type Activity) from inside a class which dont extend Activity.

For example: create an AlarmManager event, creating a broadcast or manipulating System Services.

Is it a good idea to create a static activity which will function as a utillity class to perform actions?

The benefit will be that it will be available for access from the entire app classes.

Otherwiswe i find my self duplicating code from one activity to another.

Answers


public class MyApplication extends Application {

    public static MyApplication instance = new MyApplication();
    private static Context context;

    @Override
    public Context getApplicationContext() {
        // TODO Auto-generated method stub
        return super.getApplicationContext();
    }

    @Override
    public void onCreate() {
        // TODO Auto-generated method stub
        super.onCreate();
        context = this;
    }

    public static Context getContext() {
        return context;
    }

}

You can call this by simply MyApplication.getContext();

And add this tag into your AndroidManifest.xml to initialize this class when your application get started.

<application
        android:allowBackup="true"
        android:icon="@drawable/ic_launcher"
        android:name="com.example.application.MyApplication"
        android:label="@string/app_name"
        android:theme="@style/AppTheme" >

Make sure these calls need an Activity and not a Context. I believe the cases you mention only require a Context, which is readily available outside of an Activity. For example, an Android Service derives from Context, as does the Application object itself.


Need Your Help

Java in 2011: threaded sockets VS NIO: what to choose on 64bit OS and latest Java version?

java networking io nio

I've read several posts about java.net vs java.nio here on StackOverflow and on some blogs. But I still cannot catch an idea of when should one prefer NIO over threaded sockets. Can you please exam...