Service小结

来源:互联网 发布:兰州网络机柜 编辑:程序博客网 时间:2024/06/06 08:42

1 什么是服务

服务用于执行不需要和用户交互,而且长期运行的任务。但它并不是运行在独立的进程中,而且会依赖于创建服务时所在的应用程序进程。也就是说一个应用开启了服务,应用只要在后台运行,服务就在;而应用退出,服务也随之结束。服务是单例的。


2 如何使用

2.1 定义

新建一个类继承Service即可。

2.2 生命周期

onCreate():创建服务时调用;
onBind():以bindService方式启动服务调用,不会重复调用;
onStartCommand():每次以startService方式启动服务调用;
onDestroy():服务销毁时调用。

2.3 启动与停止

一种是借助Intent,调用startService(intent)进行启动服务;调用StopService(intent)销毁服务;这2个方法都是在Context类中使用的。在Service类中调用stopSelf也是可以停止服务的。

另一种启动服务是使用bindService和unbindService,同样也是借助Intent在Context类进行调用,不同的是在该启动服务方式下,还需要借助ServiceConnection类对象(该对象的使用在Binder的使用中介绍)。

需要注意的是,如果一个服务被上述两者方法进行了调用,那么也必须通过2种停止方法方可销毁该服务。

2.4 Binder的使用

前提:启动方式为bindService。
在继承Service时,onBind()方法是必须重写的,它主要的作用适用于Service和Activity的通信交互。
通常的做法是自定义一个内部类继承Binder,内部写好相关的方法等,而后在onBind方法中进行返回其实例。
而后在启动服务的ServiceConnection中onServiceConnected()方法进行接收(第二个参数进行强转即可),随即就可以运用该对象调用其方法进行通信。

2.5 IntentService使用

IntentService是一种特殊的Service,它的onHandleIntent()方法就是一个子线程,同时在服务结束后,会自动销毁,可以有效的避免ANR和忘记关闭服务。
用法与Service差不多,也是继承IntentService,然后无参构造,调用父类,在onHandleIntent()实现业务。
示例代码:

public MyIntentService() {// 无参构造调用父类    super("MyIntentService");}@Overrideprotected void onHandleIntent(Intent intent) {//已经在子线程中运行    // 打印当前线程的id--业务实现    Log.d(TAG, "Thread id is " + Thread.currentThread().getId());}

3 其他

3.1 前台服务

服务会因系统内存不足而被回收,为避免如此,可以使用前台服务。具体方法是在Service类的onCreate()方法中构建Notification对象,再通过startDoreground()方法变成一个前台服务,并在系统状态栏显示出来。
示例代码如下:

/** 变为前台服务,避免内存不足被回收 */Notification notification =    new Notification(R.drawable.ic_launcher, "Test...", System.currentTimeMillis());Intent notificationIntent = new Intent(this, MainActivity.class);PendingIntent pendingIntent = PendingIntent.getActivity(this, 0, notificationIntent, 0);notification.setLatestEventInfo(this, "标题", "内容", pendingIntent);startForeground(1, notification);

3.2 心跳服务

心跳服务中的定时机制有2种,一种是Java API提供的Timer类,一种是Android的Alarm机制。推荐使用Alarm机制,因为手机的休眠策略会让CPU进入睡眠状态,进而导致Timer的任务无法执行。
Alarm机制的使用:
获取到了AlarmManager 的实例,然后定义任务的触发时间为若干时间后,再使用 PendingIntent 指定处
理定时任务的广播接收器为 AlarmReceiver(再次启动服务),最后调用 set()方法完成设定。
示例代码如下:

Service类:

AlarmManager manager=(AlarmManager)getSystemService(ALARM_SERVICE);int time=3*1000;//3秒数long triggerAtTime=SystemClock.elapsedRealtime()+time;Intent i=new Intent(this,AlarmReceiver.class);PendingIntent pi=PendingIntent.getBroadcast(this, 0, i, 0);manager.set(AlarmManager.ELAPSED_REALTIME_WAKEUP, triggerAtTime, pi);

Receiver类:

@Override public void onReceive(Context context, Intent intent) {Intent i = new Intent(context, LongRunningService.class);context.startService(i);}
0 0
原创粉丝点击