Frage

I have three questions:-

1) I am creating an OPCUA client for an OPCUA server. My Application has several avtivities, and most of them need the connected client. What is the best way to make my connected client available in all my actvities. I have currently used a static variable to hold my client. But is there any other better way. My client is not Serializable or Parcelable and thus cannot be passed as an intent argument.

2) Can I maintain this static variable in a Service and access the same in all my activities with MySerivce.connectedClient? Would that be good programming practice?

3) What if my application force closes and the connection with my server is not released. I want to be able to disconnect from my server even if my application force closes. Is there a way to ensure this (except for enclosing all my code in a try catch block) ?

Please suggest.

War es hilfreich?

Lösung

Its better to keep all application specific things in Application class.

http://developer.android.com/reference/android/app/Application.html

eg-

 public class XYZ extends Application {
 .....

 }

All the app specific initialization could be used here too.

For your requirement , Static initialization fits here well. The only thing is that It can be done in Application class rather than a Service ( which is prone to be killed by android )

Force stopping the app will kill the entire process (i.e. with Process.killProcess(int pid)). All resources associated with the application will be removed and freed by the kernel. So no, there is no way that you can intercept this action.

but for safer side always

1) You should unregister the server connection in OnDestory ()

2) Even for more safer you can use following functions in Application class

public void onLowMemory ()
public void onTerminate ()
public void onTrimMemory (int level)

Andere Tipps

To me, this sounds as if you should implement your client as a concurrent, app specific (private) Service. It would be started and stopped on demand by Android, and all your Activities could bind to it.

http://developer.android.com/guide/components/services.html

Lizenziert unter: CC-BY-SA mit Zuschreibung
Nicht verbunden mit StackOverflow
scroll top