简体   繁体   中英

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.

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.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM