关于Service各种知识点总结

作者: 奔跑吧李博 | 来源:发表于2018-12-28 11:27 被阅读12次
    Service生命周期:
    启动模式:
    1.Start方式:

    启动后在后台单独执行,不给组件返回结果
    调用onstartCommand,需要调用stopService才能停止service

    2.Bind方式:

    可与绑定的组件进行交互
    Service可与多个组件绑定,不再与任何绑定才会destroy.
    Service不是新的线程,也不是新的进程

    • 若您需要在Service中执行较为耗时的操作(如播放音乐、执行网络请求等),需要在Service中创建一个新的线程Thread还是使用Service?

    看是否需要与用户交互,要交互用thread,不交互可用service。

    • IntentService默认启动子线程,操作完成后无需调用stop,onHandleIntent()会自动调用该方法

    • 启动service:
      Intent intent = new Intent(this,MyIntentService.class);
      与activity启动方式类似,startService(intent);

    • 前台service:
      前台Service用于动态通知消息,如天气预报。该Service不易被kill。
      一个播放音乐的Service必须是前台Service,只有这样用户才能确知其运行状态

    • service调用的各种方法:


    • service连接回调:


    Service启动方式

    1.Service的第一种启动方式,采用start的方式开启服务

    1.定义一个类继承Service
    2.在Manifest.xml文件中配置该Service
    3.使用Context的startService(Intent)方法启动该Service
    4.不再使用时,调用stopService(Intent)方法停止该服务

    使用这种start方式启动的Service的生命周期如下:
    onCreate()--->onStartCommand() ---> onDestory()

    特点:一旦服务开启跟调用者(开启者)就没有任何关系了。
    开启者退出了,开启者挂了,服务还在后台长期的运行。
    开启者不能调用服务里面的方法。

    2.Service的第二种启动方式,采用bind的方式开启服务

    1.定义一个类继承Service
    2.在Manifest.xml文件中配置该Service
    3.使用Context的bindService(Intent, ServiceConnection, int)方法启动该Service
    4.不再使用时,调用unbindService(ServiceConnection)方法停止该服务

    使用这种start方式启动的Service的生命周期如下:
    onCreate() --->onBind()--->onunbind()--->onDestory()

    特点:bind的方式开启服务,绑定服务,调用者挂了,服务也会跟着挂掉。
    绑定者可以调用服务里面的方法。

    启动过程代码:
    public class MainActivity extends Activity {
    
        private MyConn conn;
        private Intent intent;
        private IMyBinder myBinder;
    
        @Override
        protected void onCreate(Bundle savedInstanceState) {
            super.onCreate(savedInstanceState);
            setContentView(R.layout.activity_main);
        }
    
        //开启服务按钮的点击事件
        public void start(View view) {
            intent = new Intent(this, MyService.class);
            conn = new MyConn();
            //绑定服务,
            // 第一个参数是intent对象,表面开启的服务。
            // 第二个参数是绑定服务的监听器
            // 第三个参数一般为BIND_AUTO_CREATE常量,表示自动创建bind
            bindService(intent, conn, BIND_AUTO_CREATE);
        }
    
        //调用服务方法按钮的点击事件
        public void invoke(View view) {
            myBinder.invokeMethodInMyService();
        }
    
        private class MyConn implements ServiceConnection {
            @Override
            public void onServiceConnected(ComponentName componentName, IBinder iBinder) {
                //iBinder为服务里面onBind()方法返回的对象,所以可以强转为IMyBinder类型
                myBinder = (IMyBinder) iBinder;
            }
    
            @Override
            public void onServiceDisconnected(ComponentName componentName) {
            }
        }
    }
    

    关于Service其它问题

    • IntentService与Service的区别

    Service做耗时操作容易引起ANR,所以创造一个IntentService是处理异步请求的一个类,在IntentService内有一个工作线程来处理耗时操作,启动IntentService的方式和启动传统的Service一样,同时,当任务执行完后,IntentService会自动停止,而不需要我们手动去控制或stopSelf()。

    • Service怎么保证在后台不被杀死?

    重写onStartCommand()方法,将flags设置START_STICKY,服务被杀死之后系统会重新创建服务。

        @Override
        public int onStartCommand(Intent intent, int flags, int startId) {
            flags = START_STICKY;
            return super.onStartCommand(intent, flags, startId);
        }
    
    • 如何在service中弹出对话框

    Service中可以弹出对话框。比如当监听到电量变化,监听到接收短信,用Service监听,然后在Service中弹出对话框。

    AlertDialog.Builder alertDialog = new AlertDialog.Builder(this);
                alertDialog.setMessage("有新消息,是否查看?");
                alertDialog.setPositiveButton("否",
                        new DialogInterface.OnClickListener()
                        {
                            public void onClick(DialogInterface dialog, int which)
                            {
                            }
                        });
        
                alertDialog.setNegativeButton("是",
                        new DialogInterface.OnClickListener()
                        {
                            public void onClick(DialogInterface dialog, int which)
                            {
                            }
                        });
        
                ad = alertDialog.create();
                
                ad.getWindow().setType(WindowManager.LayoutParams.TYPE_SYSTEM_ALERT);  
                ad.setCanceledOnTouchOutside(false);//点击外面区域不会让dialog消失                               
                ad.show();
    

    关键点是要给dialog添加setType(WindowManager.LayoutParams.TYPE_SYSTEM_ALERT),类型是系统弹框。并加入系统弹框的权限。

    <uses-permission android:name="android.permission.SYSTEM_ALERT_WINDOW" />
    

    相关文章

      网友评论

        本文标题:关于Service各种知识点总结

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