android Sevice详解

写了这么久代码了,每次到写服务的时候总会忘记怎么写,那我就把你记到这里,这下忘记了就不会到处翻别人的博客了。

先上图,有图有真相,先上从别人那里盗来的生命周期图


启动服务用三种方式:

1,startService

2,bindService

3,startService和bindService连用

各个模式的区别

1,startService启动的生命周期

onCreate()——>onStart()(onStartCommand ()替代,onStart()过时)——>serviece is running——>onDestroy()

这种方法启动的服务是不受Activity的生命周期的影响,Activity消失过后服务依然运行


2,bindService启动的生命周期

onCreate()——>onBind()——> servieceis running——>onUnBind()——>onDestroy()

这种方法启动的服务是受Activity的生命周期的影响,Activity消失过后服务也就销毁。

同时这个种启动方式Activity里面可以操控Sevice,进行操作

3,startService和bindService连用启动

如果你既想操作service又想在Activity退出过后service依然在运行,该怎么办呢,上面两张方法都不合适

那就可以调用startService和bindService一起就能达到效果。

贴上测试的代码,自己去操作一下就会懂得,看打印就会了。

StartBindService

package come.xiaoke.growing.service;

import android.app.Service;
import android.content.Intent;
import android.os.Binder;
import android.os.IBinder;
import android.support.annotation.Nullable;
import android.util.Log;

public class StartBindService extends Service {
    private int numberStart = 0;
    private int numberBind = 0;
    private boolean run = true;

    @Override
    public void onCreate() {
        super.onCreate();
        numberStart = numberStart + 5;
        numberBind = numberBind + 5;
        Log.e("StartBindService", "onCreate");
    }

    public class BindBinder extends Binder {
        StartBindService getService() {
            return StartBindService.this;
        }
    }


    @Override
    public int onStartCommand(Intent intent, int flags, int startId) {

        new Thread(
                new Runnable() {
                    @Override
                    public void run() {
                        while (run) {

                            Log.e("StartBindService", "start:" + numberBind++);

                            try {
                                Thread.sleep(1000);
                            } catch (InterruptedException e) {
                                e.printStackTrace();
                            }
                        }
                    }
                }

        ).start();


        Log.e("StartBindService", "onStartCommand");

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

    private final IBinder mBinder = new BindBinder();

    @Nullable
    @Override
    public IBinder onBind(Intent intent) {

        new Thread(
                new Runnable() {
                    @Override
                    public void run() {
                        while (run) {

                            Log.e("StartBindService", "bind:" + numberStart++);

                            try {
                                Thread.sleep(1000);
                            } catch (InterruptedException e) {
                                e.printStackTrace();
                            }
                        }
                    }
                }

        ).start();


        Log.e("StartBindService", "onBind");
        return mBinder;
    }

    public void stop() {
        run = false;
    }

    @Override
    public boolean onUnbind(Intent intent) {
        Log.e("StartBindService", "onUnbind");
        return super.onUnbind(intent);
    }

    @Override
    public void onDestroy() {

        Log.e("StartBindService", "onDestroy");
        super.onDestroy();
    }
}

ServiecActivity

package come.xiaoke.growing.service;

import android.app.Activity;
import android.content.ComponentName;
import android.content.Context;
import android.content.Intent;
import android.content.ServiceConnection;
import android.os.Bundle;
import android.os.IBinder;
import android.view.View;

import come.xiaoke.growing.R;

public class ServiecActivity extends Activity implements View.OnClickListener {

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_serviec);
        findViewById(R.id.btn_start).setOnClickListener(this);
        findViewById(R.id.btn_bind).setOnClickListener(this);
        findViewById(R.id.btn_stop).setOnClickListener(this);
    }


    @Override
    public void onClick(View v) {
        switch (v.getId()) {
            case R.id.btn_start:

                Intent intent = new Intent(this, StartBindService.class);

                startService(intent);

                break;
            case R.id.btn_bind:
                Intent intent1 = new Intent(this, StartBindService.class);
                bindService(intent1, mConnection, Context.BIND_AUTO_CREATE);
                break;

            case R.id.btn_stop:
                if (mBoundService != null)
                    mBoundService.stop();
                break;
        }
    }


    private StartBindService mBoundService;

    //service和Activity交互的桥梁
    private ServiceConnection mConnection = new ServiceConnection() {
        public void onServiceConnected(ComponentName className, IBinder service) {

            mBoundService = ((StartBindService.BindBinder) service).getService();


        }

        public void onServiceDisconnected(ComponentName className) {

            mBoundService = null;

        }
    };


    @Override
    protected void onDestroy() {
        super.onDestroy();
        if (mBoundService != null)
            unbindService(mConnection);
    }


}

xml

<?xml version="1.0" encoding="utf-8"?>
<ScrollView xmlns:android="http://schemas.android.com/apk/res/android"
    android:layout_width="match_parent"
    android:layout_height="match_parent">

    <LinearLayout
        android:layout_width="match_parent"
        android:layout_height="match_parent"
        android:orientation="vertical">

        <Button
            android:id="@+id/btn_start"
            android:layout_width="match_parent"
            android:layout_height="wrap_content"
            android:text="StartService" />

        <Button
            android:id="@+id/btn_bind"
            android:layout_width="match_parent"
            android:layout_height="wrap_content"
            android:text="BindService" />

        <Button
            android:id="@+id/btn_stop"
            android:layout_width="match_parent"
            android:layout_height="wrap_content"
            android:text="停止计算" />

    </LinearLayout>

</ScrollView>
不容易啊,又复习了一次service,下面是最重要的来了,所以放最后面,就是service是工作在主线程也就是UI线程的,不能做耗时操作,如果你不相信可以去试一下,你的程序会没响应哦。



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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值