Services服务(启动)

今天抽点时间来讲Services服务,什么事服务呢,大家应该联想到生活中很多的服务,对的,我们这个服务简单来说和生活中的服务也一样的,Services是一个可以在后台执行长时间运行操作而不是提供用户的应用界面,服务仍将在后台继续运行,服务基本上分为两种方式,1,启动。2,绑定。今天我们就来讲讲启动,接下来执行下面的操作

首先配服务

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

要通过Activity来启动服务

protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);
        intent = new Intent(this,MyServices2.class);

    }

    public void start(View view){
        intent.putExtra("data","下载的路径");
        startService(intent);

    }

    public void stop(View view){
        stopService(intent);

    }

Services有四大生命周期还有启动的一些操作

public IBinder onBind(Intent intent) {
        Log.i("test", "onBind");
        return null;
    }

    @Override
    public void onCreate() {
        super.onCreate();
        Log.i("test", "onCreate");
    }

    @Override
    public int onStartCommand(Intent intent, int flags, int startId) {
       String data=intent.getStringExtra("data");

        Log.i("test", "onStartCommand"+data);

        //ANR:application not responsing应用程序未响应
        new MyThread(startId).start();


        return super.onStartCommand(intent, flags, startId);
    }

    class MyThread extends Thread {
        private int startId;

        public MyThread(int startId) {
            this.startId = startId;
        }

        @Override
        public void run() {
            super.run();
            for (int i = 0; i < 10; i++) {
                Log.i("test", "i=" + i);
                SystemClock.sleep(1000);
            }
            //停止服务
            // stopSelf();//当第一个线程执行完毕,则会停止服务

            //所有的线程都执行完毕,才停止服务
            stopSelf(startId);

        }
    }


    @Override
    public void onDestroy() {
        super.onDestroy();
        Log.i("test", "onDestroy");
    }

服务停止有两种方式
startId:代表启动服务的次数,由系统生成。
stopSelf(int startId):
在其参数startId跟最后启动该service时生成的ID相等时才会执行停止服务。
stopSelf():直接停止服务。

使用场景:
如果同时有多个服务启动请求发送到onStartCommand(),不应该在处理完一个请求后调用stopSelf();因为在调用此函数销毁service之前,可能service又接收到新的启动请求,如果此时service被销毁,新的请求将得不到处理。此情况应该调用stopSelf(int startId)。请参见:IntentService

`
stopService
stopSelf
stopSelf()
stopSelf(id)

Services也有两种的继承方式然后他们最大的区别就是在这里面可以直接写耗时操作,还有一个区别就是onHandleIntent是有顺序的,onStartCommand是无序的
`

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值