安卓第十二章 service

安卓service是安卓四大组件之一,是在后台运行的一个不可见的服务,比如后台检查是否有更新,后台进行一些下载任务等。
service和activity一样,都运行在主线程上,切忌service并不是一个异步线程额,所以如果需要在service里进行一些耗时操作,需要单开一个线程处理。

下面我们创建一个service。

public class MyService extends Service {
    public MyService() {
    }

    @Override
    public void onCreate() {
        super.onCreate();
    }

    @Override
    public IBinder onBind(Intent intent) {
        // TODO: Return the communication channel to the service.
        throw new UnsupportedOperationException("Not yet implemented");
    }

    @Override
    public int onStartCommand(Intent intent, int flags, int startId) {
        return super.onStartCommand(intent, flags, startId);
    }
}

manifest中

 <service
            android:name=".MyService"
            android:enabled="true"
            android:exported="true"></service>

首次创建服务时,系统会调用onCreate方法,每次通过startService()方法启动Service时都会调用onStartCommand方法。

开启service方法:

 Intent intent = new Intent(this, MyService.class);
 startService(intent)

停止service方法:

Intent intent_stop = new Intent(this, MyService.class);
stopService(intent_stop);
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值