Service基础(一)---》使用服务Service

来源:互联网 发布:web前端连接数据库 编辑:程序博客网 时间:2024/05/16 01:23

服务(Service)是Android四大组件之一,是Android实现程序后台运行的解决方案,很适合执行那些不需要和用户交互而且还要长期运行的任务,所以服务不依赖于任何用户界面。当程序被切换到后台,或者用户打开一个新的应用程序,服务依然运行。最明了的例子就是音乐播放器了,还有网络下载数据!

但要注意的一点是:启动一个服务时,系统会重新开启一个进程,它依赖于创建服务时所在的应用程序进程。当某个应用程序进程被杀掉时,所有依赖于该进程的服务也会停止运行。

下面是和威哥学习写音乐播放器的一个服务的例子:(目前是初步代码,后面还会完善)

public class PlayService extends Service {    private MediaPlayer mPlayer;    private int currentPostion;  //表示当前正在播放的歌曲的位置    ArrayList<Mp3Info> mp3Infos;    private MusicUpdateListener musicUpdateListener;    public PlayService() {    }    public class PlayBinder extends Binder {        public PlayService getPlayService() {            return PlayService.this;        }    }    @Override    public IBinder onBind(Intent intent) {        // TODO: Return the communication channel to the service.//        throw new UnsupportedOperationException("Not yet implemented");        return new PlayBinder();    }    @Override    public void onCreate() {        super.onCreate();        mPlayer = new MediaPlayer();        mp3Infos = MediaUtils.getMp3Infos(this);    }    //播放    public void play(int position) {        if (position>=0 && position<mp3Infos.size()) {            Mp3Info mp3Info = mp3Infos.get(position);            try {                mPlayer.reset();                mPlayer.setDataSource(this, Uri.parse(mp3Info.getUrl()));                mPlayer.prepare();                mPlayer.start();                currentPostion = position;            } catch (IOException e) {                e.printStackTrace();            }        }    }    //暂停    public void pause() {        if (mPlayer.isPlaying()) {            mPlayer.pause();        }    }    //上一首    public void prev() {        if (currentPostion <= 0) {            currentPostion = mp3Infos.size()-1;        } else {            currentPostion--;        }        play(currentPostion);    }    //下一首    public void next() {        if (currentPostion >= mp3Infos.size()-1) {            currentPostion = 0;        } else {            currentPostion++;        }        play(currentPostion);    }    //点击暂停后再点播放    public void start() {        if (mPlayer!=null && !mPlayer.isPlaying()) {            mPlayer.start();        }    }    public int getDuration() {        return mPlayer.getDuration();    }    //更新状态的接口    public interface MusicUpdateListener {        public void onPublish(int progress);  //更新进度条        public void onChange(int position);  //更改界面信息    }    public void setMusicUpdateListener(MusicUpdateListener musicUpdateListener) {        this.musicUpdateListener = musicUpdateListener;    }}
我们发现,定义一个服务就是去继承Service类,这是一个抽象类。其中有一些重要的方法需要我们去重写实现。我们先从简单的开始介绍:

1.public void onCreate(){}   //服务创建时调用

2.public int onStartCommand(Intent intent, int flags, int startId) {}          //服务每次启动时调用。注意创建和启动是两码事。就像造汽车和启动汽车是两码事一样

3.public void onDestroy() {}   //服务销毁时调用,回收那些不再使用的资源

4.public IBinder onBind(Intent intent) {}  //这一个方法很重要,后面介绍

而且服务要在AndroidManifest.xml中注册才会生效!!

例如:

        <service            android:name=".touch.zjzplayer.service.PlayService"            android:enabled="true"            android:exported="true" >        </service>
android:exported属性:

这个属性用于指示该服务是否能够被其他应用程序组件调用或跟它交互。如果设置为true,则能够被调用或交互,否则不能。设置为false时,只有同一个应用程序的组件或带有相同用户ID的应用程序才能启动或绑定该服务。 它的默认值依赖与该服务所包含的过滤器。没有过滤器则意味着该服务只能通过指定明确的类名来调用,这样就是说该服务只能在应用程序的内部使用(因为其他外部使用者不会知道该服务的类名),因此这种情况下,这个属性的默认值是false。另一方面,如果至少包含了一个过滤器,则意味着该服务可以给外部的其他应用提供服务,因此默认值是true。 这个属性不是限制把服务暴露给其他应用程序的唯一方法。还可以使用权限来限制能够跟该服务交互的外部实体。

我们定义好了服务,那么如何启动服务呢?

服务不会自己启动,我们要在Activity里面去启动服务。启动服务同样是通过Intent实现

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

停止服务也很简单,也是通过Intent

            Intent intent = new Intent(this, PlayService.class);            stopService(intent);

但是我们发现我们在Activity中启动了服务,然后活动和服务就毫无关系了,服务做自己的事情,活动里面也无法对服务进行控制,这怎么可以?就像生了孩子,没法管孩子一样!那怎么让这个孩子听话?这就要靠SonBind()方法了。bind的意思是捆绑,约束。

就拿一开始音乐播放器为例,我们服务启动的时候,我们要创建一个MediaPlayer()实例,还要给保存音乐信息的链表赋值,还要设置一个进行更新状态(比如进度)的监听器(监听器实际上就是实现了某个接口的实例对象),而且我们要能控制它进行上一首、下一首等切换。这时候我们需要在活动中可以拿到已经创建了的Service实例,从而对它进行控制。那么如何拿到呢?在onBind()方法里返回这个实例:(未完待续)



0 0
原创粉丝点击
热门问题 老师的惩罚 人脸识别 我在镇武司摸鱼那些年 重生之率土为王 我在大康的咸鱼生活 盘龙之生命进化 天生仙种 凡人之先天五行 春回大明朝 姑娘不必设防,我是瞎子 孩子体温34度多怎么办 宝宝感冒咳嗽流鼻涕出汗怎么办 养的小鸡总打架怎么办 小鸡一条腿瘸了怎么办 同窝小斗鸡打架怎么办 夏季羊长的慢怎么办 1岁吃母乳不吃饭怎么办 5个月宝宝黏妈妈怎么办 九个月宝宝不爱吃饭怎么办 20个月宝宝吐了怎么办 十个月的宝宝消化不好怎么办 两岁宝宝不爱喝水怎么办 两岁宝宝不爱喝水吃饭怎么办 两岁的宝宝不爱喝水怎么办 宝宝不爱吃饭不爱喝水怎么办 一多半宝宝爱喝水 不爱吃饭怎么办 1岁宝宝不爱吃饭喝水怎么办 两岁小宝宝不爱吃饭怎么办 4个月小宝宝咳嗽怎么办 3个月小宝宝咳嗽怎么办 2个月小宝宝咳嗽怎么办 8的岁儿童腿不直怎么办 作业盒子选错年级怎么办 两岁x型腿怎么办 绿萝叶子有水滴怎么办 打游戏变菜了怎么办 车被记号笔画了怎么办 水溶性彩铅受潮了怎么办 马克笔颜色涂深了怎么办 染发膏染眉毛了怎么办 用电容笔画画手有触感怎么办 CAD画图线性数字不居中怎么办 3d立体画笔堵塞怎么办 龋齿树脂填充老化后怎么办 小孩补过的牙疼怎么办 颜料弄到墙纸上怎么办 4岁的宝宝不爱涂色怎么办 oppo手机截图存不到相册怎么办 做的ih5保存不了怎么办 小偷偷东西发现后逃跑了怎么办? 网上有人传迷信诅咒怎么办