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

Ran*_*ock 8 service android

我需要从活动启动Android服务并停止活动并停止其他活动的服务.

任何帮助将不胜感激

Har*_*elm 29

服务骨架:

public class MyService extends Service {
    public static final String TAG = "MyServiceTag";
    ...
}
Run Code Online (Sandbox Code Playgroud)

这是开始活动的一部分:

processStartService(MyService.TAG);

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

这是停止活动的一部分:

processStopService(MyService.TAG);

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


Sha*_*afi -2

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

startService(intent)或者stopService(intent)

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

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

finish()

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