Passing variables between activities, services & a

2019-04-17 08:15发布

问题:

Would someone please provide me an example of the following Activity/Service/Application combination. I have all three, but I've turned my app into such a mess trying to pass a bunch of variables around the place, and now I don't know what's going on. Please be aware that I am new to android, and I have recently struggled with this, as there are so many ways this can be implemented.

I'd just like to see the 3 classes of activity, service and application where the following happens:

  • Activity stores variable x in Application, launches Service, and starts Activity 2.

  • Service retrieves variable x from Application.

  • Activity 2 retrieves variable x from Application.

Note that variable x could be anything from an Int to an ArrayList, and that in my actual program, there are a lot of variables (hence the desire for an application class).

I'd really appreciate a good example of this specific example, as I've been trying to figure all this out for a while. If someone would please take the time to put together a solid answer, I would greatly appreciate it.

For anyone asking why, the whole thing is a music player. The user picks a song, and the artist/album etc is (hopefully) stored in the application. Then the service is started, which controls the song playback, getting the songpath from the application. The second activity displays a UI with the song information (also from the application) and has next/previous buttons, which will change the value of some of the variables in the application, and instruct the service to retrieve the new values. If the user navigates away, the variables will always exist in the application, so if another UI is created, the song information can be set easily.

Am I using the right approach?

I can provide an example of what I've got, but it is a mess at the moment. Anyhow, just request for that below if you think it will help you to help me.

回答1:

You don't need to extend Application for this. You can just use static member variables in some class, like this:

public class Globals {
    public static String myVariable;
}

public class Activity1 extends Activity implements View.OnClickListener {
    @Override
    public void onCreate(Bundle savedInstanceState)
    {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.main);
        ...
    }

    public void onClick(View view) {
        // Save song name and stuff
        Globals.myVariable = "SongNameAndStuff"; // Save in static global variable
        startService(); // with appropriate parameters
        startActivity(); // with appropriate parameters

    }
}

public class Activity2 extends Activity {
    @Override
    public void onCreate(Bundle savedInstanceState)
    {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.main);
        // Get song name from Globals
       String mySongName = Globals.myVariable;
        ...
    }

public class MyService extends Service {
    // Access to song name from whatever method needs it:
    String mySongName = Globals.myVariable;
}


回答2:

I'd just use sharedpreferences tbh. Sounds like what you need... Make a class static accessible, and then make static getter and setter methods.

    import android.content.Context;
import android.content.SharedPreferences;
import android.content.SharedPreferences.Editor;
import android.util.Log;

public class OurPreferences {
    private static final String TAG = OurPreferences.class.getSimpleName();
    private final String PREFERENCES = "MobilityPreferences";
    private Context mContext;



private OurPreferences() {
}

private static SharedPreferences getPrefs(Context ctx) {
    return ctx.getSharedPreferences("PREFERENCES", Context.MODE_PRIVATE);
}
public static void setRegistrationId(String registrationId,
        long timeChanged, Context ctx) {
    if (registrationId != null) {
        Editor editor = getPrefs(ctx).edit();
        editor.putString("registrationId", registrationId);
        editor.putLong("timeChanged", timeChanged);
        editor.commit();
    }
}

public static boolean isRegistered(Context ctx) {
    boolean registered = getPrefs(ctx).getString("registrationId", null) != null;
    return registered;
}

public static long getRegistrationTimeInMilis(Context ctx){
   return getPrefs(ctx).getLong("timeChanged", -1L);
    }


回答3:

http://developer.android.com/resources/faq/framework.html#3

can put a A HashMap of WeakReferences to Objects in Application file and set the value in it...

now you can get the access to Application from Activity well as from service.... using ((YOUR_APPLICATION_NFILE_NAME)this.getApplication()). getter/setter;



回答4:

Use below Snippets :

Application Class :

public class ManagerName extends Application {
private static ManagerName singleton;
private String merchant;

public synchronized static ManagerName getInstance(Context context) {
    if (null == singleton) {
        singleton = new ManagerName();
    }
    return singleton;
}

public void setMerchant(String merchant) {
    this.merchant = merchant;
}

public String getMerchant() {
    return merchant;
}
}

Store and Retrieve Value in Activity :

public class ActivityName extends Activity  {

private ManagerName cacheManager;
@Override
public void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.user_details);

    cacheManager = ManagerName.getInstance(ActivityName.this);

    String merchant = cacheManager.setMerchant("Hello");// Store data in Application Class
    String storedValue=cacheManager.getMerchant();  // Retrieve Value from Application class    
}
}

Your Manifest should be like :

<application
    android:name=".ManagerName"
    android:icon="@drawable/ic_launcher"
    android:label="@string/app_name" >
    <activity>......</activity>
</application>

Concept for store and get back value from Application is very Simple :

  1. Create Variable in Application class name -> private ManagerName cacheManager ;
  2. Initialize it as -> cacheManager = ManagerName.getInstance(ActivityName.this);
  3. Using this instance to Save and get Values :

cacheManager.setMerchant("Hello");

cacheManager.getMerchant();

For further reference check this Link Application Class.