Android的 - 从不同的类停止服务 [英] Android - Stop a Service from a different class

查看:187
本文介绍了Android的 - 从不同的类停止服务的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

在应用程序,我正在做我想在一个活动启动意图

In the application i'm making I want to start an intent in one activity

Intent toonService = new Intent(Login.this, ToonService.class);
toonService.putExtra("toonName", result.getName());
Login.this.startService(toonService);

将以下code关闭我刚打开的意图是什么?如果没有我怎样才能得到它?

Will the following code close the intent i just opened? If not how can i get it to?

Intent toonService = new Intent(MainActivity.this,ToonService.class);
MainActivity.this.stopService(toonService);

code的第二片将在同一时间被称为完全地无关的第一张code的。

the second piece of code would be called at a time completly unrelated to the first piece of code.

推荐答案

好吧,假设你只需要该服务的一个实例一次,你可以在服务类,并从任何地点访问它持有一个静态变量运行。示例;

Well, assuming you only want one instance of this service running at once you could hold a static variable in the service class and access it from anywhere. Example;

public class ToonService extends Service{

    public static ToonService toonService;

    public ToonService(){
        toonService = this;
    }
    ...

}

有关ToonService的构造现在存储创建的实例在静态变量 toonService 。现在你可以从任何地方类访问该服务。下面的例子;

The constructor for ToonService now stores the created instance in the static variable toonService. Now you can access that service from anywhere from the class. Example below;

ToonService.toonService.stopSelf();

您也可以通过具有存储类的静态列表运行的实例,而不仅仅是单个实例处理多个实例。 值得注意,当你告诉一个服务停止,你只要求,它已停止。最终,Android操作系统将决定当它被关闭。

You could also handle multiple instances by having the class store a static List of running instances, rather than just the single instance. It is worth noting, that when you tell a service to stop, you are only requesting that it is stopped. Ultimately the Android OS will determine when it is closed.

这篇关于Android的 - 从不同的类停止服务的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆