Keeping reference of an object for a task's li

2019-07-28 17:49发布

问题:

I am looking for a way to keep reference of an object/instance that's a member object of a service. I know in case of Activities, we can save it by the provided onSaveInstance method. However, I couldn't find any similar way for a service.

I can use static object but it's unsafe as there is no guaranty, if the reference would be valid the next time, the service is created.

Another possible way would be, I store all the data on storage & later on when the service is created again, I can read the data from storage. Then traverse through information/data provided by the another class & find the relevant reference for the info read from the storage, which I think is very expensive interms of execution time.

So I am looking for a way to get rid of all this process & keep a strong reference (of the object in service) in the memory as long as the task/app is running.

Regards

回答1:

You can use application class to persist data as

public class MyApplication extends Application 
{     
     public MyDataClass data = new MyDataClass();
}

Then call it in any activity/service by:

MyApplication appState = ((MyApplication)this.getApplication());
appState.data.useAGetterOrSetterHere(); // Do whatever you need to with the data here.

In your manifest mention it as follows::

<application android:name="yourpkgname.MyApplication"/>

More info are like

Application object is an object whose lifecycle is same as our Application.

When Application starts this object is created automatically by Android Framework.

When you want to share data between more than one activities of your application or you want to retain something at application level.In that scenario you can use Application object as a global store for your application.