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