简体   繁体   English

Android网路课程

[英]Android Networking Class

I currently have an app that requires connection to a server in multiple activities. 我目前有一个需要在多个活动中连接到服务器的应用程序。 I am currently trying to create a class that handles the connection between multiple activities and provides getters to get the output streams, I have looked at a service class but I do not need to keep the connection when the app is not running. 我目前正在尝试创建一个用于处理多个活动之间的连接并提供获取方法以获取输出流的类,我查看了一个服务类,但在应用程序未运行时不需要保持连接。

I am not entirely sure what i need to do to get an object to be globally accessed from multiple activities without having to be instantiated the object in each activity. 我不完全确定我需要做什么才能从多个活动中全局访问一个对象,而不必在每个活动中实例化该对象。

You have 2 choices: 您有2个选择:

  1. Make a singleton class. 进行单例课程。 (I bet there is a lot of example in Google.) (我敢打赌Google中有很多例子。)

  2. Implement an "application" class. 实现一个“应用程序”类。 http://developer.android.com/reference/android/app/Application.html http://developer.android.com/reference/android/app/Application.html

The differences: 区别:

  1. For (1) it will instantiate the first time you access it. 对于(1),它将在您首次访问它时实例化。 (But depending on design). (但取决于设计)。 For (2) it will instantiate together with the app process. 对于(2),它将与应用程序过程一起实例化。

  2. For (1) it is more complex to handle the object life cycle. 对于(1),处理对象生命周期更为复杂。 For (2) you can manage your objects life cycle easily by controlling the access to the object in application. 对于(2),您可以通过控制对应用程序中对象的访问来轻松管理对象生命周期。

A Service is still the best idea. 服务仍然是最好的主意。 You just have to make it keep track of how many Applications are connected to it (in onBind/onStartCommand/onUnbind), and make it shutdown when it goes to zero. 您只需要使其跟踪连接的应用程序数量(在onBind / onStartCommand / onUnbind中),并在它变为零时关闭它即可。

What is a bit tricky is that Applications are not really closed in Android when they don't have focus: you would have to decide if an Application unbinds from the Service on onPause or onStop. 有点棘手的是,当应用程序没有焦点时,它们并没有真正在Android中关闭:您必须决定是在onPause还是onStop上将应用程序与服务解除绑定。

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

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