在我制作的应用程序中,我想在一个活动中开始一个意图
Intent toonService = new Intent(Login.this, ToonService.class);
toonService.putExtra("toonName", result.getName());
Login.this.startService(toonService);
下面的代码将关闭我刚刚打开的意图吗?如果不是,我怎么才能得到它?
Intent toonService = new Intent(MainActivity.this,ToonService.class);
MainActivity.this.stopService(toonService);
第二段代码将在与第一段代码完全无关的时间调用。
最佳答案
好吧,假设您只希望这个服务的一个实例同时运行,那么您可以在服务类中保存一个静态变量并从任何地方访问它。例子;
public class ToonService extends Service{
public static ToonService toonService;
public ToonService(){
toonService = this;
}
...
}
ToonService的构造函数现在将创建的实例存储在静态变量
toonService
中。现在您可以从类的任何位置访问该服务。示例如下:ToonService.toonService.stopSelf();
您还可以通过让类存储运行实例的静态
List
而不仅仅是单个实例来处理多个实例。It is worth noting,当您告诉服务停止时,您只是请求它停止。最终android操作系统将决定何时关闭。