简体   繁体   中英

Global object of android app

i am developing an android app. I have some activities in it. And i must have an object which can be available from all activities. Any ideas how to organize it?

Use the global Application object in the following way:

package com.yourpackagename;

public class App extends Application {
}

In AndroidManifest.xml :

<application android:name=".App">

To access it from an Activity :

App globalApp = (App) getApplicationContext();

The App class will be instantiated automatically when the app starts. It will be available as long as the application process is alive. It can act as a global store in which you can put your things and have access to them throughout the application lifetime.

There are a few ways to do this. If the object you want to share is a String (or easily described with a String), I would recommend Shared Preferences . It serves as a key-value store for sharing data within an application.

If this is not the case (ie the suitability of a String), you could consider passing it as an extra with the Intent that launches your various activities. For example:

Intent newActivity = new Intent(CurrentActivity.class, ActivityToLaunch.class);
newActivity.putExtra("object_key", Bundle_With_Your_Object);

For more details on this strategy (especially about the Bundle class, if you're not familiar), I would read this Android doc .

You can use SharedPreferences in this case:

To add or edit:

SharedPreferences prefs = this.getSharedPreferences("Cusom Name", Activity.MODE_PRIVATE);
prefs.edit().putString("your_key", value).commit();

To clear:

SharedPreferences prefs = this.getSharedPreferences("Cusom Name", Activity.MODE_PRIVATE);
prefs.edit().clear();

To get value:

SharedPreferences prefs = this.getSharedPreferences("Cusom Name", Activity.MODE_PRIVATE);               
String value = prefs.getString("your_key", "");

First, create a class named MasterActivity which extends Activity and define your global object.

public class MasterActivity extends Activity
{
     public Object mObject;
}

Then, you have to extend your main activity class with your MasterActivity like it :

// your main activity
public class MainActivity extends MasterActivity
{
    @Override
    protected void onCreate(Bundle savedInstanceState)
    {
        super.onCreate(savedInstanceState);
        // you can now use mObject in your main class
        mObject.yourmethod();
    }
}

By this way, you will be able to use your object in all your activities simply by extending MasterActivity instead of Activity.

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