Android学习--四大组件之一 : Service(一)

来源:互联网 发布:卡尔荣格的书淘宝 编辑:程序博客网 时间:2024/05/30 12:30

服务(Service):

没有用户界面,不需要和用户进行交互,能够在后台长期运行任务。最常见的例子是音乐播放器。

一.定义一个Service

onBind()方法是Service 中唯一的一个抽象方法,所以必须要在子类里实现。然后重写 onCreate()、onStartCommand()和 onDestroy()这三个方法。

public class MyService extends Service {    @Override    public IBinder onBind(Intent intent) {        return null;    }    //服务创建时只调用一次    @Override    public void onCreate() {        super.onCreate();    }    //服务每次启动时都会调用    @Override    public int onStartCommand(Intent intent, int flags, int startId) {        return super.onStartCommand(intent, flags, startId);    }    //服务销毁时调用    @Override    public void onDestroy() {        super.onDestroy();    }}

在AndroidManifest.xml中注册

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

二.启动和停止Service

利用Intent启动和停止Service。

    case 1:    Intent startIntent = new Intent(this, MyService.class);    startService(startIntent); // 启动服务    break;    case 2:    Intent stopIntent = new Intent(this, MyService.class);    stopService(stopIntent); // 停止服务    break;

MyService 的任何一个位置调用 stopSelf()方法就能让这个服务自动停止。

三.Service和Activity通信

1)在Myservice 中创建一个Binder对象,在内部实现方法

class MyBinder extends Binder {    public void start() {        Log.d("MyService", "start");    }    public int stop() {        Log.d("MyService", "stop");        return 0;    }}

2)在Activity创建一个ServiceConnection,在里面重写onServiceConnected()方法和 onServiceDisconnected()方法。

    private MyService.MyBinder MyBinder;    private ServiceConnection connection = new ServiceConnection() {        //在活动与服务解除绑定的时候调用        @Override        public void onServiceDisconnected(ComponentName name) {        }        //在活动与服务成功绑定的时候调用        @Override        public void onServiceConnected(ComponentName name, IBinder service) {            MyBinder = (MyService.MyBinder) service;            MyBinder.start();            MyBinder.stop();        }    };

3)在Activity中绑定Service和解除绑定

        case 1:        Intent bindIntent = new Intent(this, MyService.class);        bindService(bindIntent, connection, BIND_AUTO_CREATE); // 绑定服务        break;        case 2:        unbindService(connection); // 解绑服务        break;

有一起学习的小伙伴,添加微信公众号一起讨论哦!

这里写图片描述

原创粉丝点击