简体   繁体   English

在不同活动之间共享android服务的好方法是什么

[英]What is a good way to share an android service across different activities

How can I make only one service in an application, and make its constituting activities share it across them? 如何在一个应用程序中仅提供一项服务,并使其构成活动在它们之间共享? Can I initialize it in first activity, make it public static, and refer to it directly in other activities? 我可以在第一个活动中对其进行初始化,使其成为公共静态文件,然后在其他活动中直接引用它吗? Or do I need to create a singleton class of it, and instantiate it in every activity? 还是我需要为其创建一个单例类,并在每个活动中对其进行实例化?

Please help me find a way to do this. 请帮助我找到一种方法。 Thanks 谢谢

----update----------- ----更新-----------

say there's Activity1, Activity2, and Service3 说有Activity1,Activity2和Service3

Can I make it like this: 我可以这样吗?

public class Activity1 extends Activity{
    public static Service3 mserv; 
    onCreate(){
        bindService(new Intent(this, Service3.class))
    }
    ...
}

public class Activity2 extends Activity{
    public Service3 mservice;

    onCreate(){
        mservice = Activity1.mserv;
    }
    ....
}

public Service3 extends Service{
   onCreate(){
    ....
   }

   onBind(){
    ...
   }
}

You can use intents to speak with service, read about it here . 您可以使用意图与服务进行对话, 在此处进行了解。

It should look some thing like that: 它看起来应该像这样:

  Intent intent = new Intent(context, YourServiceClass.class);
  activity.startService(intent);

You service will get Service.onStartCommand 您的服务将获得Service.onStartCommand

You need to start your Service explicitly by calling startService() . 您需要通过调用startService()显式启动服务。 Then you can either Bind to it or coummunicate with it via LocalBroadcastManager . 然后,您可以将其绑定或通过LocalBroadcastManager与之进行LocalBroadcastManager

暂无
暂无

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

相关问题 在两个活动之间共享实例对象的好方法是什么? - What is the good way to share instance object between two Activities? 在不同活动或碎片之间共享数据的正确方法是什么? - What is the correct way to share data between different Activities or Fragments? 在具有不同基类的活动之间共享代码的最佳方式是什么? - What is the optimal way to share code between Activities with different base classes? 通过所有活动平均分享android服务 - android service by mean share by all activities 在Android Studio中跨不同活动共享变量 - Sharing Variables Across Different Activities In Android Studio 在不同子模块中的活动之间共享复杂对象的实例 - Share instance of complex object across activities in different submodules 在Android活动之间共享视图的正确方法? - Correct way to share a View between Android activities? Android-管理跨多个活动与本地服务绑定/解除绑定的有效方法 - Android - effective way to manage binding/unbinding from local service across multiple activities 当一个人在线性布局中使用权重而其他人不使用线性布局时,什么是在各个活动之间对齐布局的好方法? - What 's a good way to align layout across activities when one uses weight in linear layout while the rest does not? 在Android中的活动之间共享复杂的对象树的好选择? - Good alternatives to share a complex tree of objects between activities in Android?
 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM