Android的Service的创建与使用

Service介绍

Service是Android四大组件中与Activity最为相似的组件,它们都代表可执行的程序,
区别是:Service一直在后台运行,没有用户界面。
使用service要向Activity一样,要在AndroidManifest.xml文件中进行配置。

Service也具有自己的生命周期,下面通过一个简单的程序进行展示

public class FirstService extends Service {
    @Nullable
    @Override
    //想要使用Service必须实现这个方法,该方法返回一个IBinder对象
    //应用程序使用这个对象与Service组件进行通信
    public IBinder onBind(Intent intent) {
        return null;
    }

    //Service被创建的时候回调onCreate方法
    public void onCreate(){
        super.onCreate();
        System.out.println("Service is Created");
    }

    //Service被启动的时候回调onStartCommand方法
    public int onStartCommand(Intent intent, int flags, int startId){
        System.out.println("Service is Started");
        return START_STICKY;
    }

    //Service被销毁的时候回调onDestroy方法
    public void onDestroy(){
        super.onDestroy();
        System.out.println("Service is Destroyed");
    }
}

想要使用Service必须在AndroidManifest.xml文件中进行配置,如下

<service android:name=".FirstService"/>

Service的启动

接下来使用一个例子启动之前的那个Service的使用,这个程序布局只有两个按钮,这里省略,代码如下:

public class MainActivity extends AppCompatActivity {
    Button start,stop;
    
    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);
        start = (Button) findViewById(R.id.start);
        stop = (Button) findViewById(R.id.stop);
        final Intent intent = new Intent(this , FirstService.class);
        start.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                //启动Service
                startService(intent);
            }
        });
        stop.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                //停止Service
                stopService(intent);
            }
        });
    }
}

可以看到,调用startService()方法与stopService()方法就可以启动、关闭Service

Service的绑定

接下来的一个实例是绑定本地Service并进行通信
界面的代码如下:

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

    <Button
        android:id="@+id/bind"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:text="绑定SERVICE"/>

    <Button
        android:id="@+id/unbind"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:text="解除绑定SERVICE"/>

    <Button
        android:id="@+id/getServiceStatus"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:text="获取SERVICE状态"/>
</LinearLayout>

可以看到界面很简单,只是三个按钮,分别的功能是绑定Service,
解除绑定Service,获取Service状态

Service类的代码如下:

public class BindService extends Service{
    private int count;
    private boolean quit;
    private MyBinder binder = new MyBinder();
    //用MyBinder继承Binder来实现IBinder类
    public class MyBinder extends Binder
    {
        public int getCount()
        {
            return count;
        }
    }
    @Override
    public IBinder onBind(Intent intent) {
        System.out.println("Service is Binded");
        return binder;
    }

    public void onCreate(){
        super.onCreate();
        System.out.println("Service is Created");
        //Service被创建后,启动一条线程,动态修改count的值
        new Thread()
        {
            public void run(){
                while (!quit){
                    try{
                        Thread.sleep(1000);
                    }
                    catch (InterruptedException e){
                    }
                    count++;
                }
            }
        }.start();
    }

    public boolean onUnbind(Intent intent)
    {
        System.out.println("Service isUnbinded");
        return true;
    }
    public void onDestroy(){
        super.onDestroy();
        this.quit = true;
        System.out.println("Service is Destroyed");
    }
}

然后是Activity的代码:

public class MainActivity extends AppCompatActivity {
    Button bind, unbind, getServiceStatus;
    BindService.MyBinder binder;

    private ServiceConnection conn = new ServiceConnection() {
        @Override
        public void onServiceConnected(ComponentName name, IBinder service) {
            System.out.println("--Service Connected--");
            binder = (BindService.MyBinder) service;
        }

        @Override
        public void onServiceDisconnected(ComponentName name) {
            System.out.println("--Service Disconnected--");
        }
    };
    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);
        bind = (Button) findViewById(R.id.bind);
        unbind = (Button) findViewById(R.id.unbind);
        getServiceStatus = (Button) findViewById(R.id.getServiceStatus);
        //创建启动Service的Intent
        final Intent intent = new Intent(this,BindService.class);
        //按钮bind的监听事件,绑定Service
        bind.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                bindService(intent, conn, Service.BIND_AUTO_CREATE);
            }
        });
        //按钮unbind的监听事件,解除绑定Service
        unbind.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                unbindService(conn);
            }
        });
        //按钮getServiceStatus的监听事件,在Service与Activity之间传递数据
        getServiceStatus.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                Toast.makeText(MainActivity.this, "Service的count值为:" +
                binder.getCount() ,Toast.LENGTH_SHORT).show();
            }
        });
    }
}

在Activity绑定了Service后,通过Service里的getCount方法,得到了Service的count值。
运行程序之后,点击绑定按钮,logcat里依次输出了

Service is Created、Service is Binded、Service Connected
再点击获取状态按钮,程序使用Toast显示出了随机数count

最后点击解除绑定按钮,logcat里依次输出了
Service is Unbinded、Service is Destroyed

两种运行Service的方式的总结

以上就是两种运行Service的方式,分别是startService()方法和bindService()方法
使用startService()方法启动Service时,访问者与Service之间没有关联,访问者退出后Service也会继续运行,
使用bindService()方法启动Service是,访问者与Service绑定在一起,访问者退出后,Service就会终止。

Service的生命周期补充

使用startService时:onCreate()→onStartCommand()→Service运行中→onDestroy()→Service被关闭
使用bindService时:onCreate()→onBind()→绑定了Service→onUnbind()→onDestroy()→Service被关闭

接下来是一种特殊情况,Service先被startService()方法启动,再被bindService方法绑定,又被解除,又再被绑定
这时所触发的生命周期方法如下:onCreate(),onStartCommand(),onBind(),onUnBind,onRebind()
可以看到这种情况下回调了onRebind()方法。并且这种情况下并没有回调过onDestroy()方法,因为
这个时候Service已经被Activity的startService方法启动过了,所以在解除绑定时Service不会终止。

原文地址:https://www.cnblogs.com/vonzc/p/10565620.html