简体   繁体   English

在android中的活动,服务和应用程序之间传递变量

[英]Passing variables between activities, services & applications in android

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. 请注意我是android新手,我最近一直在努力解决这个问题,因为有很多方法可以实现。

I'd just like to see the 3 classes of activity, service and application where the following happens: 我只想看到发生以下情况的3类活动,服务和应用程序:

  • Activity stores variable x in Application, launches Service, and starts Activity 2. Activity在Application中存储变量x,启动Service,并启动Activity 2。

  • Service retrieves variable x from Application. 服务从Application检索变量x。

  • Activity 2 retrieves variable x from Application. 活动2从Application检索变量x。

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). 请注意,变量x可以是从Int到ArrayList的任何东西,而在我的实际程序中,有很多变量(因此需要应用程序类)。

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. 第二个活动显示带有歌曲信息的UI(也来自应用程序),并具有下一个/上一个按钮,这将改变应用程序中某些变量的值,并指示服务检索新值。 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. 如果用户导航,变量将始终存在于应用程序中,因此如果创建了另一个UI,则可以轻松设置歌曲信息。

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. 无论如何,如果您认为它可以帮助您帮助我,请在下面请求。

You don't need to extend Application for this. 您无需为此扩展Application 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;
}

I'd just use sharedpreferences tbh. 我只是使用共享偏好tbh。 Sounds like what you need... Make a class static accessible, and then make static getter and setter methods. 听起来像你需要的......让一个类静态可访问,然后制作静态getter和setter方法。

    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);
    }

http://developer.android.com/resources/faq/framework.html#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... 可以将WeakReferences的A HashMap放到Application文件中的对象中并设置其中的值...

now you can get the access to Application from Activity well as from service.... using ((YOUR_APPLICATION_NFILE_NAME)this.getApplication()). 现在,您可以使用((YOUR_APPLICATION_NFILE_NAME)this.getApplication())从服务....获取对Activity的访问权限。 getter/setter; 的getter / setter;

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 ; 在Application类名称中创建变量 - > private ManagerName cacheManager;
  2. Initialize it as -> cacheManager = ManagerName.getInstance(ActivityName.this); 将其初始化为 - > cacheManager = ManagerName.getInstance(ActivityName.this);
  3. Using this instance to Save and get Values : 使用此实例来保存并获取值:

cacheManager.setMerchant("Hello"); cacheManager.setMerchant( “你好”);

cacheManager.getMerchant(); cacheManager.getMerchant();

For further reference check this Link Application Class. 有关详细参考,请查看此链接应用程序类

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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