如何从一个活动启动android服务,并在另一个活动中停止服务?

如何从一个活动启动android服务,并在另一个活动中停止服务?,android,service,Android,Service,我需要从活动启动android服务,并停止活动,从其他活动停止服务 欢迎提供任何帮助如何启动/停止android服务 开始服务(意图)或停止服务(意图) 这些函数可以从任何活动调用 如何停止活动?-通过这一点,我理解您需要远离此活动。函数调用 finish() 将从活动堆栈中删除活动。服务框架: public class MyService extends Service { public static final String TAG = "MyServiceTag"; ...

我需要从活动启动android服务,并停止活动,从其他活动停止服务


欢迎提供任何帮助

如何启动/停止android服务

开始服务(意图)
停止服务(意图)

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

如何停止活动?-通过这一点,我理解您需要远离此活动。函数调用

finish()

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

服务框架:

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);
}
这是停止活动的一部分:

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);
}

我需要在活动关闭后继续运行该服务,并且我需要在另一个活动中关闭该服务我不太确定如何停止该服务。您可以从应用程序的任何位置获取静态服务实例来访问它。