Android_6_Service

作者: icechao | 来源:发表于2017-06-26 17:42 被阅读0次

    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_6_Service

        本文链接:https://www.haomeiwen.com/subject/dlpmattx.html