Android中各种Service

作者 : 开心源码 本文共3182个字,预计阅读时间需要8分钟 发布时间: 2022-05-12 共175人阅读

1. 后端服务

后端服务分为可交互服务和不可交互服务。其区别在于启动服务的方式StartService()bindService()。后者会返回Bind对象供Service中方法和解决结果,而前者不会。

1.1 不可交互服务

三个方法:

  1. onCreate,用于初始化服务,只会被调用一次。
  2. onStartService,用于执行任务,每次调用Context.startService(context,Service.class)都会调用。
  3. onDestory,调用Context.stopService(context,Service.class)结束服务的时候调用。
public class NoInterrationService extends Service {    @Nullable    @Override    public IBinder onBind(Intent intent) {        Log.d("Service","onBind");        return null;    }    @Override    public void onCreate() {        super.onCreate();        Log.d("Service","onCreate");    }    @Override    public int onStartCommand(Intent intent, int flags, int startId) {        Log.d("Service","onStartCommand");        new Thread(new Runnable() {            @Override            public void run() {                // 耗时操作            }        }).start();        return super.onStartCommand(intent, flags, startId);    }    @Override    public void onDestroy() {        Log.d("Service","onDestroy");        super.onDestroy();    }}

无交互服务的生命周期

1.2 可交互服务

利用ConnectionService类和Service交互。
启动可交互服务bindService(new Intent(getApplicationContext(), InteractionService.class), connection, BIND_AUTO_CREATE);。三个参数,intent用于指定要启动的服务名称,ServiceConnection用于交互,Flag设置服务类型。

可交互服务执行流程

ServiceConnection :

    ServiceConnection connection = new ServiceConnection() {        @Override        public void onServiceConnected(ComponentName name, IBinder service) {            Log.d("Service", "onServiceConnected");            InteractionService.MyBinder binder = (InteractionService.MyBinder) service;            binder.func1();            unbindService(this); //关闭服务        }        @Override        public void onServiceDisconnected(ComponentName name) {        }    };
}public class InteractionService extends Service {    @Override    public void onCreate() {        super.onCreate();        Log.d("Service", "onCreate");    }    @Nullable    @Override    public IBinder onBind(Intent intent) {        Log.d("Service", "onBind");        return new MyBinder();    }    class MyBinder extends Binder {        public void func1() {            Log.d("Service", "func1");            Log.d("Service", "thread id " + Thread.currentThread().getId());        }    }    @Override    public boolean onUnbind(Intent intent) {        Log.d("Service", "onUnBind");        return super.onUnbind(intent);    }    @Override    public void onDestroy() {        Log.d("Service", "onDestroy");        super.onDestroy();    }}

服务的生命周期
从日志可见BindService并没有开启新的线程,但是有的时候我们 BindService之后并没有调用Binder中定义的func。是由于开启服务是异步的,并不会立即执行ServiceConnection.onServiceConnected()方法,我想内部实现应该是消息队列,将BindService操作发送给主线程的Looper,等待主线程解决这个消息的时候,再执行ServiceConnection.onServiceConnection中的方法。

2. 混合性交互的后端服务

或者许你会迷惑,startServicebindService之间有什么关系?其实简单的说两者之间是没有关联的,相似于你亲妈生了个双胞胎一样。混合使用,其完整的生命周期是:onCreate->onStartCommand->onBind->onUnBind->onDestroy

3. 前端服务

因为后端服务优先级相比照较低,当系统出现内存不足的情况下,它就有可能会被回收掉,所以前端服务就是来弥补这个缺点的,它可以一直保持运行状态而不被系统回收。例如:墨迹天气在状态栏中的天气预告

前端服务简单的前端服务实现

4. IntentService

IntentService是专门用来处理Service中不能执行耗时操作这一问题的,创立一个IntentService也很简单,只需继承IntentService并覆写onHandlerIntent函数,在该函数中即可以执行耗时操作了。

IntentService的具体实现将在下一遍文章中详情。

public class MyIntentService extends IntentService {    /**     * Creates an IntentService.  Invoked by your subclass's constructor.     *     * @param name Used to name the worker thread, important only for debugging.     */    public MyIntentService(String name) {        super(name);    }    @Override    protected void onHandleIntent(@Nullable Intent intent) {        // 解决耗时操作,已近开起来新的线程    }}

5. 系统服务

系统服务提供了很多便捷服务,可以查询Wifi、网络状态、查询电量、查询音量、查询包名、查询Application信息等等等相关多的服务,具体大家可以自信查询文档,这里举例2个常见的服务。
Wifi

WifiManager wm = (WifiManager) getSystemService(WIFI_SERVICE);boolean enabled = wm.isWifiEnabled();

最大音量

AudioManager am = (AudioManager) getSystemService(AUDIO_SERVICE);int max = am.getStreamMaxVolume(AudioManager.STREAM_SYSTEM);

说明
1. 本站所有资源来源于用户上传和网络,如有侵权请邮件联系站长!
2. 分享目的仅供大家学习和交流,您必须在下载后24小时内删除!
3. 不得使用于非法商业用途,不得违反国家法律。否则后果自负!
4. 本站提供的源码、模板、插件等等其他资源,都不包含技术服务请大家谅解!
5. 如有链接无法下载、失效或广告,请联系管理员处理!
6. 本站资源售价只是摆设,本站源码仅提供给会员学习使用!
7. 如遇到加密压缩包,请使用360解压,如遇到无法解压的请联系管理员
开心源码网 » Android中各种Service

发表回复