【问题标题】:How to start a android service from one activity and stop service in another activity?如何从一个活动启动 android 服务并在另一个活动中停止服务?
【发布时间】:2011-09-17 11:29:18
【问题描述】:

我需要从 Activity 启动一个 android 服务并停止该 Activity 并从其他 Activity 停止服务。

任何帮助将不胜感激

【问题讨论】:

标签: android service


【解决方案1】:

服务框架:

public class MyService extends Service {
    public static final String TAG = "MyServiceTag";
    ...
}

这是开始活动的一部分:

processStartService(MyService.TAG);

private void processStartService(final String tag) {
    Intent intent = new Intent(getApplicationContext(), MyService.class);
    intent.addCategory(tag);
    startService(intent);
}

这是停止活动的一部分:

processStopService(MyService.TAG);

private void processStopService(final String tag) {
    Intent intent = new Intent(getApplicationContext(), MyService.class);
    intent.addCategory(tag);
    stopService(intent);
}

【讨论】:

    【解决方案2】:

    如何启动/停止a​​ndroid服务?

    startService(intent)stopService(intent)

    可以从任何活动中调用这些函数。

    如何停止活动? - 据我了解,您需要远离此活动。函数调用

    finish()

    将从活动堆栈中删除活动。

    【讨论】:

    • 即使在活动关闭后我也需要继续运行服务,并且我需要在另一个活动中关闭服务
    • 我不太确定如何停止此服务。也许您可以使用静态服务实例从应用程序的任何位置访问它。
    猜你喜欢
    • 2015-11-02
    • 2012-03-28
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2023-04-05
    • 1970-01-01
    相关资源
    最近更新 更多