Android_6_Service

Android_6_Service

Service(服务)是安卓四大组件之一,是一个没有用户界面的在后台运行执行耗时操作的应用组件,其他应用组件能够启动Service,并且当用户切换到另外的应用场景,Service将持续在后台运行。Service(服务可以脱离前端UI执行在安卓后台,一般这样的service把它叫做后台service,同时service还可以与前端控件绑定运行一般称为前台service,这个的服务会更难被清理,另外一个组件能够绑定到一个service与之进行交互(IPC机制),例如,一个service可能会处理网络操作,播放音乐,操作文件I/O或者与内容提供者(content provider)交互,所有这些活动都是在后台进行。

Service生命周期

Service启动有两种方式,一种是startService,一种是bind,两种启动方式service的生命同期会有一定差异,在Service每一次的开启关闭过程中,只有onStart可被多次调用(通过多次startService调用),其他onCreate,onBind,onUnbind,onDestory在一个生命周期中只能被调用一次。

注:图片引用自博客http://blog.csdn.net/agods/article/details/7468431

定义Service的步骤

1.创建Service.class继承自系统Service类复写方法

    public class ServiceDemo extends Service {
        @Override
        public IBinder onBind(Intent intent) {
            return null;
        }
    }

2.在manifest文件中声名服务,在application节点下添加

    <service android:name=".ServiceDemo">
    </service>
    
    这里name属性也可以是全类名,打点缺省应用包名

3.启动service

    Intent intent= new Intent(context,ServiceDemo.class);
    context.startService(intent);
注意: 前台Service如果20秒之内未结束就会出现ANR,后台Service如果200秒之内未结束就会出现ANR,所以不建议在service里面做太过耗时操作

local service:

启动一个前台服务:

前台服务顾名思意就是把服务在前台上显示出来,也就是把服务和一个前台显示的控件关联在一起,这样做会提高进程的优先级避免进程被杀

复写onStartCommand()方法

    @Override
    public int onStartCommand(Intent intent, int flags, int startId) {
        Log.d(TAG, "onStartCommand()");// 在API11之后构建Notification的方式
        Notification.Builder builder = new Notification.Builder(this.getApplicationContext()); //获取一个Notification构造器
        Intent nfIntent = new Intent(this, MainActivity.class);builder.setContentIntent(PendingIntent.getActivity(this, 0, nfIntent, 0)) // 设置
        PendingIntent.setLargeIcon(BitmapFactory.decodeResource(this.getResources(), R.mipmap.ic_large)) // 设置下拉列表中的图标(大标)
        .setContentTitle("下拉列表中的Title") // 设置下拉列表里的标题
        .setSmallIcon(R.mipmap.ic_launcher) // 设置状态栏内的小图标
        .setContentText("要显示的内容") // 设置上下文内容
        .setWhen(System.currentTimeMillis()); // 设置该通知发生的时间
        Notification notification = builder.build(); // 获取构建好的
        Notificationnotification.defaults = Notification.DEFAULT_SOUND; //设置为默认的声音
    }
启动一个后台服务:
一般是注册一个广播,当接收到广播时,在广播中启动服务

进程间通讯

remote service:

aidl(Android Interface Definition Language)

Android翻译:Android interface definition language(aidl)

在AndroidStudio中使用aidl
最后编辑于
©著作权归作者所有,转载或内容合作请联系作者
平台声明:文章内容(如有图片或视频亦包括在内)由作者上传并发布,文章内容仅代表作者本人观点,简书系信息发布平台,仅提供信息存储服务。

推荐阅读更多精彩内容

  • Android 自定义View的各种姿势1 Activity的显示之ViewRootImpl详解 Activity...
    passiontim阅读 173,217评论 25 708
  • 转载注明出处:http://www.jianshu.com/p/a1d3d9693e91 1. 简介 与前一篇An...
    王三的猫阿德阅读 1,965评论 1 9
  • 上篇我们讲解了Android中的5中等级的进程,分别是:前台进程、可见进程、服务进程、后台进程、空进程。系统会按照...
    徐爱卿阅读 3,886评论 6 33
  • 最近好忙,好忙 脑子一直忙着设计PPT 想设计稿方案 脑髓都捐给公司了 脑子真的只想空洞一下 祝各位好友生活愉快!
    一日蜉蝣君阅读 146评论 4 3
  • 金秋九月,恩,没有播音腔,只是觉得又是新的一天了。 新的一天新开始,只是这个开始的姿势很奇怪。通常我睡觉是很老实的...
    黄姑娘与高先生的日常阅读 117评论 0 0