安卓之service常用用法详解

来源:互联网 发布:网络安全法第二十七条 编辑:程序博客网 时间:2024/06/06 03:23

安卓一直是半吊子水平,在写一个小东西时,发现自己对service的理解还不够,特总结如下:

service的创建

public class MinaService extends Service{    private ConnectionThread thread;    @Override    public void onCreate() {        super.onCreate();        thread = new ConnectionThread("mina", getApplicationContext());        thread.start();        Log.i("tag", "启动线程尝试连接");    }    @Override    public int onStartCommand(Intent intent, int flags, int startId) {        return super.onStartCommand(intent, flags, startId);    }    @Override    public void onDestroy() {        super.onDestroy();        thread.disConnect();        thread=null;    }    @Nullable    @Override    public IBinder onBind(Intent intent) {        return null;    }    class ConnectionThread extends HandlerThread{        private Context context;        boolean isConnection;        ConnectionManager mManager;        public ConnectionThread(String name, Context context){            super(name);            this.context = context;            //初始化连接配置信息            ConnectionConfig config = new ConnectionConfig.Builder(context)                    .setIp("10.101.252.112")                    .setPort(9555)                    .setReadBufferSize(10240)                    .setConnectionTimeOut(10000).builder();            //根据哦配置信息,生成连接管理类            mManager = new ConnectionManager(config);        }        @Override        protected void onLooperPrepared() {            while(true){                isConnection = mManager.connect();                if(isConnection){                    Log.i("tag", "连接成功");                    break;                }                try {                    Log.i("tag", "尝试重新连接");                    Thread.sleep(3000);                } catch (InterruptedException e) {                    e.printStackTrace();                }            }        }        public void disConnect(){            mManager.disConnect();        }    }}

在manifest注册service

这一点一定别忘了,今天写了服务但是没注册,怎么调都没有结果,引以为戒

Services的两种启动形式

  1. 有其他组件发起

    其他组件调用startService()方法启动一个Service。

Intent intent = new Intent(MainActivity.this, MinaService.class);startService(intent);
 一旦启动,Service将一直运行在后台(run in the background indefinitely)即便启动Service的组件已被destroy。通常,一个被start的Service会在后台执行单独的操作,也并不给启动它的组件返回结果。比如说,一个start的Service执行在后台下载或上传一个文件的操作,完成之后,Service应自己停止。

2. 列表内容

其他组件调用bindService()方法绑定一个Service。

通过绑定方式启动的Service是一个client-server结构,该Service可以与绑定它的组件进行交互。一个bound service仅在有组件与其绑定时才会运行(A bound service runs only as long as another application component is bound to it),多个组件可与一个service绑定,service不再与任何组件绑定时,该service会被destroy

service的访问

无论通过那种方式启动service(start、bind、start&bind),任何组件(甚至其他应用的组件)都可以使用service。并通过Intent传递参数。也可以将Service在manifest文件中配置成私有的,不允许其他应用访问

容易忽略的一个问题

Service运行在主线程中(A service runs in the main thread of its hosting process),Service并不是一个新的线程,也不是新的进程。
也就是说,若您需要在Service中执行较为耗时的操作(如播放音乐、执行网络请求等),需要在Service中创建一个新的线程。这可以防止ANR的发生,同时主线程可以执行正常的UI操作

使用Service还是使用Thread?

Service是一个运行在后台的组件,并不与用户交互。您仅在需要的时候创建Service( create a service only if that is what you need)。
当用户正在与UI交互时,需要执行一些主线程无法完成的工作,应当创建一个线程。例如当activity正在运行时,需要播放音乐,此时需要在Activity的onCreate()中创建线程并在onStart()中开启。最后在onStop()中停止。您也可以考虑使用AsyncTask 或 HandlerThread来替代Thread创建线程

四大方法

为了创建Service,需要继承Service类。并重写它的回调方法,这些回调方法反应了Service的生命周期,并提供了绑定Service的机制。最重要的Service的生命周期回调方法如下所示:

  • onStartCommand():当其他组件调用startService()方法请求启动Service时,该方法被回调。一旦Service启动,它会在后台独立运行。当Service执行完以后,需调用stopSelf() 或 stopService()方法停止Service。(若您只希望bind Service,则无需调用这些方法)

  • onBind():当其他组件调用bindService()方法请求绑定Service时,该方法被回调。该方法返回一个IBinder接口,该接口是Service与绑定的组件进行交互的桥梁。若Service未绑定其他组件,该方法应返回null。

  • onCreate():当Service第一次创建时,回调该方法。该方法只被回调一次,并在onStartCommand() 或 onBind()方法被回调之前执行。若Service处于运行状态,该方法不会回调。

  • onDestroy():当Service被销毁时回调,在该方法中应清除一些占用的资源,如停止线程、接触绑定注册的监听器或broadcast receiver 等。该方法是Service中的最后一个回调。

如果某个组件通过调用startService()启动了Service(系统会回调onStartCommand()方法),那么直到在Service中手动调用stopSelf()方法、或在其他组件中手动调用stopService()方法,该Service才会停止

如果某个组件通过调用bindService()绑定了Service(系统不会回调onStartCommand()方法),只要该组件与Service处于绑定状态,Service就会一直运行,当Service不再与组件绑定时,该Service将被destroy。

当系统内存低时,系统将强制停止Service的运行;若Service绑定了正在与用户交互的activity,那么该Service将不大可能被系统kill( less likely to be killed)。如果创建的是前台Service,那么该Service几乎不会被kill(almost never be killed)。否则,当创建了一个长时间在后台运行的Service后,系统会降低该Service在后台任务栈中的级别——这意味着它容易被kill(lower its position in the list of background tasks over time and the service will become highly susceptible to killing),所以在开发Service时,需要使Service变得容易被restart,因为一旦Service被kill,再restart它需要其资源可用时才行(restarts it as soon as resources become available again ),当然这也取决于onStartCommand()方法返回的值

向用户发送通知

运行中的Service可以通过Toast Notifications 或 Status Bar Notifications 向用户发送通知。Toast是一个可以短时间弹出的提醒框。二Status Bar是顶部状态栏中出现的太有图标的信息,用户可以通过下拉状态栏获得具体信息并执行某些操作(如启动Activity)。

通常,Status Bar用于通知某些操作已经完成,如下载文件完成。当用户下拉状态栏后,点击该通知,可获取详细内容,如查看该下载的文件

0 0
原创粉丝点击