使用Action启动/关闭Service

本文介绍了在Android应用中如何使用Intent及Action参数来控制Service的启动和关闭。通过在manifest文件中为Service设置特定的Action,并在Service类中定义静态常量来引用该Action,可以简化Service的控制流程。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

前面有用使用Intent来控制  Service

使用的参数是Service的类

Service的启动/关闭还有另外一种方式来控制

通过Intent传入Action的参数

 

 

在manifest中注册一个Service并且设置一个action

<service     
            android:enabled="true" 
            android:exported="false"
            android:name="com.services.sev.PlayService" >
            <intent-filter>
                <action android:name="com.example.codetest_1.action.startPlayService" />
            </intent-filter>
        </service>

注意这个name的字符串

可以在Service类中增加一个字段

public static final String ACTION = "com.example.codetest_1.action.startPlayService";

这样 只需修改Intent的调用方法 就可以启动/关闭Service了

Intent intent = new Intent();
            intent.setAction(PlayService.ACTION);
            this.startService(intent);
Intent intent = new Intent();
            intent.setAction(PlayService.ACTION);
            this.stopService(intent);

 

转载于:https://www.cnblogs.com/chenlong-50954265/p/5394248.html

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值