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

来源:互联网 发布:长城网络还原怎么卸载 编辑:程序博客网 时间:2024/05/30 23:04

四.Service的生命周期

Service的生命周期,从它被创建开始,到它被销毁为止,可以有两条不同的路径:

A started Service

  启动的Service通过其他组件调用 startService()被创建。

  这种Service可以无限地运行下去,必须调用stopSelf()方法或者其他组件调用stopService()方法来停止它。

  当Service被停止时,系统会销毁它。

A bound Service

  被绑定的service是当其他组件(一个客户)调用bindService()来创建的。

  客户可以通过一个IBinder接口和Service进行通信。

  客户可以通过 unbindService()方法来关闭这种连接。

  一个Service可以同时和多个客户绑定,当多个客户都解除绑定之后,系统会销毁service。

这里写图片描述

  • 一个被开启的Service仍然可能被绑定。

Service整体的生命时间是从onCreate()被调用开始,到onDestroy()方法返回为止。
和activity一样,service在onCreate()中进行它的初始化工作,在onDestroy()中释放残留的资源。
比如,一个音乐播放service可以在onCreate()中创建播放音乐的线程,在onDestory()中停止这个线程。
onCreate() 和 onDestroy()会被所有的service调用,不论service是通过startService()还是bindService()建立。

五.前台Service

1)前台服务
服务几乎都是在后台运行的,服务的系统优先级还是比较低的,当系统出现内存不足的情况时,就有可能会回收掉正在后台运行的服务。如果你希望服务可以一直保持运行状态,而不会由于系统内存不足的原因导致被回收,就可以考虑使用前台服务。前台服务和普通服务最大的区别就在于,它会一直有一个正在运行的图标在系统的状态栏显示,下拉状态栏后可以看到更加详细的信息,非常类似于通知的效果。当然有时候你也可能不仅仅是为了防止服务被回收掉才使用前台服务的,有些项目由于特殊的需求会要求必须使用前台服务,比如说天气,它的服务在后台更新天气数据的同时,还会在系统状态栏一直显示当前的天气信息。

2)前台服务创建

    Intent intent=new Intent(this,MainActivity.class);    PendingIntent pi=PendingIntent.getActivity(this,0,intent,0);//创建通知,使用NotificationCompat能支持所有版本Notification notification=new NotificationCompat.Builder(this)        .setContentTitle("Title")        .setContentText("Message")        .setSmallIcon(R.mipmap.ic_launcher)        .setWhen(System.currentTimeMillis())        .setLargeIcon(BitmapFactory.decodeResource(getResources(),R.mipmap.ic_launcher))        .setContentIntent(pi)        .build();        //将Service变成前台服务并显示出来        startForeground(1, notification);

六IntentService

Service的任务默认是在主线程里面运行的,当直接处理的复杂逻辑任务过多时,系统容易出现ANR(应用无响应)的情况,所以Android 多线程编程是时候出场了。

    public class MyService extends Service {        @Override        public IBinder onBind(Intent intent) {            return null;        }        @Override        public int onStartCommand(Intent intent, int flags, int startId) {            new Thread(new Runnable() {                @Override                public void run() {                // 处理具体的逻辑                //线程执行完自动关闭                stopSelf();                }            }).start();            return super.onStartCommand(intent, flags, startId);        }    }

而学习的IntentService更加方便,不需要去调用stopSelf()方法来关闭Service,能够自动关闭。

  public class MyIntentService extends IntentService {        public MyIntentService() {            super("MyIntentService"); // 调用父类的有参构造函数        }        //onHandleIntent()方法在子线程中运行        @Override        protected void onHandleIntent(Intent intent) {        }        @Override        public void onDestroy() {            super.onDestroy();            Log.d("pipa", "onDestroy");        }    }
Intent intentService = new Intent(this, MyIntentService.class);//启动服务startService(intentService);

Service的基本内容学习到这里了,关于Service的进阶知识在以后的学习中深入了解。

原创粉丝点击