我是android的新手,我有一个问题。
我想在我的整个android程序中只有一个类的实例,这样它的属性在程序中不会改变,但我也想在所有程序中调用它的方法我的活动。
通过一些搜索,我意识到我可以通过实现类传递我的对象作为Serializable或Parcelable。我做到了这一点,但我得到了以下错误:
java.lang.RuntimeException: Parcelable encountered IOException writing serializable object
java.io.NotSerializableException: microsoft.aspnet.signalr.client.hubs.HubConnection
如您所见,我的一个类属性是HubConnection
,它位于Microsoft软件包中,我无法使其可序列化。
如何将SignalR类的对象传递给另一个活动?我有什么选择?
public class SignalR implements Serializable {
private HubConnection connection;
private HubProxy proxy;
//some methods
}
答案 0 :(得分:3)
如果您的目标是从您的所有活动中全局访问您的班级的单个实例,那么您不希望使用bundle传递它。而是使用singleton pattern。
如果您出于其他原因需要使用捆绑包,请使用Parcelable
代替Serializable
,这意味着更快。创建一个parcelable有一个模式可供遵循。最好的办法是从here复制粘贴答案,然后更改构造函数,parcelling和unparcelling。
答案 1 :(得分:3)
如果您想在整个应用程序中使用 YourCustomClass 的单个实例,则可以在YourApplication类中保留自定义类对象的引用。
创建一个类并将其扩展到Application类。在应用程序类中创建setter和getter方法以访问自定义类实例。现在,您可以从应用程序中的任何位置访问自定义类实例,而不必在活动之间传递实例。
public class YourApplicationClass extends Application{
private YourCustomClass yourCustomClass;
public YourCustomClass getYourCustomClass() {
if (yourCustomClass == null) {
yourCustomClass = new YourCustomClass();
}
return yourCustomClass;
}
public void setYourCustomClass(YourCustomClass yourCustomClass) {
this.yourCustomClass = yourCustomClass;
}
}
不要忘记在您的清单文件中放置android:name =“ YourApplicationClass ”。
<application
......
android:name=".YourApplicationClass"
....... >
现在要从您的活动中访问该对象,比如说MainActivity,你会写一些像 -
@override
protected void onCreate(Bundle savedInstanceState) {
YourApplicationClass app = (YourApplicationClass) getApplication();
YourCustomClass yourCustomInstance = app.getYourCustomClass();
}